-
Notifications
You must be signed in to change notification settings - Fork 3
Feat: 카카오 소셜 로그인/회원가입 기능 통합 및 개선 #514
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 all commits
b39be78
330aea9
ea62b4e
ed2ebee
bda0d7c
1111ca8
4f08ab6
09faf72
ee94188
7389939
2246157
ef429a5
251faed
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 |
|---|---|---|
|
|
@@ -42,3 +42,5 @@ next-env.d.ts | |
|
|
||
| *storybook.log | ||
| storybook-static | ||
|
|
||
| local-assets/ | ||
| 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> | ||
| ); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| 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, | ||
| }), | ||
| signal: AbortSignal.timeout(60000), | ||
| }, | ||
| ); | ||
|
|
||
| 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); | ||
| } | ||
| } | ||
| 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); | ||
| // } | ||
|
Comment on lines
+101
to
+119
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. 💡 Verification agent 🧩 Analysis chain주석 처리된 에러 핸들링 코드 정리가 필요합니다. 주석 처리된 transition 페이지 리다이렉션 로직이 있습니다. 이 기능이 향후 구현 예정인지, 아니면 제거해야 할 코드인지 명확히 하시기 바랍니다. 이 기능의 구현 상태를 확인하기 위해 다음 스크립트를 실행해보세요: 🏁 Script executed: #!/bin/bash
# Description: Check if KakaoTransition component handles 'already-exists' status
# Search for 'already-exists' status handling in KakaoTransition component
rg -A 5 -B 5 "already-exists" src/domain/Auth/components/KakaoTransition.tsx
# Search for similar error handling patterns in signin route
rg -A 5 -B 5 "transition" src/app/api/auth/kakao/signin/route.tsLength of output: 801 불필요한 주석 정리 또는 기능 구현 결정 필요
다음 중 하나를 선택해 주세요:
점검이 필요한 위치:
🤖 Prompt for AI Agents |
||
|
|
||
| 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); | ||
| } | ||
| } | ||
| 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
+11
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. 🛠️ Refactor suggestion 환경 변수 검증 추가를 권장합니다. 환경 변수가 누락된 경우에 대한 런타임 검증을 추가하면 더 안전합니다. -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;
+
+if (!KAKAO_REDIRECT_URI || !KAKAO_CLIENT_ID) {
+ throw new Error('카카오 OAuth 환경 변수가 설정되지 않았습니다.');
+}📝 Committable suggestion
Suggested change
🤖 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> | ||||||||||||||||||
| ); | ||||||||||||||||||
| } | ||||||||||||||||||
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.
💡 Verification agent
🧩 Analysis chain
URL 쿼리 파라미터로 전달되는 에러 메시지 보안 검토
에러 메시지를 URL 쿼리 파라미터로 전달하는 것은 다음과 같은 보안 위험이 있을 수 있습니다:
Also applies to: 125-126
🏁 Script executed:
Length of output: 2041
XSS 및 민감 정보 노출 위험: URL 쿼리로 전달되는 에러 메시지 처리 필요
현재 구현
src/app/api/auth/kakao/signin/route.ts(114–116):error.message를 쿼리 파라미터로 전달src/domain/Auth/components/KakaoTransition.tsx:위험
권장 조치
encodeURIComponent()적용 후, React의 기본 이스케이프 기능으로 렌더링DOMPurify등 라이브러리로 sanitize 검증 추가src/app/(auth)/signin/page.tsx)에서도 동일한 패턴이 있는지 확인 후 위 조치 적용🤖 Prompt for AI Agents