authProvider.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use client';
  2. import { createContext, useContext, useEffect, useState, useCallback } from 'react';
  3. import { checkAuthServer } from '@/lib/api/auth';
  4. // 인증 상태 Context
  5. const AuthContext = createContext<{
  6. isLoading: boolean;
  7. isAuthenticated: boolean;
  8. setIsAuthenticated: (value: boolean) => void;
  9. checkAuth: () => Promise<boolean>;
  10. }>({
  11. isLoading: true,
  12. isAuthenticated: false,
  13. setIsAuthenticated: () => {},
  14. checkAuth: async () => false
  15. });
  16. // Context Provider
  17. export function AuthProvider({ children }: { children: React.ReactNode }) {
  18. const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  19. const [isLoading, setIsLoading] = useState<boolean>(true);
  20. const checkAuth = useCallback(async (): Promise<boolean> => {
  21. try {
  22. const ret = await checkAuthServer();
  23. setIsAuthenticated(ret);
  24. setIsLoading(false);
  25. return ret;
  26. } catch {
  27. console.error("인증 확인 중 오류 발생");
  28. setIsAuthenticated(false);
  29. return false;
  30. }
  31. }, []);
  32. useEffect(() => {
  33. checkAuth();
  34. }, [checkAuth]);
  35. // 401 Auth:unauthroized 이벤트 수신
  36. useEffect(() => {
  37. const eventKey = 'auth:unauthorized';
  38. const handleUnauthorized = () => {
  39. setIsAuthenticated(false);
  40. localStorage.setItem('rememberMe', 'false');
  41. localStorage.removeItem('member');
  42. if (!window.location.pathname.startsWith('/login')) {
  43. window.location.replace(`/login?returnUrl=${encodeURIComponent(window.location.pathname + window.location.search)}`);
  44. }
  45. };
  46. window.addEventListener(eventKey, handleUnauthorized);
  47. return () => window.removeEventListener(eventKey, handleUnauthorized);
  48. }, []);
  49. return (
  50. <AuthContext.Provider value={{ isLoading, isAuthenticated, setIsAuthenticated, checkAuth }}>
  51. {children}
  52. </AuthContext.Provider>
  53. );
  54. }
  55. // Context 사용을 위한 커스텀 훅
  56. export function useAuthContext() {
  57. return useContext(AuthContext);
  58. }