/
auth.controller.ts
96 lines (85 loc) · 2.25 KB
/
auth.controller.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import {
Body,
Controller,
Delete,
HttpCode,
HttpStatus,
Post,
Req,
Res,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { Public } from './auth.decorator';
import { AuthService } from './auth.service';
import { LoggerService } from '../../lib/modules/logger/logger.service';
@Controller('auth')
export class AuthController {
constructor(
private authService: AuthService,
private loggerService: LoggerService,
) {}
@Public()
@HttpCode(HttpStatus.OK)
@Post('login')
async signIn(
@Body() body: Record<string, any>,
@Res({ passthrough: true }) res: Response,
) {
const { email, password, rememberMe } = body;
const data = await this.authService.signIn(email, password);
if (rememberMe) {
this.setRefreshToken(res, data.refreshToken);
}
return { data };
}
@Public()
@HttpCode(HttpStatus.OK)
@Post('refresh')
async refreshToken(
@Req() request: Request,
@Body() body: Record<string, any>,
@Res({ passthrough: true }) response: Response,
): Promise<Record<string, any>> {
const refreshToken = this.extractTokenFromCookie(request);
try {
const { uuid } = body;
const result = await this.authService.verifyRefreshToken(uuid, {
uuid,
refreshToken,
});
if (!result) {
response.status(401);
return { message: 'invalid refresh token or uuid' };
}
this.setRefreshToken(response, result.refreshToken);
return { data: result };
} catch (e) {
response.status(401);
this.loggerService.logger.info(e);
return { message: e.message };
}
}
@Public()
@HttpCode(HttpStatus.OK)
@Delete('refresh')
async clearRefreshToken(@Res({ passthrough: true }) response: Response) {
this.removeRefreshToken(response);
}
private extractTokenFromCookie(request: Request): string | undefined {
return request.cookies.refreshToken;
}
private setRefreshToken(res: Response, token: string) {
res.cookie('refreshToken', token, {
secure: true,
httpOnly: true,
sameSite: 'none',
});
}
private removeRefreshToken(res: Response) {
res.cookie('refreshToken', {
secure: true,
httpOnly: true,
sameSite: 'none',
});
}
}