Files
certd/packages/ui/certd-server/src/modules/login/service/login-service.ts
T

72 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-07-15 00:30:33 +08:00
import { Config, Inject, Provide } from '@midwayjs/core';
import { UserService } from '../../sys/authority/service/user-service.js';
2024-07-15 00:30:33 +08:00
import jwt from 'jsonwebtoken';
2024-10-03 22:03:49 +08:00
import { CommonException } from '@certd/lib-server';
import { RoleService } from '../../sys/authority/service/role-service.js';
import { UserEntity } from '../../sys/authority/entity/user.js';
2024-10-03 22:03:49 +08:00
import { SysSettingsService } from '@certd/lib-server';
import { SysPrivateSettings } from '@certd/lib-server';
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-06-28 09:44:35 +08:00
@Config('auth.jwt')
2023-01-29 13:44:19 +08:00
private jwt: any;
2024-08-27 13:46:19 +08:00
@Inject()
sysSettingsService: SysSettingsService;
2023-01-29 13:44:19 +08:00
/**
* login
*/
async login(user) {
console.assert(user.username != null, '用户名不能为空');
const info = await this.userService.findOne({ username: user.username });
if (info == null) {
throw new CommonException('用户名或密码错误');
}
2024-07-15 00:30:33 +08:00
const right = await this.userService.checkPassword(user.password, info.password, info.passwordVersion);
2023-01-29 13:44:19 +08:00
if (!right) {
throw new CommonException('用户名或密码错误');
}
2024-10-27 00:04:02 +08:00
if (info.status === 0) {
throw new CommonException('用户已被禁用');
}
2023-01-29 13:44:19 +08:00
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;
2024-08-27 13:46:19 +08:00
const setting = await this.sysSettingsService.getSetting<SysPrivateSettings>(SysPrivateSettings);
const jwtSecret = setting.jwtKey;
const token = jwt.sign(tokenInfo, jwtSecret, {
2023-01-29 13:44:19 +08:00
expiresIn: expire,
});
return {
token,
expire,
};
}
}