-
Notifications
You must be signed in to change notification settings - Fork 228
/
auth.controller.ts
72 lines (63 loc) · 1.72 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
import { Controller, Get, Post, UseGuards, Req, Res, UnauthorizedException, Body } from '@nestjs/common';
import type { Request, Response } from 'express';
import {
AuthService,
LocalLoginGuard,
Payload,
AuthenticatedGuard,
LocalAuthGuard,
JwtAuthGuard,
JwtSign,
JwtVerifyGuard,
} from '../../auth';
import { ReqUser } from '../../common';
/**
* https://docs.nestjs.com/techniques/authentication
*/
@Controller()
export class AuthController {
constructor(private auth: AuthService) {}
/**
* See test/e2e/local-auth.spec.ts
* need username, password in body
* skip guard to @Public when using global guard
*/
@Post('login')
@UseGuards(LocalLoginGuard)
public login(@ReqUser() user: Payload): Payload {
return user;
}
@Get('logout')
public logout(@Req() req: Request, @Res() res: Response): void {
req.logout(() => {
res.redirect('/');
});
}
@Get('check')
@UseGuards(AuthenticatedGuard)
public check(@ReqUser() user: Payload): Payload {
return user;
}
/**
* See test/e2e/jwt-auth.spec.ts
*/
@UseGuards(LocalAuthGuard)
@Post('jwt/login')
public jwtLogin(@ReqUser() user: Payload): JwtSign {
return this.auth.jwtSign(user);
}
@UseGuards(JwtAuthGuard)
@Get('jwt/check')
public jwtCheck(@ReqUser() user: Payload): Payload {
return user;
}
// Only verify is performed without checking the expiration of the access_token.
@UseGuards(JwtVerifyGuard)
@Post('jwt/refresh')
public jwtRefresh(@ReqUser() user: Payload, @Body('refresh_token') token?: string): JwtSign {
if (!token || !this.auth.validateRefreshToken(user, token)) {
throw new UnauthorizedException('InvalidRefreshToken');
}
return this.auth.jwtSign(user);
}
}