All files / auth auth.service.ts

100% Statements 58/58
100% Branches 5/5
100% Functions 5/5
100% Lines 55/55

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 1342x 2x 2x           2x 2x 2x         2x 2x   2x     2x   11x 11x               2x 2x 2x 2x   1x       1x         4x 4x 4x 1x     3x         3x 3x 1x 1x       2x 2x 1x     1x           1x   1x         3x       3x         3x 3x   2x 1x 1x 1x 1x   2x       2x         2x 2x 1x 1x     2x             2x 2x   2x 2x   2x   2x      
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { blancLogger } from 'blanc-logger';
import { isEmpty } from 'class-validator';
import { Request, Response } from 'express';
import * as jwt from 'jsonwebtoken';
import { ApiAuthPostUserLogoutResponseDto } from 'src/auth/dto/api-auth-post-user-logout-response.dto';
import { ApiAuthPostUserRefreshResponseDto } from 'src/auth/dto/api-auth-post-user-refresh-response.dto';
import { SocialUser } from 'src/auth/interfaces/auth.interface';
import { ERROR } from 'src/commons/constants/error';
import { verifyJWT } from 'src/commons/helpers/jwt.helper';
import {
  generateAccessToken,
  generateRefreshToken,
  setRefreshCookie,
} from 'src/commons/helpers/token.helper';
import { generateUUID } from 'src/commons/util/uuid';
import { ConfigService } from 'src/config/config.service';
import { UserDto } from 'src/user/dto/user.dto';
import { UserQueryRepository } from 'src/user/user.query.repository';
 
@Injectable()
export class AuthService {
  constructor(
    private readonly configService: ConfigService,
    private readonly userQueryRepository: UserQueryRepository,
  ) {}
 
  async handleSocialLogin(
    req: Request,
    res: Response,
    provider: string,
  ): Promise<{ access_token: string }> {
    try {
      const user = req.user as SocialUser;
      user.type = provider as SocialUser['type'];
      return await this.getOrCreateUserAuth(user, res);
    } catch (e) {
      blancLogger.error(`Error in handleSocialLogin for ${provider} : [${req.user}]`, {
        moduleName: 'AuthService',
        stack: e.stack,
      });
      throw new UnauthorizedException(ERROR.AUTHENTICATION);
    }
  }
 
  async silentRefresh(req: Request, res: Response): Promise<ApiAuthPostUserRefreshResponseDto> {
    try {
      const refreshToken = req.cookies.refresh_token;
      if (isEmpty(refreshToken)) {
        throw new UnauthorizedException(ERROR.AUTHENTICATION);
      }
 
      const decoded = await verifyJWT<jwt.JwtPayload>(
        refreshToken,
        this.configService.get('JWT_REFRESH_KEY'),
      );
 
      const userId = decoded.aud;
      if (isEmpty(userId)) {
        res.clearCookie('refresh_token');
        throw new UnauthorizedException(ERROR.AUTHENTICATION);
      }
 
      /** 로그아웃 후에는 Silent Refresh를 무시 */
      const loginUser = await this.userQueryRepository.findId(+userId);
      if (loginUser.refresh_token !== refreshToken) {
        throw new UnauthorizedException(ERROR.AUTHENTICATION);
      }
 
      const payload = {
        id: loginUser.id,
        uuid: loginUser.uuid,
        nickname: loginUser.name,
        profile_image: loginUser.profile_image,
      };
      const accessToken = generateAccessToken(payload, this.configService);
 
      return {
        ok: true,
        access_token: accessToken,
      };
    } catch (e) {
      blancLogger.error(`Error in silentRefresh: ${e.message}`, {
        moduleName: 'AuthService',
        stack: e.stack,
      });
      throw new UnauthorizedException(ERROR.AUTHENTICATION);
    }
  }
 
  async logout(user: UserDto, res: Response): Promise<ApiAuthPostUserLogoutResponseDto> {
    try {
      if (isEmpty(user.id)) throw new UnauthorizedException(ERROR.AUTHENTICATION);
 
      const loginUser = await this.userQueryRepository.findId(user.id);
      loginUser.refresh_token = null;
      await this.userQueryRepository.save(loginUser);
      res.clearCookie('refreshToken');
      return { ok: true };
    } catch (e) {
      blancLogger.error(`Error in logout for user [${user}]: ${e.message}`, {
        moduleName: 'AuthService',
        stack: e.stack,
      });
      throw new UnauthorizedException(ERROR.AUTHENTICATION);
    }
  }
 
  async getOrCreateUserAuth(user: SocialUser, res: Response): Promise<{ access_token: string }> {
    let findUser = await this.userQueryRepository.findUser(user);
    if (isEmpty(findUser)) {
      const uuid = generateUUID();
      findUser = await this.userQueryRepository.createUser(user, uuid);
    }
 
    const payload = {
      id: findUser.id,
      uuid: findUser.uuid,
      nickname: findUser.name,
      profile_image: findUser.profile_image,
    };
 
    const accessToken = generateAccessToken(payload, this.configService);
    const refreshToken = generateRefreshToken(findUser.id, this.configService);
 
    findUser.refresh_token = refreshToken;
    await this.userQueryRepository.save(findUser);
 
    setRefreshCookie(res, refreshToken, this.configService);
 
    return { access_token: accessToken };
  }
}