-
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 4 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
| 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| 'use client'; | ||
|
|
||
| import Image from 'next/image'; | ||
| import { useSearchParams } from 'next/navigation'; | ||
|
|
||
| import LogoSymbol from '@/shared/assets/logos/LogoSymbol'; | ||
| import Button from '@/shared/components/Button'; | ||
|
|
||
| const KAKAO_REDIRECT_URI = process.env.NEXT_PUBLIC_KAKAO_SIGNUP_REDIRECT_URI!; | ||
| const KAKAO_CLIENT_ID = process.env.NEXT_PUBLIC_KAKAO_REST_API_KEY!; | ||
|
Comment on lines
+9
to
+10
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. 환경 변수 검증이 누락되었습니다. 클라이언트 컴포넌트에서 환경 변수에 직접 접근하고 있지만, 값이 존재하는지 검증하지 않습니다. 런타임 오류를 방지하기 위해 검증 로직을 추가해주세요. 다음과 같이 수정하는 것을 제안합니다: -const KAKAO_REDIRECT_URI = process.env.NEXT_PUBLIC_KAKAO_SIGNUP_REDIRECT_URI!;
-const KAKAO_CLIENT_ID = process.env.NEXT_PUBLIC_KAKAO_REST_API_KEY!;
+const KAKAO_REDIRECT_URI = process.env.NEXT_PUBLIC_KAKAO_SIGNUP_REDIRECT_URI;
+const KAKAO_CLIENT_ID = process.env.NEXT_PUBLIC_KAKAO_REST_API_KEY;그리고 const handleRedirectToKakao = () => {
if (!KAKAO_CLIENT_ID || !KAKAO_REDIRECT_URI) {
console.error('카카오 OAuth 환경 변수가 설정되지 않았습니다.');
return;
}
// ... 기존 로직
};🤖 Prompt for AI Agents |
||
|
|
||
| /** | ||
| * @component KakaoTransitionPage | ||
| * @description | ||
| * 카카오 OAuth 인증 흐름 중, 사용자가 로그인 또는 회원가입 중간에 분기되는 전환 페이지입니다. | ||
| * | ||
| * - 백엔드 응답에서 `403`, `404`, `409`, `400` 등의 상태 코드가 발생할 경우, | ||
| * 서버는 클라이언트를 `/kakao/transition?status=...` 주소로 리디렉션합니다. | ||
| * | ||
| * - 해당 페이지는 쿼리 파라미터로 전달된 `status`, `message`를 읽고, | ||
| * 상황에 따라 안내 메시지와 함께 다시 카카오 인증 페이지로 유도합니다. | ||
| * | ||
| * @example | ||
| * ``` | ||
| * /kakao/transition?status=need-signup&message=회원가입 먼저 해주세요. | ||
| * | ||
| * ``` | ||
| * | ||
| * ### 쿼리 파라미터 | ||
| * - `status`: 분기 상태 (`need-signup`) | ||
| * - `message`: 사용자에게 표시할 메시지 | ||
| * | ||
| * ### 동작 흐름 | ||
| * 1. `status`가 `need-signup`이면 "회원 가입 먼저 진행해주세요."라는 안내 문구가 표시됩니다. | ||
| * 2. 버튼을 누르면 카카오 인증 페이지로 다시 리디렉션되어 새로운 인가 코드를 받게 됩니다. | ||
| */ | ||
| export default function KakaoTransition() { | ||
| const searchParams = useSearchParams(); | ||
|
|
||
| const status = searchParams.get('status'); | ||
| const message = searchParams.get('message'); | ||
|
|
||
| const handleRedirectToKakao = () => { | ||
| const kakaoAuthUrl = `https://kauth.kakao.com/oauth/authorize?response_type=code&client_id=${KAKAO_CLIENT_ID}&redirect_uri=${KAKAO_REDIRECT_URI}`; | ||
| window.location.href = kakaoAuthUrl; | ||
| }; | ||
|
|
||
| const notAMember = status === 'need-signup'; | ||
|
|
||
| const title = notAMember | ||
| ? '회원 가입 먼저 진행해주세요.' | ||
| : '처리 중 문제가 발생했습니다.'; | ||
|
|
||
| return ( | ||
| <div className='flex-col-center font-size-16 gap-10 p-4 text-center text-black'> | ||
| <LogoSymbol className='text-brand-2 size-100' /> | ||
| <h2 className='font-size-20 font-semibold'>{title}</h2> | ||
| <p>{message ?? '아래 버튼을 눌러 회원가입하세요.'}</p> | ||
|
|
||
| <Button | ||
| variant='primary' | ||
| size='small' | ||
| className='bg-kakao hover:bg-kakao/80 w-full py-17.5' | ||
| onClick={handleRedirectToKakao} | ||
| > | ||
| <div className='relative flex w-full items-center justify-center gap-0.5'> | ||
| <Image | ||
| src='/icons/kakao-btn-sm.svg' | ||
| alt='Kakao Icon' | ||
| width={24} | ||
| height={24} | ||
| /> | ||
| <span className='font-size-15 text-gray-800'>계속하기</span> | ||
| </div> | ||
| </Button> | ||
| </div> | ||
| ); | ||
| } | ||
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.