-
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
Changes from 5 commits
89b29ca
8650263
60a4446
4a37b62
e6a1881
1052e20
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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'; |
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가 확실히 더 적절하겠네요! |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,240 @@ | ||
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: '[email protected]', | ||
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('사용자를 찾을 수 없으면 next를 호출해야 한다', 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(); | ||
}); | ||
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. 미들웨어 로직상 DB에 사용자가 없으면 DB Error를 던지고 next를 호출하는데, 그 부분이 포함되면 더 좋을 것 같네요~! 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. 좋은 포인트 지적 너무 감사해요! 테스트 구성을 아예 바꿀게요! 생각해보니까 에러 여부 자체 테스팅 보다
|
||
|
||
it('쿠키 대신 요청 본문에서 토큰을 추출해야 한다', async () => { | ||
// 요청 본문에 토큰 설정 | ||
mockRequest.body = { | ||
accessToken: validToken, | ||
refreshToken: 'refresh-token' | ||
}; | ||
|
||
// 사용자 정보 mock | ||
const mockUser = { | ||
id: 1, | ||
username: 'testuser', | ||
email: '[email protected]', | ||
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); | ||
}); | ||
|
||
it('쿠키와 요청 본문 대신 헤더에서 토큰을 추출해야 한다', async () => { | ||
// 헤더에 토큰 설정 | ||
mockRequest.headers = { | ||
'access_token': validToken, | ||
'refresh_token': 'refresh-token' | ||
}; | ||
|
||
// 사용자 정보 mock | ||
const mockUser = { | ||
id: 1, | ||
username: 'testuser', | ||
email: '[email protected]', | ||
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); | ||
}); | ||
}); | ||
}); |
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으로 명시하니 코드가 의미하는 바가 명확해진 것 같습니다!
이 역시 디테일한 부분을 놓쳤었던 것 같네요🥲