feat: token 令牌
This commit is contained in:
1 parent
a2ee53f83a
commit
ec0e6867ee
12 files changed
+408
-7
No files matched your search
@@ -0,0 +1,44 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { TokenCreateRequest } from '../dto/token-create.request';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { TokenVo } from '../vo/TokenVo';
|
||||
import { JWT_SECRET } from '../constants/jwt';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async createToken(tokenCreateRequest: TokenCreateRequest) {
|
||||
// 验证用户信息和密码
|
||||
const user = await this.userService.findByUserName(
|
||||
tokenCreateRequest.username,
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
}
|
||||
// 验证密码
|
||||
const isPasswordValid = await bcrypt.compare(
|
||||
tokenCreateRequest.password,
|
||||
user.encryptedPassword,
|
||||
);
|
||||
if (!isPasswordValid) {
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
}
|
||||
const payload = { sub: user.id, username: user.username }; // payload 中包含用户 ID 和用户名
|
||||
const tokenVo = new TokenVo();
|
||||
try {
|
||||
tokenVo.token = await this.jwtService.signAsync(payload, {
|
||||
secret: JWT_SECRET,
|
||||
});
|
||||
} catch (e) {
|
||||
throw new UnauthorizedException('token生成失败');
|
||||
}
|
||||
return tokenVo;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user