AINTECH CODEaintech-auth-service
Search files... (Ctrl+P)
auth.service.ts
Button.tsx
utils.ts
aintech-auth-servicesrcservicesauth.service.ts
1import { Injectable, UnauthorizedException } from '@nestjs/common';
2import { JwtService } from '@nestjs/jwt';
3import { UserService } from './user.service';
4import { TokenPayload, AuthResponse } from '../types';
5 
6// Token refresh interval: 5 min before expiry
7const REFRESH_THRESHOLD = 5 * 60 * 1000;
8const MAX_RETRIES = 3;
9 
10/** Authentication service handling JWT tokens */
11@Injectable()
12export class AuthService {
13 private tokenCache = new Map<string, TokenPayload>();
14 
15 constructor(
16 private readonly jwtService: JwtService,
17 private readonly userService: UserService,
18 ) {}
19 
20 async validateUser(email: string, password: string): Promise<AuthResponse> {
21 const user = await this.userService.findByEmail(email);
22 if (!user || !await user.comparePassword(password)) {
23 throw new UnauthorizedException('Invalid credentials');
24 }
25 return this.generateTokens(user);
26 }
27 
28 async refreshToken(token: string): Promise<AuthResponse> {
29 try {
30 const payload = this.jwtService.verify<TokenPayload>(token);
31 const user = await this.userService.findById(payload.sub);
32 this.tokenCache.set(user.id, payload);
33 return this.generateTokens(user);
34 } catch {
35 throw new UnauthorizedException('Token expired');
36 }
37 }
38 
39 private async generateTokens(user: User): Promise<AuthResponse> {
40 const payload: TokenPayload = { sub: user.id, email: user.email };
41 const accessToken = this.jwtService.sign(payload, { expiresIn: '15m' });
42 const refreshToken = this.jwtService.sign(payload, { expiresIn: '7d' });
43 return { accessToken, refreshToken, user };
44 }
45}
$ npm run dev
 
AINTECH Code Server v2.4.0
Local: http://localhost:3000
Ready in 847ms
 
Compiled /api/auth in 234ms
Compiled /dashboard in 412ms
$
main M
Ln 20, Col 8Spaces: 2UTF-8TS1.5 KBPrettier