|
1 | | -import axios from 'axios'; |
2 | 1 | import { useEffect } from 'react'; |
3 | 2 | import { useNavigate } from 'react-router-dom'; |
4 | 3 | import { LoadingSpinner } from '@/shared/components/LoadingSpinner'; |
| 4 | +import { postAuthCode } from './api/postAuthCode'; |
| 5 | +import { setAccessToken, setTemporaryToken } from '../Signup/utils/token'; |
| 6 | +import type { ErrorResponse } from '../Signup/type/error'; |
| 7 | +import type { AxiosError } from 'axios'; |
| 8 | + |
| 9 | +interface LoginSuccessResponse { |
| 10 | + status: 'LOGIN_SUCCESS'; |
| 11 | + accessToken: string; |
| 12 | + refreshToken: string; |
| 13 | +} |
| 14 | + |
| 15 | +interface RegistrationRequiredResponse { |
| 16 | + status: 'REGISTRATION_REQUIRED'; |
| 17 | + temporaryToken: string; |
| 18 | +} |
| 19 | + |
| 20 | +type LoginResponse = LoginSuccessResponse | RegistrationRequiredResponse; |
5 | 21 |
|
6 | 22 | export const KakaoCallback = () => { |
7 | 23 | const navigate = useNavigate(); |
8 | 24 |
|
9 | 25 | useEffect(() => { |
10 | 26 | const code = new URL(window.location.href).searchParams.get('code'); |
11 | | - if (!code) return; |
12 | 27 |
|
13 | | - console.log(code); |
| 28 | + if (!code) { |
| 29 | + navigate('/login'); |
| 30 | + return; |
| 31 | + } |
| 32 | + |
14 | 33 | const fetchToken = async () => { |
15 | 34 | try { |
16 | | - const res = axios.post(`${import.meta.env.VITE_API_BASE_URL}/auth/kakao/login`, { |
17 | | - authorizationCode: code, |
18 | | - }); |
19 | | - console.log('응답res ', res); |
20 | | - |
21 | | - // CASE 1) 기존 회원 |
22 | | - |
23 | | - // 1-1. accessToken, refreshToken 발급 |
24 | | - // localStorage.setItem('accessToken', res.data.accessToken); |
25 | | - // localStorage.setItem('refreshToken ', res.data.refreshToken)- (수정전) |
26 | | - // refreshToken은 httpOnly 관리(수정후) |
27 | | - // ------------------------------------------------------------ |
28 | | - // 2-2 main 페이지 이동 |
29 | | - // navigate('/'); // 로그인 후 홈으로 이동 |
30 | | - |
31 | | - // CASE 2) 기존 회원 |
32 | | - // 2-1. 임시 토큰 |
33 | | - // 2-2. navigate('/signup') |
34 | | - } catch (error) { |
35 | | - console.log('error:', error); |
| 35 | + const response: LoginResponse = await postAuthCode(code); |
| 36 | + |
| 37 | + switch (response.status) { |
| 38 | + case 'LOGIN_SUCCESS': |
| 39 | + setAccessToken(response.accessToken); |
| 40 | + navigate('/'); |
| 41 | + break; |
| 42 | + case 'REGISTRATION_REQUIRED': |
| 43 | + setTemporaryToken(response.temporaryToken); |
| 44 | + navigate('/signup'); |
| 45 | + break; |
| 46 | + } |
| 47 | + } catch (e) { |
| 48 | + const error = e as AxiosError<ErrorResponse>; |
| 49 | + return new Error(error.response?.data.message); |
36 | 50 | } |
37 | 51 | }; |
38 | | - |
39 | 52 | fetchToken(); |
40 | 53 | }, [navigate]); |
41 | 54 |
|
|
0 commit comments