|
| 1 | +import { create } from 'zustand'; |
| 2 | +import { customToast } from '../components/toast/CustomToastUtils'; |
| 3 | + |
| 4 | +interface User { |
| 5 | + id: string; |
| 6 | + email: string; |
| 7 | + nickname: string; |
| 8 | + isFirstLogin: boolean; |
| 9 | + abv_degree?: number; |
| 10 | + provider?: 'naver' | 'kakao' | 'google'; |
| 11 | +} |
| 12 | + |
| 13 | +interface AuthState { |
| 14 | + user: User | null; |
| 15 | + accessToken: string | null; |
| 16 | + isLoggedIn: boolean; |
| 17 | + setUser: (user: User, token: string) => void; |
| 18 | + logout: () => Promise<void>; |
| 19 | + loginWithProvider: (provider: User['provider']) => void; |
| 20 | + |
| 21 | + updateUser: () => Promise<User | null>; |
| 22 | +} |
| 23 | + |
| 24 | +export const useAuthStore = create<AuthState>((set) => ({ |
| 25 | + user: null, |
| 26 | + accessToken: null, |
| 27 | + isLoggedIn: false, |
| 28 | + |
| 29 | + loginWithProvider: (provider) => { |
| 30 | + window.location.href = `http://localhost:8080/oauth2/authorization/${provider}`; |
| 31 | + }, |
| 32 | + |
| 33 | + setUser: (user, token) => { |
| 34 | + const updatedUser = { ...user, abv_degree: 5.0 }; |
| 35 | + set({ user: updatedUser, accessToken: token, isLoggedIn: true }); |
| 36 | + |
| 37 | + customToast.success(`${updatedUser.nickname}님, 로그인 성공 🎉`); |
| 38 | + }, |
| 39 | + |
| 40 | + logout: async () => { |
| 41 | + try { |
| 42 | + await fetch('http://localhost:8080/user/auth/logout', { |
| 43 | + method: 'POST', |
| 44 | + credentials: 'include', |
| 45 | + }); |
| 46 | + |
| 47 | + customToast.success('로그아웃 되었습니다.'); |
| 48 | + set({ user: null, accessToken: null, isLoggedIn: false }); |
| 49 | + } catch (err) { |
| 50 | + customToast.error('로그아웃 실패❌ \n 다시 시도해주세요.'); |
| 51 | + console.error('로그아웃 실패', err); |
| 52 | + } |
| 53 | + }, |
| 54 | + |
| 55 | + updateUser: async () => { |
| 56 | + try { |
| 57 | + const res = await fetch('http://localhost:8080/user/auth/refresh', { |
| 58 | + method: 'POST', |
| 59 | + credentials: 'include', |
| 60 | + headers: { 'Content-Type': 'application/json' }, |
| 61 | + }); |
| 62 | + |
| 63 | + if (!res.ok) throw new Error('토큰 갱신 실패'); |
| 64 | + const data = await res.json(); |
| 65 | + |
| 66 | + console.log('updateUser response:', data); |
| 67 | + const userInfo = data?.data?.user; |
| 68 | + const accessToken = data?.data?.accessToken; |
| 69 | + |
| 70 | + if (userInfo && accessToken) { |
| 71 | + set({ user: userInfo, accessToken, isLoggedIn: true }); |
| 72 | + console.log('토큰 및 유저 정보 갱신 완료:', userInfo); |
| 73 | + return userInfo; |
| 74 | + } |
| 75 | + |
| 76 | + return null; |
| 77 | + } catch (err) { |
| 78 | + console.error('updateUser 실패', err); |
| 79 | + set({ accessToken: null, user: null, isLoggedIn: false }); |
| 80 | + return null; |
| 81 | + } |
| 82 | + }, |
| 83 | +})); |
0 commit comments