// src/service/user.service.ts import { Inject, Provide } from '@midwayjs/core'; import { InjectEntityModel } from '@midwayjs/typeorm'; import { Repository } from 'typeorm'; import * as bcrypt from 'bcryptjs'; import { JwtService } from '@midwayjs/jwt'; import { User } from '../entity/user.entity'; import { LoginResDTO } from '../dto/user.dto'; import { plainToInstance } from 'class-transformer'; @Provide() export class UserService { @InjectEntityModel(User) userModel: Repository; @Inject() jwtService: JwtService; async login(username: string, password: string): Promise { const user = await this.userModel.findOne({ where: { username, isActive: true }, }); if (!user || !(await bcrypt.compare(password, user.password))) { throw new Error('用户名或者密码错误'); } // 生成 JWT,包含角色和权限信息 const token = await this.jwtService.sign({ id: user.id, username: user.username, }); return { token, //role: user.role, username: user.username, userId: user.id, permissions: user.permissions, }; } async addUser(username: string, password: string) { const existingUser = await this.userModel.findOne({ where: { username }, }); if (existingUser) { throw new Error('用户已存在'); } const hashedPassword = await bcrypt.hash(password, 10); const user = this.userModel.create({ username, password: hashedPassword, }); return this.userModel.save(user); } async listUsers(current: number, pageSize: number) { const [items, total] = await this.userModel.findAndCount({ skip: (current - 1) * pageSize, take: pageSize, }); return { items, total, current, pageSize }; } async toggleUserActive(userId: number, isActive: boolean) { const user = await this.userModel.findOne({ where: { id: userId } }); if (!user) { throw new Error('User not found'); } user.isActive = isActive; return this.userModel.save(user); } async getUser(userId: number) { return plainToInstance( User, await this.userModel.findOne({ where: { id: userId } }) ); } }