-
Notifications
You must be signed in to change notification settings - Fork 3
Feat/ API 라우터 수정 및 미들웨어 일시적 추가 #138
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
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e52c509
Update: issue template updated
Ruthgyeul 6103e6a
Potential fix for code scanning alert no. 1: Workflow does not contai…
Ruthgyeul 8d37f8f
Update: CI/CD Permission
Ruthgyeul 50b396e
Update: CI/CD Permission
Ruthgyeul c882774
Update: minor change on auth logics
Ruthgyeul f9ee21b
Update: minor change on auth logics
Ruthgyeul 35393fa
Update: create middleware temporally
Ruthgyeul 4adf188
Update middleware.ts
Ruthgyeul f4117ce
Update src/lib/rate-limit.ts
Ruthgyeul 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
File renamed without changes.
File renamed without changes.
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,6 @@ | ||
| name: Build Docker and Upload to S3 | ||
| permissions: | ||
| contents: read | ||
|
|
||
| on: | ||
| push: | ||
|
|
||
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
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,72 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
| import axios, { AxiosError, AxiosResponse } from 'axios'; | ||
|
|
||
| const API_BASE_URL = process.env.NEXT_PUBLIC_BASE_API_URL; | ||
| const TIMEOUT = 5000; | ||
|
|
||
| interface RefreshResponse { | ||
| accessToken?: string; | ||
| refreshToken?: string; | ||
| message?: string; | ||
| } | ||
|
|
||
| interface ErrorResponse { | ||
| error: string; | ||
| } | ||
|
|
||
| export async function POST(req: NextRequest): Promise<NextResponse<RefreshResponse | ErrorResponse>> { | ||
| const refreshUrl = `${API_BASE_URL}/auth/refresh`; | ||
| const isProd = process.env.NODE_ENV === 'production'; | ||
|
|
||
| try { | ||
| const cookies = req.headers.get('cookie') || ''; | ||
| const body = await req.json(); | ||
|
|
||
| const response: AxiosResponse<RefreshResponse> = await axios.post( | ||
| refreshUrl, | ||
| body, | ||
| { | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| Cookie: cookies, | ||
| }, | ||
| withCredentials: true, | ||
| timeout: TIMEOUT, | ||
| } | ||
| ); | ||
|
|
||
| const nextResponse = NextResponse.json(response.data, { | ||
| status: response.status, | ||
| }); | ||
|
|
||
| const setCookies = response.headers['set-cookie']; | ||
| if (setCookies) { | ||
| setCookies.forEach((cookieStr: string) => { | ||
| const [nameValue] = cookieStr.split(';'); | ||
| const [name, value] = nameValue.split('='); | ||
| nextResponse.cookies.set(name, value, { | ||
| path: '/', | ||
| httpOnly: true, | ||
| secure: isProd, | ||
| sameSite: isProd ? 'none' : 'lax', | ||
| domain: isProd ? '.gdgocinha.com' : undefined, | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| return nextResponse; | ||
| } catch (error) { | ||
| const axiosError = error as AxiosError<ErrorResponse>; | ||
| const status = axiosError?.response?.status || 500; | ||
| let errorMessage = 'Authentication failed'; | ||
|
|
||
| if (axiosError.code === 'ECONNABORTED') { | ||
| errorMessage = 'Request timeout'; | ||
| } else if (axiosError.response?.data?.error) { | ||
| errorMessage = axiosError.response.data.error; | ||
| } | ||
|
|
||
| console.error('[AUTH PROXY ERROR] /refresh', axiosError.message); | ||
| return NextResponse.json({ error: errorMessage }, { status }); | ||
| } | ||
| } | ||
This file was deleted.
Oops, something went wrong.
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,142 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import axios from 'axios'; | ||
|
|
||
| import { rateLimit } from '@/lib/rate-limit'; | ||
|
|
||
| const ORIGINAL_AUTH_URL = process.env.NEXT_PUBLIC_BASE_API_URL; | ||
|
|
||
| interface LoginRequest { | ||
| email: string; | ||
| password: string; | ||
| } | ||
|
|
||
| interface LoginResponse { | ||
| error?: string; | ||
| [key: string]: any; | ||
| } | ||
|
|
||
| export async function POST(request: Request): Promise<NextResponse> { | ||
| try { | ||
| // Rate limiting 적용 | ||
| const limiter = rateLimit({ | ||
| interval: 60 * 1000, // 1분 | ||
| uniqueTokenPerInterval: 500, | ||
| }); | ||
|
|
||
| try { | ||
| await limiter.check(5, 'LOGIN_ATTEMPT'); // 1분당 5회 시도 제한 | ||
| } catch { | ||
| return NextResponse.json( | ||
| { error: '너무 많은 로그인 시도가 있었습니다. 잠시 후 다시 시도해주세요.' }, | ||
| { status: 429 } | ||
| ); | ||
| } | ||
|
|
||
| // 클라이언트로부터 받은 요청 데이터 추출 | ||
| const { email, password }: LoginRequest = await request.json(); | ||
|
|
||
| // 입력값 검증 | ||
| if (!email || !password) { | ||
| return NextResponse.json( | ||
| { error: '이메일과 비밀번호를 모두 입력해주세요.' }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| if (!email.includes('@') || !email.includes('.')) { | ||
| return NextResponse.json( | ||
| { error: '유효한 이메일 주소를 입력해주세요.' }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| if (password.length < 8) { | ||
| return NextResponse.json( | ||
| { error: '비밀번호는 8자 이상이어야 합니다.' }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| const isProd = process.env.NODE_ENV === 'production'; | ||
|
|
||
| // 기존 refresh_token 쿠키 삭제 | ||
| const response = NextResponse.json({}); | ||
| response.cookies.set('refresh_token', '', { | ||
| path: '/', | ||
| httpOnly: true, | ||
| secure: isProd, | ||
| sameSite: isProd ? 'none' : 'lax', | ||
| domain: isProd ? '.gdgocinha.com' : undefined, | ||
| expires: new Date(0), | ||
| }); | ||
|
|
||
| const authResponse = await axios.post( | ||
| `${ORIGINAL_AUTH_URL}/auth/login`, | ||
| { email, password }, | ||
| { | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| withCredentials: true, | ||
| } | ||
| ); | ||
|
|
||
| const data = authResponse.data; | ||
|
|
||
| const nextResponse = NextResponse.json(data, { | ||
| status: authResponse.status, | ||
| statusText: authResponse.statusText, | ||
| }); | ||
|
|
||
| // 원본 응답의 쿠키가 있으면 추출하여 현재 도메인에 설정 | ||
| const cookies = authResponse.headers['set-cookie']; | ||
Ruthgyeul marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (cookies) { | ||
| cookies.forEach((cookie: string) => { | ||
| const cookieParts = cookie.split(';')[0].split('='); | ||
| const cookieName = cookieParts[0]; | ||
| const cookieValue = cookieParts.slice(1).join('='); | ||
|
|
||
| nextResponse.cookies.set(cookieName, cookieValue, { | ||
| path: '/', | ||
| httpOnly: true, | ||
| secure: isProd, | ||
| sameSite: isProd ? 'none' : 'lax', | ||
| domain: isProd ? '.gdgocinha.com' : undefined, | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| return nextResponse; | ||
| } catch (error: any) { | ||
| console.error('로그인 프록시 오류:', error); | ||
|
|
||
| // 구체적인 에러 메시지 처리 | ||
| if (error.response) { | ||
| switch (error.response.status) { | ||
| case 401: | ||
| return NextResponse.json( | ||
| { error: '이메일 또는 비밀번호가 올바르지 않습니다.' }, | ||
| { status: 401 } | ||
| ); | ||
| case 403: | ||
| return NextResponse.json( | ||
| { error: '접근이 거부되었습니다.' }, | ||
| { status: 403 } | ||
| ); | ||
| case 404: | ||
| return NextResponse.json( | ||
| { error: '서비스를 찾을 수 없습니다.' }, | ||
| { status: 404 } | ||
| ); | ||
| default: | ||
| return NextResponse.json( | ||
| { error: '서버 오류가 발생했습니다. 잠시 후 다시 시도해주세요.' }, | ||
| { status: error.response.status } | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| return NextResponse.json( | ||
| { error: '서버 오류가 발생했습니다. 잠시 후 다시 시도해주세요.' }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
| } | ||
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,55 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import axios from 'axios'; | ||
|
|
||
| const ORIGINAL_AUTH_URL = process.env.NEXT_PUBLIC_BASE_API_URL; | ||
|
|
||
| export async function POST(request: Request): Promise<NextResponse> { | ||
| try { | ||
| const response = await axios.post( | ||
| `${ORIGINAL_AUTH_URL}/auth/logout`, | ||
| {}, | ||
| { | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| withCredentials: true, | ||
| } | ||
| ); | ||
|
|
||
| // 응답 생성 | ||
| const nextResponse = NextResponse.json( | ||
| { message: '로그아웃이 완료되었습니다.' }, | ||
| { | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| } | ||
| ); | ||
|
|
||
| // 쿠키 삭제 | ||
| const cookies = response.headers['set-cookie']; | ||
| if (cookies) { | ||
| cookies.forEach((cookie: string) => { | ||
| const cookieParts = cookie.split(';')[0].split('='); | ||
| const cookieName = cookieParts[0]; | ||
|
|
||
| // 쿠키 삭제 | ||
| nextResponse.cookies.delete(cookieName); | ||
| }); | ||
| } | ||
|
|
||
| nextResponse.cookies.delete('refresh_token'); | ||
|
|
||
| return nextResponse; | ||
| } catch (error: any) { | ||
| console.error('로그아웃 프록시 오류:', error); | ||
|
|
||
| // 에러 응답 생성 | ||
| const errorResponse = NextResponse.json( | ||
| { error: '로그아웃 처리 중 오류가 발생했습니다.' }, | ||
| { status: error.response?.status || 500 } | ||
| ); | ||
|
|
||
| // 에러가 발생하더라도 클라이언트 측 쿠키는 삭제 | ||
| errorResponse.cookies.delete('refresh_token'); | ||
|
|
||
| return errorResponse; | ||
| } | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.