|
| 1 | +import { useNavigate } from 'react-router'; |
| 2 | +import loginApi from '../api/auth/login'; |
| 3 | +import getMeApi from '../api/auth/me'; |
| 4 | +import signupApi from '../api/auth/signup'; |
| 5 | +import socialApi from '../api/auth/social'; |
| 6 | +import type { |
| 7 | + LoginRequest, |
| 8 | + SignUpRequest, |
| 9 | + SocialLoginRequest, |
| 10 | +} from '../types/auth'; |
| 11 | +import useAuthStore from './useAuthStore'; |
| 12 | + |
| 13 | +export default function useAuth() { |
| 14 | + const navigate = useNavigate(); |
| 15 | + |
| 16 | + const { user, isLoggedIn, login, logout, updateUser } = useAuthStore( |
| 17 | + (state) => state |
| 18 | + ); |
| 19 | + |
| 20 | + // 1. μ΄λ©μΌ λ‘κ·ΈμΈ λ‘μ§ |
| 21 | + const handleLogin = async (data: LoginRequest) => { |
| 22 | + try { |
| 23 | + const { user, token } = await loginApi(data); |
| 24 | + login(user, token); // Zustand μ€ν μ΄ μ
λ°μ΄νΈ |
| 25 | + navigate('/'); // λ©μΈ νμ΄μ§λ‘ μ΄λ |
| 26 | + } catch (error) { |
| 27 | + console.error('Login failed:', error); |
| 28 | + alert('μμ΄λ λλ λΉλ°λ²νΈλ₯Ό νμΈν΄μ£ΌμΈμ.'); |
| 29 | + } |
| 30 | + }; |
| 31 | + |
| 32 | + // 2. μ΄λ©μΌ νμκ°μ
λ‘μ§ |
| 33 | + const handleSignUp = async (data: SignUpRequest) => { |
| 34 | + try { |
| 35 | + const { user, token } = await signupApi(data); |
| 36 | + login(user, token); |
| 37 | + navigate('/'); |
| 38 | + } catch (error) { |
| 39 | + console.error('Signup failed:', error); |
| 40 | + alert('νμκ°μ
μ€ μ€λ₯κ° λ°μνμ΅λλ€.'); |
| 41 | + } |
| 42 | + }; |
| 43 | + |
| 44 | + // 3. μμ
λ‘κ·ΈμΈ λ‘μ§ |
| 45 | + const handleSocialLogin = async (data: SocialLoginRequest) => { |
| 46 | + try { |
| 47 | + const { user, token } = await socialApi(data); |
| 48 | + login(user, token); |
| 49 | + navigate('/'); |
| 50 | + } catch (error) { |
| 51 | + console.error('Social login failed:', error); |
| 52 | + alert('μμ
λ‘κ·ΈμΈμ μ€ν¨νμ΅λλ€.'); |
| 53 | + } |
| 54 | + }; |
| 55 | + |
| 56 | + // 4. λ΄ μ 보 λκΈ°ν |
| 57 | + const refreshUser = async () => { |
| 58 | + if (!isLoggedIn) return; |
| 59 | + try { |
| 60 | + const userData = await getMeApi(); |
| 61 | + // μ μ μ 보μ κ·Έλ£Ή μ 보 λ±μ΄ λ΄κΈ΄ λ°μ΄ν°λ‘ μ€ν μ΄ κ°±μ |
| 62 | + updateUser(userData); |
| 63 | + } catch (error) { |
| 64 | + console.error('Refresh user failed:', error); |
| 65 | + handleLogout(); // ν ν°μ΄ μ ν¨νμ§ μμΌλ©΄ λ‘κ·Έμμ μ²λ¦¬ |
| 66 | + alert('μ μ μ 보 λκΈ°ν μ€ μ€λ₯κ° λ°μνμ΅λλ€.'); |
| 67 | + } |
| 68 | + }; |
| 69 | + |
| 70 | + // 5. λ‘κ·Έμμ λ‘μ§ |
| 71 | + const handleLogout = () => { |
| 72 | + logout(); // Zustand μν μ΄κΈ°ν |
| 73 | + navigate('/login'); |
| 74 | + }; |
| 75 | + |
| 76 | + return { |
| 77 | + user, |
| 78 | + isLoggedIn, |
| 79 | + handleLogin, |
| 80 | + handleSignUp, |
| 81 | + handleSocialLogin, |
| 82 | + refreshUser, |
| 83 | + handleLogout, |
| 84 | + }; |
| 85 | +} |
0 commit comments