| 21 | |
| 22 | @Controller("auth") |
| 23 | export class AuthController { |
| 24 | constructor( |
| 25 | private auth: AuthService, |
| 26 | @Inject(AUTH_CONFIG) private cfg: AuthConfig, |
| 27 | ) {} |
| 28 | |
| 29 | private setRefreshCookie(res: Response, token: string) { |
| 30 | res.cookie(COOKIE, token, { |
| 31 | httpOnly: true, |
| 32 | secure: this.cfg.cookieSecure, |
| 33 | sameSite: "lax", |
| 34 | maxAge: this.cfg.refreshTtlSec * 1000, |
| 35 | path: COOKIE_PATH, |
| 36 | }); |
| 37 | } |
| 38 | |
| 39 | @Public() |
| 40 | @Post("register") |
| 41 | @HttpCode(200) |
| 42 | register(@Body() body: { email?: string; password?: string }, @Res({ passthrough: true }) res: Response) { |
| 43 | const r = this.auth.register(body?.email, body?.password); |
| 44 | this.setRefreshCookie(res, r.refreshToken); |
| 45 | return { user: r.user, accessToken: r.accessToken, refreshToken: r.refreshToken }; |
| 46 | } |
| 47 | |
| 48 | @Public() |
| 49 | @Post("login") |
| 50 | @HttpCode(200) |
| 51 | login(@Body() body: { email?: string; password?: string }, @Res({ passthrough: true }) res: Response) { |
| 52 | const r = this.auth.login(body?.email, body?.password); |
| 53 | this.setRefreshCookie(res, r.refreshToken); |
| 54 | return { user: r.user, accessToken: r.accessToken, refreshToken: r.refreshToken }; |
| 55 | } |
| 56 | |
| 57 | @Public() |
| 58 | @Post("refresh") |
| 59 | @HttpCode(200) |
| 60 | refresh(@Req() req: Request, @Body() body: { refreshToken?: string }, @Res({ passthrough: true }) res: Response) { |
| 61 | const rt = body?.refreshToken ?? readCookie(req, COOKIE); |
| 62 | const r = this.auth.refresh(rt); |
| 63 | this.setRefreshCookie(res, r.refreshToken); |
| 64 | return { accessToken: r.accessToken, refreshToken: r.refreshToken }; |
| 65 | } |
| 66 | |
| 67 | @Public() |
| 68 | @Post("logout") |
| 69 | @HttpCode(200) |
| 70 | logout(@Req() req: Request, @Body() body: { refreshToken?: string }, @Res({ passthrough: true }) res: Response) { |
| 71 | this.auth.logout(body?.refreshToken ?? readCookie(req, COOKIE)); |
| 72 | res.clearCookie(COOKIE, { path: COOKIE_PATH }); |
| 73 | return { ok: true }; |
| 74 | } |
| 75 | |
| 76 | @Get("me") |
| 77 | me(@CurrentUser() user: AuthUser) { |
| 78 | return this.auth.me(user.id); |
| 79 | } |
| 80 | } |