Conversation
There was a problem hiding this comment.
Summary of Changes
Hello @Dobbymin, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
이 PR은 카카오 로그인 기능을 전반적으로 개선하여 사용자 경험과 코드 구조를 향상시키는 데 중점을 둡니다. 핵심 변경 사항은 OAuth 리다이렉트 로직을 재사용 가능한 React 훅으로 분리하고, 인증 관련 데이터를 효율적으로 관리하기 위한 전용 저장소 모듈을 도입한 것입니다. 이를 통해 기존 OAuth 리다이렉트 페이지의 복잡성을 줄이고, 불필요한 API 호출을 최적화하며, 전반적인 타입 안정성을 높였습니다. 또한, 로그인 버튼에 로딩 상태를 추가하여 사용자에게 더 나은 피드백을 제공합니다.
Highlights
- 카카오 로그인 로직 훅 분리: 기존의 카카오 로그인 리다이렉트 로직을 useKakaoLogin 및 useKakaoCallback 훅으로 분리하여 재사용성과 유지보수성을 높였습니다.
- 인증 저장소 모듈 도입: 인증 관련 토큰(refreshToken)을 localStorage에 안전하게 저장하고 관리하기 위한 authStorage 유틸리티 모듈을 추가했습니다.
- OAuth 리다이렉트 페이지 개선: OAuth 리다이렉트 페이지의 불필요한 상태 관리와 API 호출 로직을 제거하고, 새로 정의된 훅을 활용하여 코드를 대폭 간소화했습니다.
- 타입 정의 개선: getTicketApi의 응답 타입을 명시적으로 정의하여 TypeScript의 타입 안정성을 강화하고 개발자 경험을 향상시켰습니다.
- 로그인 버튼 로딩 상태 추가: 카카오 로그인 버튼에 로딩 상태를 표시하여 사용자가 로그인 진행 상황을 시각적으로 인지할 수 있도록 사용자 경험을 개선했습니다.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
카카오 로그인 기능 개선을 위한 리팩토링 작업을 잘 수행하셨습니다. OAuth 로직을 커스텀 훅으로 분리하고, 인증 상태 관리를 위한 모듈을 추가하여 코드 구조를 개선한 점이 인상적입니다. 전반적으로 좋은 방향의 변경이지만, 몇 가지 잠재적인 버그와 개선점을 발견하여 리뷰에 포함했습니다. 특히 auth-storage의 get 함수에서 발생할 수 있는 런타임 에러는 반드시 수정이 필요해 보입니다. 또한, 비동기 로직과 에러 처리를 좀 더 견고하게 만들면 더 안정적인 기능이 될 것입니다. 자세한 내용은 각 파일의 주석을 참고해주세요.
| const get = (): AuthStorageKey[T] => { | ||
| const value = storage.getItem(storageKey); | ||
|
|
||
| return JSON.parse(value as string); | ||
| }; |
There was a problem hiding this comment.
get 함수는 localStorage에 해당 키가 없을 때 storage.getItem(storageKey)가 null을 반환하여 JSON.parse(null)이 호출되면서 런타임 에러를 발생시킵니다. 이는 애플리케이션을 중단시킬 수 있는 심각한 버그입니다.
값이 null인 경우를 처리하고, JSON.parse를 try-catch 블록으로 감싸 안정성을 높이는 것이 좋습니다. 또한, 반환 타입을 AuthStorageKey[T] | null로 변경하여 호출하는 쪽에서 값이 없을 수 있는 상황을 인지하고 처리하도록 강제하는 것이 좋습니다.
const get = (): AuthStorageKey[T] | null => {
const value = storage.getItem(storageKey);
if (value === null) {
return null;
}
try {
return JSON.parse(value);
} catch (e) {
console.error('Failed to parse auth storage value:', e);
return null;
}
};| window.location.href = `${BASE_URL}/oauth2/authorization/kakao | ||
| `; |
| return useQuery({ | ||
| queryKey: KakaoCallbackQueryKey.callback(ticket), | ||
| // code가 있을 때만 이 쿼리를 실행해. | ||
| queryFn: () => getTicketApi(ticket), | ||
| // 이 쿼리는 한 번만 실행되면 되므로, 재시도나 캐시 관련 옵션을 조정할 수 있어. | ||
| retry: 0, | ||
| staleTime: Infinity, | ||
| }); |
There was a problem hiding this comment.
ticket 값이 없을 때에도 getTicketApi가 호출되어 불필요한 API 요청이 발생하고 있습니다. useQuery의 enabled 옵션을 사용하여 ticket이 존재할 때만 쿼리가 실행되도록 하는 것이 좋습니다. 이렇게 하면 의도치 않은 에러 발생을 막고 네트워크 리소스를 절약할 수 있습니다.
return useQuery({
queryKey: KakaoCallbackQueryKey.callback(ticket),
// ticket이 있을 때만 이 쿼리를 실행해.
queryFn: () => getTicketApi(ticket),
enabled: !!ticket,
// 이 쿼리는 한 번만 실행되면 되므로, 재시도나 캐시 관련 옵션을 조정할 수 있어.
retry: 0,
staleTime: Infinity,
});| export default function OAuthRedirectPage() { | ||
| const [searchParams] = useSearchParams(); | ||
|
|
||
| const navigate = useNavigate(); | ||
| const [error, setError] = useState<string | null>(null); | ||
|
|
||
| // URL에서 ticket 파라미터 추출 | ||
| const ticket = searchParams.get('ticket'); | ||
| const oauthError = searchParams.get('error'); | ||
| const errorDescription = searchParams.get('error_description'); | ||
|
|
||
| useEffect(() => { | ||
| if (oauthError) { | ||
| setError(errorDescription || `OAuth 인증 오류: ${oauthError}`); | ||
| } else if (!ticket) { | ||
| setError('인증 토큰이 없습니다. 다시 로그인해주세요.'); | ||
| } | ||
| }, [oauthError, errorDescription, ticket]); | ||
|
|
||
| // ticket이 있고 OAuth 에러가 없을 때만 API 호출 | ||
| const shouldCallApi = !!ticket && !oauthError; | ||
| const { | ||
| data: authData, | ||
| error: apiError, | ||
| isLoading, | ||
| } = useGetAuthTicket(shouldCallApi ? ticket : ''); | ||
|
|
||
| // API 에러 처리 | ||
| useEffect(() => { | ||
| if (apiError) { | ||
| console.error('API 호출 중 오류:', apiError); | ||
| setError('인증 검증에 실패했습니다. 다시 시도해주세요.'); | ||
| } | ||
| }, [apiError]); | ||
| const { data, isSuccess, isError } = useKakaoCallback(ticket ?? ''); | ||
|
|
||
| // 성공 시 처리 | ||
| useEffect(() => { | ||
| if (authData && !isLoading && !apiError && shouldCallApi) { | ||
| console.log('OAuth 인증 성공!', authData); | ||
|
|
||
| // refreshToken을 localStorage에 저장 | ||
| localStorage.setItem('refreshToken', authData.refreshToken); | ||
| if (isSuccess && data) { | ||
| authStorage.refreshToken.set(data.refreshToken); | ||
|
|
||
| // 메인 페이지로 이동 | ||
| navigate(ROUTER_PATH.MAIN, { replace: true }); | ||
| navigate(ROUTER_PATH.ROOT); | ||
| } | ||
| }, [authData, isLoading, apiError, navigate, shouldCallApi]); | ||
|
|
||
| if (isLoading && shouldCallApi) { | ||
| return ( | ||
| <div className='flex min-h-screen items-center justify-center'> | ||
| <div className='text-center'> | ||
| <div className='mb-4'> | ||
| <div className='mx-auto h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent'></div> | ||
| </div> | ||
| <p className='text-lg font-medium text-gray-700'>인증 처리 중...</p> | ||
| <p className='mt-2 text-sm text-gray-500'>잠시만 기다려주세요.</p> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| if (error) { | ||
| return ( | ||
| <div className='flex min-h-screen items-center justify-center'> | ||
| <div className='text-center'> | ||
| <div className='mb-4'> | ||
| <div className='mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-red-100'> | ||
| <svg | ||
| className='h-6 w-6 text-red-600' | ||
| fill='none' | ||
| viewBox='0 0 24 24' | ||
| stroke='currentColor' | ||
| > | ||
| <path | ||
| strokeLinecap='round' | ||
| strokeLinejoin='round' | ||
| strokeWidth={2} | ||
| d='M6 18L18 6M6 6l12 12' | ||
| /> | ||
| </svg> | ||
| </div> | ||
| </div> | ||
| <h2 className='mb-2 text-xl font-semibold text-gray-900'>인증 실패</h2> | ||
| <p className='mb-4 text-gray-600'>{error}</p> | ||
| <button | ||
| onClick={() => navigate(ROUTER_PATH.LOGIN)} | ||
| className='rounded-lg bg-blue-500 px-4 py-2 text-white transition-colors hover:bg-blue-600' | ||
| > | ||
| 로그인 페이지로 돌아가기 | ||
| </button> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
| if (isError) { | ||
| // 실패 시, 에러 처리 후 로그인 페이지로 이동 | ||
| toast.error('카카오 로그인에 실패했습니다.'); | ||
| navigate('/login'); | ||
| } | ||
| }, [isSuccess, isError, data, navigate]); | ||
|
|
||
| return null; | ||
| return <div>로그인 중입니다...</div>; | ||
| } |
| useEffect(() => { | ||
| if (authData && !isLoading && !apiError && shouldCallApi) { | ||
| console.log('OAuth 인증 성공!', authData); | ||
|
|
||
| // refreshToken을 localStorage에 저장 | ||
| localStorage.setItem('refreshToken', authData.refreshToken); | ||
| if (isSuccess && data) { | ||
| authStorage.refreshToken.set(data.refreshToken); | ||
|
|
||
| // 메인 페이지로 이동 | ||
| navigate(ROUTER_PATH.MAIN, { replace: true }); | ||
| navigate(ROUTER_PATH.ROOT); | ||
| } | ||
| }, [authData, isLoading, apiError, navigate, shouldCallApi]); | ||
|
|
||
| if (isLoading && shouldCallApi) { | ||
| return ( | ||
| <div className='flex min-h-screen items-center justify-center'> | ||
| <div className='text-center'> | ||
| <div className='mb-4'> | ||
| <div className='mx-auto h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent'></div> | ||
| </div> | ||
| <p className='text-lg font-medium text-gray-700'>인증 처리 중...</p> | ||
| <p className='mt-2 text-sm text-gray-500'>잠시만 기다려주세요.</p> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| if (error) { | ||
| return ( | ||
| <div className='flex min-h-screen items-center justify-center'> | ||
| <div className='text-center'> | ||
| <div className='mb-4'> | ||
| <div className='mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-red-100'> | ||
| <svg | ||
| className='h-6 w-6 text-red-600' | ||
| fill='none' | ||
| viewBox='0 0 24 24' | ||
| stroke='currentColor' | ||
| > | ||
| <path | ||
| strokeLinecap='round' | ||
| strokeLinejoin='round' | ||
| strokeWidth={2} | ||
| d='M6 18L18 6M6 6l12 12' | ||
| /> | ||
| </svg> | ||
| </div> | ||
| </div> | ||
| <h2 className='mb-2 text-xl font-semibold text-gray-900'>인증 실패</h2> | ||
| <p className='mb-4 text-gray-600'>{error}</p> | ||
| <button | ||
| onClick={() => navigate(ROUTER_PATH.LOGIN)} | ||
| className='rounded-lg bg-blue-500 px-4 py-2 text-white transition-colors hover:bg-blue-600' | ||
| > | ||
| 로그인 페이지로 돌아가기 | ||
| </button> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
| if (isError) { | ||
| // 실패 시, 에러 처리 후 로그인 페이지로 이동 | ||
| toast.error('카카오 로그인에 실패했습니다.'); | ||
| navigate('/login'); | ||
| } | ||
| }, [isSuccess, isError, data, navigate]); | ||
|
|
There was a problem hiding this comment.
useEffect 내의 두 if 문은 상호 배타적인 조건을 검사하므로 if-else if 구조로 변경하면 코드의 가독성과 의도를 더 명확하게 할 수 있습니다.
useEffect(() => {
if (isSuccess && data) {
authStorage.refreshToken.set(data.refreshToken);
navigate(ROUTER_PATH.ROOT);
} else if (isError) {
// 실패 시, 에러 처리 후 로그인 페이지로 이동
toast.error('카카오 로그인에 실패했습니다.');
navigate('/login');
}
}, [isSuccess, isError, data, navigate]);
| const set = (value: AuthStorageKey[T]) => { | ||
| if (value === undefined || value === null) { | ||
| return storage.removeItem(storageKey); | ||
| } | ||
|
|
||
| const stringifiedValue = JSON.stringify(value); | ||
|
|
||
| storage.setItem(storageKey, stringifiedValue); | ||
| }; |
There was a problem hiding this comment.
set 함수의 value 파라미터 타입은 AuthStorageKey[T] (즉, string)으로 지정되어 있습니다. 이로 인해 value === undefined || value === null 조건문은 TypeScript의 strictNullChecks 옵션이 활성화된 경우 항상 false가 되어 사실상 도달할 수 없는 코드가 됩니다.
storage.removeItem을 호출하는 의도를 명확히 하려면, value의 타입을 AuthStorageKey[T] | null | undefined로 변경하여 null 또는 undefined를 명시적으로 허용하는 것이 좋습니다.
const set = (value: AuthStorageKey[T] | null | undefined) => {
if (value === undefined || value === null) {
return storage.removeItem(storageKey);
}
const stringifiedValue = JSON.stringify(value);
storage.setItem(storageKey, stringifiedValue);
};
📝 요약 (Summary)
카카오 로그인 기능을 개선하여 더 나은 사용자 경험과 코드 구조를 제공합니다. OAuth 리다이렉트 로직을 훅으로 분리하고, 인증 저장소 모듈을 추가하여 상태 관리를 개선했습니다.
✅ 주요 변경 사항 (Key Changes)
💻 상세 구현 내용 (Implementation Details)
카카오 로그인 훅 구현
useKakaoLogin훅: OAuth 리다이렉트 로직을 별도 훅으로 분리인증 저장소 모듈 추가
auth-store모듈: 인증 관련 상태 및 유틸리티 함수 통합OAuth 리다이렉트 페이지 개선
타입 정의 개선
카카오 로그인 버튼 개선
🚀 트러블 슈팅 (Trouble Shooting)
📸 스크린샷 (Screenshots)
[개선된 카카오 로그인 버튼 및 로딩 상태 스크린샷을 여기에 추가해주세요]
#️⃣ 관련 이슈 (Related Issues)