Skip to content

Commit

Permalink
[NDD-356]: 로깅 기능 추가 && 토큰 관련 이슈 해결(이제 그만좀) (5h / 2h) (#204)
Browse files Browse the repository at this point in the history
* fix: 토큰의 무한 401케이스 에러 해결

* feat: 미들웨어에서 캐시 제어와 요청 url에 대한 로깅을 처리하는 기능 구현

* refactor: no-cache제거

* refactor: CORS methods 수정 && /api/member, /api/auth/reissue에서 캐시를 받지 않도록 수정

* feat: 에러케이스에 대한 로깅 기능 구현
  • Loading branch information
JangAJang authored Dec 14, 2023
1 parent 5b3356a commit 3ded775
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 8 deletions.
1 change: 1 addition & 0 deletions BE/src/config/cors.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export const CORS_CONFIG: CorsOptions = {
origin: CORS_ORIGIN,
credentials: true,
exposedHeaders: CORS_HEADERS,
methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTION', 'HEADER'],
};
4 changes: 3 additions & 1 deletion BE/src/constant/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,7 @@ export const INTERNAL_SERVER_ERROR = 500;

export const ACCESS_TOKEN_EXPIRES_IN = process.env.ACCESS_TOKEN_EXPIRES_IN; // 1 시간
export const REFRESH_TOKEN_EXPIRES_IN = process.env.REFRESH_TOKEN_EXPIRES_IN; // 7 일

export const NO_CACHE_URL = ['/api/member', '/api/auth/reissue'];
export const HOUR_IN_SECONDS = 60 * 60;
export const WEEK_IN_SECONDS = 60 * 60 * 24 * 7;
export const WEEK_IN_SECONDS = 60 * 60 * 24 * 7;
12 changes: 12 additions & 0 deletions BE/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,28 @@ import { setupSwagger } from './config/swagger.config';
import { CORS_CONFIG } from './config/cors.config';
import * as cookieParser from 'cookie-parser';
import { initializeTransactionalContext } from 'typeorm-transactional';
import { LoggerService } from './config/logger.config';
import { NO_CACHE_URL } from './constant/constant';

async function bootstrap() {
initializeTransactionalContext();
const app = await NestFactory.create(AppModule, {
abortOnError: true,
});
const expressApp = app.getHttpAdapter().getInstance();
const logger = new LoggerService('traffic');
app.use(cookieParser());
app.useGlobalPipes(new ValidationPipe());
app.enableCors(CORS_CONFIG);
setupSwagger(app);
// 캐시 제어 미들웨어 등록
expressApp.use((req, res, next) => {
if (NO_CACHE_URL.includes(req.url)) {
res.setHeader('Cache-Control', 'no-cache');
}
logger.info(req.url);
next();
});
await app.listen(8080, '0.0.0.0');
}

Expand Down
8 changes: 7 additions & 1 deletion BE/src/token/guard/token.hard.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { TokenService } from '../service/token.service';
import { getTokenValue } from 'src/util/token.util';
import { isEmpty } from 'class-validator';
import { InvalidTokenException } from '../exception/token.exception';

@Injectable()
export class TokenHardGuard extends AuthGuard('jwt') {
Expand All @@ -13,6 +15,10 @@ export class TokenHardGuard extends AuthGuard('jwt') {
const request = context.switchToHttp().getRequest();
const token = getTokenValue(request);

if (isEmpty(token)) {
throw new InvalidTokenException();
}

try {
request.user = await this.validateToken(token);
return true;
Expand All @@ -22,6 +28,6 @@ export class TokenHardGuard extends AuthGuard('jwt') {
}

private async validateToken(token: string) {
return this.tokenService.findMemberByToken(token, true);
return await this.tokenService.findMemberByToken(token, true);
}
}
2 changes: 1 addition & 1 deletion BE/src/token/service/token.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class TokenService {
throw new NeedToLoginException();
}

return this.updateToken(accessToken, refreshToken);
return await this.updateToken(accessToken, refreshToken);
}

async getPayload(singleToken: string) {
Expand Down
4 changes: 4 additions & 0 deletions BE/src/util/exception.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ import {
NOT_FOUND,
UNAUTHORIZED,
} from '../constant/constant';
import { LoggerService } from '../config/logger.config';

const errorLogger = new LoggerService('ERROR');

class HttpCustomException extends HttpException {
constructor(message: string, errorCode: string, status: number) {
super({ message: message, errorCode: errorCode }, status);
errorLogger.error(errorCode, super.stack);
}
}

Expand Down
6 changes: 1 addition & 5 deletions BE/src/util/token.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@ export const getTokenValue = (request: Request) => {
return request.cookies['accessToken'].split(' ').pop();
}

if (request.get('cookie')) {
return request.get('cookie').split('Bearer ').pop();
}

return '';
return null;
};

export const validateManipulatedToken = (member: Member | undefined) => {
Expand Down

0 comments on commit 3ded775

Please sign in to comment.