๐Ÿ“ฆ cityzenKIM / toy_project_board

๐Ÿ“„ auth.controller.ts ยท 77 lines
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
77import {
  Body,
  Controller,
  HttpStatus,
  Logger,
  Post,
  Req,
  Res,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { JwtAuthGuard } from './jwt/jwt-auth.guard';
import { LoginRequestDto } from './dto/login-request.dto';

@ApiTags('AUTH')
@Controller('api/auth')
export class AuthController {
  private readonly logger = new Logger('AuthControllerLogger');
  constructor(private readonly authService: AuthService) {}

  @ApiOperation({ summary: '๋กœ๊ทธ์ธ' })
  @Post('login')
  async login(@Body() data: LoginRequestDto, @Res() res: Response) {
    const user = await this.authService.validateUser(data.email, data.password);
    const { accessToken, refreshToken } = await this.authService.generateTokens(
      user,
    );

    res.cookie('refresh_token', refreshToken, {
      httpOnly: true,
      secure: true,
    });

    return res.status(HttpStatus.OK).json({
      statusCode: 200,
      message: '๋กœ๊ทธ์ธ ์„ฑ๊ณต',
      accessToken,
    });
  }

  @ApiOperation({ summary: '๋กœ๊ทธ์•„์›ƒ' })
  @UseGuards(JwtAuthGuard)
  @Post('logout')
  async logout(@Res() res: Response) {
    res.clearCookie('refresh_token', {
      httpOnly: true,
      secure: true,
    });
    return res.status(HttpStatus.OK).json({
      statusCode: 200,
      message: '๋กœ๊ทธ์•„์›ƒ ์„ฑ๊ณต',
    });
  }

  @ApiOperation({ summary: 'ํ† ํฐ ์žฌ๋ฐœ๊ธ‰' })
  @Post('refresh')
  async refreshToken(@Req() req, @Res() res: Response) {
    const refreshToken = req.cookies['refresh_token'];

    if (!refreshToken) {
      throw new UnauthorizedException('ํ† ํฐ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.');
    }
    const newTokens = await this.authService.refreshToken(refreshToken);
    res.cookie('refresh_token', newTokens.refreshToken, {
      httpOnly: true,
      secure: true, // HTTPS ์‚ฌ์šฉ ์‹œ์—๋งŒ true
    });
    return res.status(HttpStatus.OK).json({
      statusCode: 200,
      accesToken: newTokens.accessToken,
    });
  }
}