forked from wangziqi/gongxue-base
feat(rbac): add RbacController with role CRUD, permissions tree, and user management endpoints
This commit is contained in:
@@ -262,4 +262,70 @@ export class RbacService {
|
||||
}
|
||||
return Array.from(codes);
|
||||
}
|
||||
|
||||
// ---- 用户管理 ----
|
||||
|
||||
async findAllUsers() {
|
||||
const users = await this.userRepo.find({
|
||||
relations: ['roles'],
|
||||
order: { createdAt: 'DESC' },
|
||||
});
|
||||
return users.map(u => ({
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
name: u.name,
|
||||
isActive: u.isActive,
|
||||
lastLoginAt: u.lastLoginAt,
|
||||
createdAt: u.createdAt,
|
||||
updatedAt: u.updatedAt,
|
||||
roles: u.roles?.map(r => ({ id: r.id, name: r.name })) || [],
|
||||
}));
|
||||
}
|
||||
|
||||
async createUser(dto: { username: string; password: string; name: string; roleIds?: number[] }) {
|
||||
const exists = await this.userRepo.findOne({ where: { username: dto.username } });
|
||||
if (exists) throw new Error('用户名已存在');
|
||||
const hash = await bcrypt.hash(dto.password, 10);
|
||||
const user = this.userRepo.create({ username: dto.username, passwordHash: hash, name: dto.name });
|
||||
if (dto.roleIds && dto.roleIds.length > 0) {
|
||||
user.roles = await this.roleRepo.findByIds(dto.roleIds);
|
||||
}
|
||||
await this.userRepo.save(user);
|
||||
return { message: '用户创建成功' };
|
||||
}
|
||||
|
||||
async updateUser(id: number, dto: { username?: string; name?: string; isActive?: boolean; roleIds?: number[] }) {
|
||||
const user = await this.userRepo.findOne({ where: { id }, relations: ['roles'] });
|
||||
if (!user) throw new Error('用户不存在');
|
||||
if (dto.username !== undefined && dto.username !== user.username) {
|
||||
const exists = await this.userRepo.findOne({ where: { username: dto.username } });
|
||||
if (exists) throw new Error('用户名已存在');
|
||||
user.username = dto.username;
|
||||
}
|
||||
if (dto.name !== undefined) user.name = dto.name;
|
||||
if (dto.isActive !== undefined) user.isActive = dto.isActive;
|
||||
if (dto.roleIds !== undefined) {
|
||||
user.roles = dto.roleIds.length > 0
|
||||
? await this.roleRepo.findByIds(dto.roleIds)
|
||||
: [];
|
||||
}
|
||||
await this.userRepo.save(user);
|
||||
return { message: '更新成功' };
|
||||
}
|
||||
|
||||
async resetPassword(id: number, newPassword: string) {
|
||||
const user = await this.userRepo.findOne({ where: { id } });
|
||||
if (!user) throw new Error('用户不存在');
|
||||
user.passwordHash = await bcrypt.hash(newPassword, 10);
|
||||
await this.userRepo.save(user);
|
||||
return { message: '密码已重置' };
|
||||
}
|
||||
|
||||
async deleteUser(id: number) {
|
||||
const user = await this.userRepo.findOne({ where: { id } });
|
||||
if (!user) throw new Error('用户不存在');
|
||||
if (user.username === 'admin') throw new Error('不能删除默认管理员');
|
||||
await this.userRepo.remove(user);
|
||||
return { message: '用户已删除' };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user