-
Notifications
You must be signed in to change notification settings - Fork 3
Feat: 카카오 OAuth redirect URI 분리 #496
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
Closed
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b39be78
(#473) feat: 카카오 OAuth redirect URI 분리하여 로그인/회원가입 흐름 통합
sgoldenbird fe5c5eb
Merge branch 'develop' into feat/473/oauth-unified
Yongmin0423 330aea9
(#473) refactor: setAuthCookies 유틸로 access/refresh 토큰 갱신 처리 일원화
sgoldenbird ea62b4e
Merge branch 'develop' into feat/473/oauth-unified
sgoldenbird 23f0846
(#473) feat: 카카오 OAuth 로그인/회원가입 통합 흐름 구현
sgoldenbird 683cfd5
Merge branch 'feat/473/oauth-unified' of https://github.com/codeit-FE…
Yongmin0423 a5fad41
(#473) test: console.log 찍히도록
Yongmin0423 7545820
(#473) test: dynamic 추가
Yongmin0423 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| 'use client'; | ||
| import dynamic from 'next/dynamic'; | ||
| import { Suspense } from 'react'; | ||
|
|
||
| const KakaoTransition = dynamic( | ||
| () => import('@/domain/Auth/components/KakaoTransition'), | ||
| { ssr: false }, // 클라이언트 전용 렌더링 | ||
| ); | ||
|
|
||
| export default function Page() { | ||
| return ( | ||
| <Suspense fallback={null}> | ||
| <KakaoTransition /> | ||
| </Suspense> | ||
| ); | ||
| } |
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 |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
|
|
||
| import { | ||
| OAuthResponse, | ||
| oauthResponseSchema, | ||
| } from '@/domain/Auth/schemas/response'; | ||
| import setAuthCookies from '@/domain/Auth/utils/setAuthCookies'; | ||
| import { API_ENDPOINTS } from '@/shared/constants/endpoints'; | ||
| import { ERROR_CODES, ROUTES } from '@/shared/constants/routes'; | ||
|
|
||
| /** | ||
| * @function handleOauthSignIn | ||
| * @description | ||
| * 백엔드에 카카오 인가 코드를 전달하여 로그인 시도 후 사용자 정보를 반환합니다. | ||
| * 실패 시 에러 객체에 HTTP 상태 코드를 포함하여 던집니다. | ||
| * | ||
| * @param kakaoAuthCode - 카카오에서 발급받은 인가 코드 | ||
| * @returns 유효성 검증된 OAuth 로그인 응답 데이터 | ||
| * @throws 로그인 실패 또는 응답 형식이 올바르지 않을 경우 오류 | ||
| */ | ||
| async function handleOauthSignIn( | ||
| kakaoAuthCode: string, | ||
| ): Promise<OAuthResponse> { | ||
| const redirectUri = process.env.NEXT_PUBLIC_KAKAO_SIGNIN_REDIRECT_URI; | ||
| if (!redirectUri) { | ||
| throw new Error( | ||
| 'NEXT_PUBLIC_KAKAO_SIGNIN_REDIRECT_URI가 설정되지 않았습니다.', | ||
| ); | ||
| } | ||
|
|
||
| const signInRes = await fetch( | ||
| `${process.env.API_BASE_URL}${API_ENDPOINTS.OAUTH.SIGNIN_PROVIDER('kakao')}`, | ||
| { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ | ||
| token: kakaoAuthCode, | ||
| redirectUri, | ||
| }), | ||
| }, | ||
| ); | ||
|
|
||
| const responseData = await signInRes.json(); | ||
| if (!signInRes.ok) { | ||
| throw Object.assign( | ||
| new Error(responseData.message || '로그인에 실패했습니다.'), | ||
| { | ||
| status: signInRes.status, | ||
| }, | ||
| ); | ||
| } | ||
| return oauthResponseSchema.parse(responseData); | ||
| } | ||
|
|
||
| /** | ||
| * @function GET | ||
| * @description | ||
| * 카카오 OAuth 로그인 콜백을 처리하는 라우트입니다. | ||
| * | ||
| * 1. 인가 코드로 백엔드에 로그인 요청 | ||
| * 2. 성공 시 토큰 쿠키 저장 및 메인 페이지로 이동 | ||
| * 3. 실패 시 에러 코드에 따라 적절한 리디렉션 처리 | ||
| * | ||
| * ### 에러별 리디렉션 전략: | ||
| * - 403 또는 404 → `/kakao/transition?status=need-signup` | ||
| * - 그 외 → `/signin?error=...&message=...` | ||
| * | ||
| * @param request - Next.js 서버 요청 객체 | ||
| * @returns 리디렉션 응답 | ||
| */ | ||
| export async function GET(request: NextRequest) { | ||
| try { | ||
| const code = request.nextUrl.searchParams.get('code'); | ||
|
|
||
| if (!code) { | ||
| throw Object.assign(new Error('카카오 인증 코드가 없습니다.'), { | ||
| status: 400, | ||
| }); | ||
| } | ||
|
|
||
| const responseData = await handleOauthSignIn(code); | ||
| const response = NextResponse.redirect( | ||
| new URL(ROUTES.ACTIVITIES.ROOT, request.url), | ||
| ); | ||
| setAuthCookies(response, { | ||
| accessToken: responseData.accessToken, | ||
| refreshToken: responseData.refreshToken, | ||
| }); | ||
| return response; | ||
| } catch (error: unknown) { | ||
| console.error('[Kakao Signin Error]:', error); | ||
|
|
||
| const errorStatus = | ||
| error instanceof Error && 'status' in error | ||
| ? (error as Error & { status: number }).status | ||
| : undefined; | ||
|
|
||
| if (errorStatus === 404 || errorStatus === 403) { | ||
| const redirectToTransition = new URL( | ||
| '/kakao/transition', | ||
| request.nextUrl.origin, | ||
| ); | ||
| redirectToTransition.searchParams.set('status', 'need-signup'); | ||
| redirectToTransition.searchParams.set( | ||
| 'message', | ||
| error instanceof Error ? error.message : '회원가입 먼저 해주세요.', | ||
| ); | ||
| return NextResponse.redirect(redirectToTransition); | ||
| } | ||
|
|
||
| const defaultErrorUrl = new URL( | ||
| `${ROUTES.SIGNIN}?error=${ERROR_CODES.OAUTH_KAKAO_FAILED}`, | ||
| request.url, | ||
| ); | ||
| if (error instanceof Error) { | ||
| defaultErrorUrl.searchParams.append('message', error.message); | ||
| } | ||
| return NextResponse.redirect(defaultErrorUrl); | ||
| } | ||
| } |
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,130 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
|
|
||
| import { | ||
| OAuthResponse, | ||
| oauthResponseSchema, | ||
| } from '@/domain/Auth/schemas/response'; | ||
| import setAuthCookies from '@/domain/Auth/utils/setAuthCookies'; | ||
| import { API_ENDPOINTS } from '@/shared/constants/endpoints'; | ||
| import { ERROR_CODES, ROUTES } from '@/shared/constants/routes'; | ||
|
|
||
| /** | ||
| * @function handleOauthSignUp | ||
| * @description | ||
| * 백엔드에 카카오 인가 코드와 랜덤 닉네임을 전달하여 회원가입을 시도합니다. | ||
| * 실패 시 HTTP 상태 코드와 함께 오류를 던집니다. | ||
| * | ||
| * @param kakaoAuthCode - 카카오로부터 받은 인가 코드 | ||
| * @param nickname - 자동 생성된 임의 닉네임 | ||
| * @returns 백엔드 응답 (accessToken, refreshToken 등 포함) | ||
| * @throws 백엔드 API 실패 또는 응답 스키마 불일치 시 에러 발생 | ||
| */ | ||
| async function handleOauthSignUp( | ||
| kakaoAuthCode: string, | ||
| nickname: string, | ||
| ): Promise<OAuthResponse> { | ||
| const redirectUri = process.env.NEXT_PUBLIC_KAKAO_SIGNUP_REDIRECT_URI; | ||
| if (!redirectUri) { | ||
| throw new Error( | ||
| 'NEXT_PUBLIC_KAKAO_SIGNUP_REDIRECT_URI가 설정되지 않았습니다.', | ||
| ); | ||
| } | ||
|
|
||
| const signUpResponse = await fetch( | ||
| `${process.env.API_BASE_URL}${API_ENDPOINTS.OAUTH.SIGNUP_PROVIDER('kakao')}`, | ||
| { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ | ||
| token: kakaoAuthCode, | ||
| nickname: nickname, | ||
| redirectUri, | ||
| }), | ||
| }, | ||
| ); | ||
|
|
||
| const responseData = await signUpResponse.json(); | ||
| if (!signUpResponse.ok) { | ||
| throw Object.assign( | ||
| new Error(responseData.message || '회원가입에 실패했습니다.'), | ||
| { | ||
| status: signUpResponse.status, | ||
| }, | ||
| ); | ||
| } | ||
| return oauthResponseSchema.parse(responseData); | ||
| } | ||
|
|
||
| /** | ||
| * @function GET | ||
| * @description | ||
| * 카카오 OAuth 회원가입 콜백을 처리하는 라우트입니다. | ||
| * | ||
| * 1. 인가 코드(code)를 쿼리에서 추출 | ||
| * 2. 자동 생성된 랜덤 닉네임으로 회원가입 시도 | ||
| * 3. 성공 시 토큰을 쿠키에 저장하고 `/activities`로 이동 | ||
| * 4. 실패 시 상태에 따라 리디렉션 분기 | ||
| * | ||
| * ### 리디렉션 분기 | ||
| * - 409 또는 400: 이미 가입된 사용자 → `/kakao/transition?status=already-exists` | ||
| * - 기타 오류: `/signup?error=...&message=...` 으로 리디렉션 (토스트 처리용) | ||
| * | ||
| * @param request - Next.js GET 요청 객체 | ||
| * @returns 리디렉션 응답 | ||
| */ | ||
| export async function GET(request: NextRequest) { | ||
| try { | ||
| const code = request.nextUrl.searchParams.get('code'); | ||
|
|
||
| if (!code) { | ||
| throw Object.assign(new Error('카카오 인증 코드가 없습니다.'), { | ||
| status: 400, | ||
| }); | ||
| } | ||
|
|
||
| const arbitraryNickname = `K_${crypto.randomUUID().replace(/-/g, '').slice(0, 7)}`; | ||
| const responseData = await handleOauthSignUp(code, arbitraryNickname); | ||
|
|
||
| const response = NextResponse.redirect( | ||
| new URL(ROUTES.ACTIVITIES.ROOT, request.url), | ||
| ); | ||
|
|
||
| setAuthCookies(response, { | ||
| accessToken: responseData.accessToken, | ||
| refreshToken: responseData.refreshToken, | ||
| }); | ||
|
|
||
| return response; | ||
| } catch (error: unknown) { | ||
| console.error('[Kakao Signup Error]:', error); | ||
|
|
||
| // const errorStatus = | ||
| // error instanceof Error && 'status' in error | ||
| // ? (error as Error & { status: number }).status | ||
| // : undefined; | ||
|
|
||
| // if (errorStatus === 409 || errorStatus === 400) { | ||
| // const redirectToTransition = new URL( | ||
| // '/kakao/transition', | ||
| // request.nextUrl.origin, | ||
| // ); | ||
| // redirectToTransition.searchParams.set('status', 'already-exists'); | ||
| // redirectToTransition.searchParams.set( | ||
| // 'message', | ||
| // error instanceof Error | ||
| // ? error.message | ||
| // : '이미 가입된 회원입니다. 로그인해주세요.', | ||
| // ); | ||
| // return NextResponse.redirect(redirectToTransition); | ||
| // } | ||
|
|
||
| const defaultErrorUrl = new URL( | ||
| `${ROUTES.SIGNUP}?error=${ERROR_CODES.OAUTH_KAKAO_FAILED}`, | ||
| request.url, | ||
| ); | ||
| if (error instanceof Error) { | ||
| defaultErrorUrl.searchParams.append('message', error.message); | ||
| } | ||
| return NextResponse.redirect(defaultErrorUrl); | ||
| } | ||
| } | ||
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
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.