返回 AiToEarn
auth.service.ts
根目录 / project / aitoearn-electron / server / src / auth / auth.service.ts
1 /*
2 * @Author: nevin
3 * @Date: 2022-01-21 09:42:13
4 * @LastEditors: nevin
5 * @LastEditTime: 2025-02-26 09:20:47
6 * @Description: 认证
7 */
8 import { Injectable, UnauthorizedException } from '@nestjs/common';
9 import { JwtService } from '@nestjs/jwt';
10 import { TokenInfo } from './interfaces/auth.interfaces';
11
12 @Injectable()
13 export class AuthService {
14 constructor(private readonly jwtService: JwtService) {}
15
16 /**
17 * 生成Token
18 * @param tokenInfo
19 * @returns
20 */
21 async generateToken(tokenInfo: TokenInfo): Promise<string> {
22 const payload: TokenInfo = {
23 phone: tokenInfo.phone,
24 id: tokenInfo.id,
25 name: tokenInfo.name,
26 isManager: tokenInfo.isManager,
27 };
28 return this.jwtService.sign(payload);
29 }
30
31 /**
32 * 重置Token
33 * @param tokenInfo
34 * @returns
35 */
36 async resetToken(tokenInfo: TokenInfo): Promise<string> {
37 const payload: TokenInfo = {
38 phone: tokenInfo.phone,
39 id: tokenInfo.id,
40 name: tokenInfo.name,
41 isManager: tokenInfo.isManager,
42 };
43 return this.jwtService.sign(payload);
44 }
45
46 async decodeToken(token: string): Promise<TokenInfo> {
47 token = token.replace('Bearer ', '');
48 try {
49 return this.jwtService.decode(token);
50 } catch (error) {
51 if (error.name === 'TokenExpiredError') {
52 throw new UnauthorizedException('Token已过期,请重新登录');
53 } else {
54 throw new UnauthorizedException('Token校验失败,请重新登录');
55 }
56 }
57 }
58 }
59
59 lines TYPESCRIPT