All files / auth auth.controller.ts

100% Statements 40/40
100% Branches 2/2
100% Functions 10/10
100% Lines 38/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 1631x                   1x 1x 1x   1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x         1x   12x 12x         7x 7x 4x   4x 4x   3x       3x                   1x                       1x 3x                 1x                       1x 2x                 1x                       1x 2x                               1x       1x                                   1x       1x      
import {
  Controller,
  Get,
  HttpStatus,
  Post,
  Req,
  Res,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { blancLogger } from 'blanc-logger';
import { Request, Response } from 'express';
import { AuthService } from 'src/auth/auth.service';
import { ApiAuthPostUserLogoutResponseDto } from 'src/auth/dto/api-auth-post-user-logout-response.dto';
import { ApiAuthPostUserRefreshRequestDto } from 'src/auth/dto/api-auth-post-user-refresh-request.dto';
import { ApiAuthPostUserRefreshResponseDto } from 'src/auth/dto/api-auth-post-user-refresh-response.dto';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
import { GoogleRequest, KakaoRequest, NaverRequest } from 'src/auth/interfaces/auth.interface';
import { ERROR } from 'src/commons/constants/error';
import { ApiExceptionResponse } from 'src/commons/decorators/api-exception-response.decorator';
import { ApiSuccessResponse } from 'src/commons/decorators/api-success-response.decorator';
import { CurrentUser } from 'src/commons/decorators/user.decorator';
import { getFrontendUrl } from 'src/commons/helpers/frontend-redirect.helper';
import { ConfigService } from 'src/config/config.service';
import { UserDto } from 'src/user/dto/user.dto';
 
@ApiTags('계정')
@Controller('/api/auth')
@Controller()
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly configService: ConfigService,
  ) {}
 
  /** 소셜 로그인 Callback 처리 메서드 */
  private async handleSocialLoginCallback(req: Request, res: Response, provider: string) {
    try {
      const result = await this.authService.handleSocialLogin(req, res, provider);
      const frontendUrl = getFrontendUrl(req.headers.referer || '', this.configService);
 
      blancLogger.log(`${provider} login success for [${req.user}]`, 'AuthController');
      res.redirect(`${frontendUrl}/?token=${result.access_token}`);
    } catch (e) {
      blancLogger.error(`Error in ${provider} login for [${req.user}]: ${e.message}`, {
        moduleName: 'AuthController',
        stack: e.stack,
      });
      throw new UnauthorizedException(ERROR.AUTHENTICATION);
    }
  }
 
  @Get('/login/google')
  @ApiOperation({
    summary: '구글 로그인',
    description: '구글 로그인 요청',
  })
  @UseGuards(AuthGuard('google'))
  async googleAuth(@Req() _req: Request) {}
 
  @Get('/google/callback')
  @UseGuards(AuthGuard('google'))
  @ApiOperation({
    summary: '구글 로그인 콜백',
    description: 'referer를 기반으로 프론트엔드 리다이렉션 URL을 결정',
  })
  @ApiExceptionResponse([ERROR.AUTHENTICATION], {
    description: '구글 로그인 실패',
    status: HttpStatus.UNAUTHORIZED,
  })
  async googleCallback(@Req() req: GoogleRequest, @Res() res: Response) {
    return this.handleSocialLoginCallback(req, res, 'google');
  }
 
  @Get('/login/kakao')
  @ApiOperation({
    summary: '카카오 로그인',
    description: '카카오 로그인 요청',
  })
  @UseGuards(AuthGuard('kakao'))
  async kakaoAuth(@Req() _req: Request) {}
 
  @Get('/kakao/callback')
  @UseGuards(AuthGuard('kakao'))
  @ApiOperation({
    summary: '카카오 로그인 콜백',
    description: 'referer를 기반으로 프론트엔드 리다이렉션 URL을 결정',
  })
  @ApiExceptionResponse([ERROR.AUTHENTICATION], {
    description: '카카오 로그인 실패',
    status: HttpStatus.UNAUTHORIZED,
  })
  async kakaoCallback(@Req() req: KakaoRequest, @Res() res: Response) {
    return this.handleSocialLoginCallback(req, res, 'kakao');
  }
 
  @Get('/login/naver')
  @ApiOperation({
    summary: '네이버 로그인',
    description: '네이버 로그인',
  })
  @UseGuards(AuthGuard('naver'))
  async naverAuth(@Req() _req: Request) {}
 
  @Get('/naver/callback')
  @UseGuards(AuthGuard('naver'))
  @ApiOperation({
    summary: '네이버 로그인 콜백',
    description: 'referer를 기반으로 프론트엔드 리다이렉션 URL을 결정',
  })
  @ApiExceptionResponse([ERROR.AUTHENTICATION], {
    description: '네이버 로그인 실패',
    status: HttpStatus.UNAUTHORIZED,
  })
  async naverCallback(@Req() req: NaverRequest, @Res() res: Response) {
    return this.handleSocialLoginCallback(req, res, 'naver');
  }
 
  @Post('/refresh')
  @ApiOperation({
    summary: '로그인 연장',
    description: '토큰 리프레시',
  })
  @ApiSuccessResponse(ApiAuthPostUserRefreshResponseDto, {
    description: '로그인 연장 성공',
    status: HttpStatus.CREATED,
  })
  @ApiExceptionResponse([ERROR.AUTHENTICATION], {
    description: '로그인 연장 실패',
    status: HttpStatus.UNAUTHORIZED,
  })
  async silentRefresh(
    @Req() req: ApiAuthPostUserRefreshRequestDto,
    @Res({ passthrough: true }) res: Response,
  ): Promise<ApiAuthPostUserRefreshResponseDto> {
    return this.authService.silentRefresh(req, res);
  }
 
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('access-token')
  @Post('/logout')
  @ApiOperation({
    summary: '로그아웃',
    description: '로그아웃 요청',
  })
  @ApiSuccessResponse(ApiAuthPostUserLogoutResponseDto, {
    description: '로그아웃 성공',
    status: HttpStatus.CREATED,
  })
  @ApiExceptionResponse([ERROR.AUTHENTICATION], {
    description: '로그아웃 실패',
    status: HttpStatus.UNAUTHORIZED,
  })
  async logout(
    @Res({ passthrough: true }) res: Response,
    @CurrentUser() user: UserDto,
  ): Promise<ApiAuthPostUserLogoutResponseDto> {
    return this.authService.logout(user, res);
  }
}