-
Notifications
You must be signed in to change notification settings - Fork 0
[25.05.05 / TASK-182] Feature - middleware 인가 로직 전체 리펙토링, 그에 따른 대응 개발 #30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
89b29ca
feature: 인가 미들 웨어 분리, 인증 로직은 서비스로 합병, 그에 따른 타입을 포함한 전체 리펙토링
Nuung 8650263
feature: 미들웨어 자체 테스트 코드 추가, 그에 따른 velog api 유닛 테스트 추가
Nuung 60a4446
modify: 검증 완료
Nuung 4a37b62
modify: user me api 에서 username 때문에 외부 API 호출부분 추가
Nuung e6a1881
modify: SLACK_WEBHOOK_URL 이 왜 빠졌지? 추가
Nuung 1052e20
modify: 테스트 코드 피드백 반영, 리펙토링 (가독성, 가시성)
Nuung File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
export { CustomError } from './custom.exception'; | ||
export { DBError } from './db.exception'; | ||
export { TokenError, TokenExpiredError, InvalidTokenError } from './token.exception'; | ||
export { TokenError, TokenExpiredError, InvalidTokenError, QRTokenExpiredError, QRTokenInvalidError } from './token.exception'; | ||
export { UnauthorizedError } from './unauthorized.exception'; | ||
export { BadRequestError } from './badRequest.exception'; | ||
export { NotFoundError } from './notFound.exception'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
import { CustomError } from './custom.exception'; | ||
import { BadRequestError } from './badRequest.exception'; | ||
import { UnauthorizedError } from './unauthorized.exception'; | ||
|
||
export class TokenError extends CustomError { | ||
|
@@ -18,3 +19,19 @@ export class InvalidTokenError extends UnauthorizedError { | |
super(message, 'INVALID_TOKEN'); | ||
} | ||
} | ||
|
||
/* =================================================== | ||
아래 부터는 QRToken 에 관한 에러 | ||
=================================================== */ | ||
|
||
export class QRTokenExpiredError extends BadRequestError { | ||
constructor(message = 'QR 토큰이 만료되었습니다') { | ||
super(message, 'TOKEN_EXPIRED'); | ||
} | ||
} | ||
|
||
export class QRTokenInvalidError extends BadRequestError { | ||
constructor(message = '유효하지 않은 QR 토큰입니다') { | ||
super(message, 'INVALID_TOKEN'); | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. QR 토큰에 대한 에러는 UnauthorizedError가 아닌 BadRequestError가 확실히 더 적절하겠네요! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,213 @@ | ||
import { Request, Response } from 'express'; | ||
import { authMiddleware } from '@/middlewares/auth.middleware'; | ||
import pool from '@/configs/db.config'; | ||
|
||
// pool.query 모킹 | ||
jest.mock('@/configs/db.config', () => ({ | ||
query: jest.fn(), | ||
})); | ||
|
||
// logger 모킹 | ||
jest.mock('@/configs/logger.config', () => ({ | ||
error: jest.fn(), | ||
info: jest.fn(), | ||
})); | ||
|
||
describe('인증 미들웨어', () => { | ||
let mockRequest: Partial<Request>; | ||
let mockResponse: Partial<Response>; | ||
let nextFunction: jest.Mock; | ||
|
||
beforeEach(() => { | ||
// 테스트마다 request, response, next 함수 초기화 | ||
mockRequest = { | ||
body: {}, | ||
headers: {}, | ||
cookies: {}, | ||
}; | ||
mockResponse = { | ||
json: jest.fn(), | ||
status: jest.fn().mockReturnThis(), | ||
}; | ||
nextFunction = jest.fn(); | ||
}); | ||
|
||
afterEach(() => { | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
describe('verify', () => { | ||
const validToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYzc1MDcyNDAtMDkzYi0xMWVhLTlhYWUtYTU4YTg2YmIwNTIwIiwiaWF0IjoxNjAzOTM0NTI5LCJleHAiOjE2MDM5MzgxMjksImlzcyI6InZlbG9nLmlvIiwic3ViIjoiYWNjZXNzX3Rva2VuIn0.Q_I4PMBeeZSU-HbPZt7z9OW-tQjE0NI0I0DLF2qpZjY'; | ||
|
||
it('유효한 토큰으로 사용자 정보를 Request에 추가해야 한다', async () => { | ||
// 유효한 토큰 준비 | ||
mockRequest.cookies = { | ||
'access_token': validToken, | ||
'refresh_token': 'refresh-token' | ||
}; | ||
|
||
// 사용자 정보 mock | ||
const mockUser = { | ||
id: 1, | ||
username: 'testuser', | ||
email: 'test@example.com', | ||
velog_uuid: 'c7507240-093b-11ea-9aae-a58a86bb0520' | ||
}; | ||
|
||
// DB 쿼리 결과 모킹 | ||
(pool.query as jest.Mock).mockResolvedValueOnce({ | ||
rows: [mockUser] | ||
}); | ||
|
||
// 미들웨어 실행 | ||
await authMiddleware.verify( | ||
mockRequest as Request, | ||
mockResponse as Response, | ||
nextFunction | ||
); | ||
|
||
// 검증 | ||
expect(nextFunction).toHaveBeenCalledTimes(1); | ||
expect(nextFunction).not.toHaveBeenCalledWith(expect.any(Error)); | ||
expect(mockRequest.user).toEqual(mockUser); | ||
expect(mockRequest.tokens).toEqual({ | ||
accessToken: validToken, | ||
refreshToken: 'refresh-token' | ||
}); | ||
expect(pool.query).toHaveBeenCalledWith( | ||
'SELECT * FROM "users_user" WHERE velog_uuid = $1', | ||
['c7507240-093b-11ea-9aae-a58a86bb0520'] | ||
); | ||
}); | ||
|
||
it('토큰이 없으면 InvalidTokenError를 전달해야 한다', async () => { | ||
// 토큰 없음 | ||
mockRequest.cookies = {}; | ||
|
||
// 미들웨어 실행 | ||
await authMiddleware.verify( | ||
mockRequest as Request, | ||
mockResponse as Response, | ||
nextFunction | ||
); | ||
|
||
// 검증 | ||
expect(nextFunction).toHaveBeenCalledTimes(1); | ||
expect(nextFunction).toHaveBeenCalledWith( | ||
expect.objectContaining({ | ||
name: 'InvalidTokenError', | ||
message: 'accessToken과 refreshToken의 입력이 올바르지 않습니다' | ||
}) | ||
); | ||
}); | ||
|
||
it('유효하지 않은 토큰으로 InvalidTokenError를 전달해야 한다', async () => { | ||
// 유효하지 않은 토큰 (JWT 형식은 맞지만 내용이 잘못됨) | ||
const invalidToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpbnZhbGlkIjoidG9rZW4ifQ.invalidSignature'; | ||
mockRequest.cookies = { | ||
'access_token': invalidToken, | ||
'refresh_token': 'refresh-token' | ||
}; | ||
|
||
// 미들웨어 실행 | ||
await authMiddleware.verify( | ||
mockRequest as Request, | ||
mockResponse as Response, | ||
nextFunction | ||
); | ||
|
||
// 검증 | ||
expect(nextFunction).toHaveBeenCalledTimes(1); | ||
expect(nextFunction).toHaveBeenCalledWith(expect.any(Error)); | ||
}); | ||
|
||
it('UUID가 없는 페이로드로 InvalidTokenError를 전달해야 한다', async () => { | ||
// UUID가 없는 토큰 (페이로드를 임의로 조작) | ||
const tokenWithoutUUID = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MDM5MzQ1MjksImV4cCI6MTYwMzkzODEyOSwiaXNzIjoidmVsb2cuaW8iLCJzdWIiOiJhY2Nlc3NfdG9rZW4ifQ.2fLHQ3yKs9UmBQUa2oat9UOLiXzXvrhv_XHU2qwLBs8'; | ||
|
||
mockRequest.cookies = { | ||
'access_token': tokenWithoutUUID, | ||
'refresh_token': 'refresh-token' | ||
}; | ||
|
||
// 미들웨어 실행 | ||
await authMiddleware.verify( | ||
mockRequest as Request, | ||
mockResponse as Response, | ||
nextFunction | ||
); | ||
|
||
// 검증 | ||
expect(nextFunction).toHaveBeenCalledTimes(1); | ||
expect(nextFunction).toHaveBeenCalledWith( | ||
expect.objectContaining({ | ||
name: 'InvalidTokenError', | ||
message: '유효하지 않은 토큰 페이로드 입니다.' | ||
}) | ||
); | ||
}); | ||
|
||
it('사용자를 찾을 수 없으면 DBError가 발생해야 한다', async () => { | ||
// 유효한 토큰 준비 | ||
mockRequest.cookies = { | ||
'access_token': validToken, | ||
'refresh_token': 'refresh-token' | ||
}; | ||
|
||
// 사용자가 없음 모킹 | ||
(pool.query as jest.Mock).mockResolvedValueOnce({ | ||
rows: [] | ||
}); | ||
|
||
// 미들웨어 실행 | ||
await authMiddleware.verify( | ||
mockRequest as Request, | ||
mockResponse as Response, | ||
nextFunction | ||
); | ||
|
||
// 검증 | ||
expect(nextFunction).toHaveBeenCalledTimes(1); | ||
expect(mockRequest.user).toBeUndefined(); | ||
expect(nextFunction).toHaveBeenCalledWith( | ||
expect.objectContaining({ | ||
name: 'DBError', | ||
message: '사용자를 찾을 수 없습니다.' | ||
}) | ||
); | ||
}); | ||
|
||
it('쿠키에 토큰이 없으면 헤더에서 토큰을 가져와야 한다', async () => { | ||
// 요청 본문에 토큰 설정 | ||
mockRequest.body = { | ||
accessToken: validToken, | ||
refreshToken: 'refresh-token' | ||
}; | ||
|
||
// 사용자 정보 mock | ||
const mockUser = { | ||
id: 1, | ||
username: 'testuser', | ||
email: 'test@example.com', | ||
velog_uuid: 'c7507240-093b-11ea-9aae-a58a86bb0520' | ||
}; | ||
|
||
// DB 쿼리 결과 모킹 | ||
(pool.query as jest.Mock).mockResolvedValueOnce({ | ||
rows: [mockUser] | ||
}); | ||
|
||
// 미들웨어 실행 | ||
await authMiddleware.verify( | ||
mockRequest as Request, | ||
mockResponse as Response, | ||
nextFunction | ||
); | ||
|
||
// 검증 | ||
expect(nextFunction).toHaveBeenCalledTimes(1); | ||
expect(nextFunction).not.toHaveBeenCalledWith(expect.any(Error)); | ||
expect(mockRequest.user).toEqual(mockUser); | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
found가 아닌 userLoginToken으로 명시하니 코드가 의미하는 바가 명확해진 것 같습니다!
이 역시 디테일한 부분을 놓쳤었던 것 같네요🥲