'use client'; import { createContext, useContext, useEffect, useState, useCallback } from 'react'; import { checkAuthServer } from '@/lib/api/auth'; // 인증 상태 Context const AuthContext = createContext<{ isLoading: boolean; isAuthenticated: boolean; setIsAuthenticated: (value: boolean) => void; checkAuth: () => Promise; }>({ isLoading: true, isAuthenticated: false, setIsAuthenticated: () => {}, checkAuth: async () => false }); // Context Provider export function AuthProvider({ children }: { children: React.ReactNode }) { const [isAuthenticated, setIsAuthenticated] = useState(false); const [isLoading, setIsLoading] = useState(true); const checkAuth = useCallback(async (): Promise => { try { const ret = await checkAuthServer(); setIsAuthenticated(ret); setIsLoading(false); return ret; } catch { console.error("인증 확인 중 오류 발생"); setIsAuthenticated(false); return false; } }, []); useEffect(() => { checkAuth(); }, [checkAuth]); // 401 Auth:unauthroized 이벤트 수신 useEffect(() => { const eventKey = 'auth:unauthorized'; const handleUnauthorized = () => { setIsAuthenticated(false); localStorage.setItem('rememberMe', 'false'); localStorage.removeItem('member'); if (!window.location.pathname.startsWith('/login')) { window.location.replace(`/login?returnUrl=${encodeURIComponent(window.location.pathname + window.location.search)}`); } }; window.addEventListener(eventKey, handleUnauthorized); return () => window.removeEventListener(eventKey, handleUnauthorized); }, []); return ( {children} ); } // Context 사용을 위한 커스텀 훅 export function useAuthContext() { return useContext(AuthContext); }