2023-01-29 13:44:19 +08:00
|
|
|
import { Config, Inject, Provide } from '@midwayjs/decorator';
|
|
|
|
|
import { UserService } from '../../authority/service/user-service';
|
|
|
|
|
import * as jwt from 'jsonwebtoken';
|
|
|
|
|
import { CommonException } from '../../../basic/exception/common-exception';
|
2023-06-27 09:29:43 +08:00
|
|
|
import { RoleService } from '../../authority/service/role-service';
|
|
|
|
|
import { UserEntity } from '../../authority/entity/user';
|
2023-01-29 13:44:19 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 系统用户
|
|
|
|
|
*/
|
|
|
|
|
@Provide()
|
|
|
|
|
export class LoginService {
|
|
|
|
|
@Inject()
|
|
|
|
|
userService: UserService;
|
2023-06-27 09:29:43 +08:00
|
|
|
@Inject()
|
|
|
|
|
roleService: RoleService;
|
2023-01-29 13:44:19 +08:00
|
|
|
@Config('biz.jwt')
|
|
|
|
|
private jwt: any;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* login
|
|
|
|
|
*/
|
|
|
|
|
async login(user) {
|
|
|
|
|
console.assert(user.username != null, '用户名不能为空');
|
|
|
|
|
const info = await this.userService.findOne({ username: user.username });
|
|
|
|
|
if (info == null) {
|
|
|
|
|
throw new CommonException('用户名或密码错误');
|
|
|
|
|
}
|
|
|
|
|
const right = this.userService.checkPassword(user.password, info.password);
|
|
|
|
|
if (!right) {
|
|
|
|
|
throw new CommonException('用户名或密码错误');
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-27 09:29:43 +08:00
|
|
|
const roleIds = await this.roleService.getRoleIdsByUserId(info.id);
|
|
|
|
|
return this.generateToken(info, roleIds);
|
2023-01-29 13:44:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 生成token
|
|
|
|
|
* @param user 用户对象
|
2023-06-27 09:29:43 +08:00
|
|
|
* @param roleIds
|
2023-01-29 13:44:19 +08:00
|
|
|
*/
|
2023-06-27 09:29:43 +08:00
|
|
|
async generateToken(user: UserEntity, roleIds: number[]) {
|
2023-01-29 13:44:19 +08:00
|
|
|
const tokenInfo = {
|
|
|
|
|
username: user.username,
|
|
|
|
|
id: user.id,
|
2023-06-27 09:29:43 +08:00
|
|
|
roles: roleIds,
|
2023-01-29 13:44:19 +08:00
|
|
|
};
|
|
|
|
|
const expire = this.jwt.expire;
|
|
|
|
|
const token = jwt.sign(tokenInfo, this.jwt.secret, {
|
|
|
|
|
expiresIn: expire,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
token,
|
|
|
|
|
expire,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|