Skip to content

Commit

Permalink
refactor: 인증 중 BaseException 사용하도록 수정 #81
Browse files Browse the repository at this point in the history
  • Loading branch information
Miensoap committed Nov 9, 2024
1 parent c821a12 commit 7407bdf
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import { TokenExpiredError } from 'jsonwebtoken';
import { ConfigService } from '@nestjs/config';
import { AuthService } from './auth.service';
import { AuthenticationException } from './exception/AuthenticationException';

@Injectable()
export class JwtAuthGuard implements CanActivate {
private jwtSecretKey: string;
private authService: AuthService;
private readonly jwtSecretKey: string;

constructor(private configService: ConfigService) {
this.jwtSecretKey = this.configService.get<string>('JWT_SECRET_KEY');
Expand All @@ -22,7 +16,7 @@ export class JwtAuthGuard implements CanActivate {
const request = context.switchToHttp().getRequest();
const token = request.headers['authorization']?.split(' ')[1];
if (!token) {
throw new UnauthorizedException('토큰이 없습니다.');
throw new AuthenticationException('토큰이 없습니다.');
}
try {
request.user = jwt.verify(token, this.jwtSecretKey) as {
Expand All @@ -32,9 +26,9 @@ export class JwtAuthGuard implements CanActivate {
return true;
} catch (error) {
if (error instanceof TokenExpiredError) {
throw new UnauthorizedException('만료된 토큰입니다.');
throw new AuthenticationException('만료된 토큰입니다.');
}
throw new UnauthorizedException('유효하지 않은 토큰입니다.');
throw new AuthenticationException('유효하지 않은 토큰입니다.');
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export type googleTokenResponse = {
access_token: string;
refresh_token: string;
};

export type googleUserResponse = {
Expand Down
12 changes: 12 additions & 0 deletions backend/src/auth/exception/AuthenticationException.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { BaseException } from '../../common/exception/BaseException';
import { HttpStatus } from '@nestjs/common';

export class AuthenticationException extends BaseException {
constructor(message: string = '인증에 실패했습니다.') {
super({
code: 601,
message: message,
status: HttpStatus.UNAUTHORIZED,
});
}
}

0 comments on commit 7407bdf

Please sign in to comment.