authProvider.tsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use client';
  2. import { createContext, useContext, useEffect, useState, useCallback } from 'react';
  3. import { verifyAccessToken, refreshAccessToken } 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. let ret = await verifyAccessToken();
  23. if (!ret) {
  24. ret = await refreshAccessToken();
  25. }
  26. setIsAuthenticated(ret);
  27. setIsLoading(false);
  28. return ret;
  29. } catch {
  30. console.error("인증 확인 중 오류 발생");
  31. setIsAuthenticated(false);
  32. return false;
  33. }
  34. }, []);
  35. useEffect(() => {
  36. checkAuth();
  37. }, [checkAuth]);
  38. return (
  39. <AuthContext.Provider value={{ isLoading, isAuthenticated, setIsAuthenticated, checkAuth }}>
  40. {children}
  41. </AuthContext.Provider>
  42. );
  43. }
  44. // Context 사용을 위한 커스텀 훅
  45. export function useAuthContext() {
  46. return useContext(AuthContext);
  47. }