forked from yoone/API
1
0
Fork 0
API/src/service/user.service.ts

80 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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<User>;
@Inject()
jwtService: JwtService;
async login(username: string, password: string): Promise<LoginResDTO> {
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 } })
);
}
}