|
| 1 | +import { |
| 2 | + createContext, |
| 3 | + useContext, |
| 4 | + useState, |
| 5 | + useEffect, |
| 6 | + useCallback, |
| 7 | +} from "react"; |
| 8 | + |
| 9 | +import { useCheckUser } from "~/service/auth"; |
| 10 | + |
| 11 | +type LoginResponseType = { |
| 12 | + token: string; |
| 13 | + expired: number; |
| 14 | +}; |
| 15 | + |
| 16 | +type AuthContextType = { |
| 17 | + isLogin: boolean; |
| 18 | + isLoading: boolean; |
| 19 | + handleLogin: (response: LoginResponseType) => void; |
| 20 | +}; |
| 21 | + |
| 22 | +const AuthContext = createContext<AuthContextType>({ |
| 23 | + isLogin: false, |
| 24 | + isLoading: false, |
| 25 | + handleLogin: () => {}, |
| 26 | +}); |
| 27 | + |
| 28 | +export default function AuthProvider({ |
| 29 | + children, |
| 30 | +}: { |
| 31 | + children: React.ReactNode; |
| 32 | +}) { |
| 33 | + const [isLogin, setIsLogin] = useState<boolean>(false); |
| 34 | + |
| 35 | + const { trigger, isMutating } = useCheckUser(); |
| 36 | + |
| 37 | + useEffect(() => { |
| 38 | + const abortController = new AbortController(); |
| 39 | + |
| 40 | + const checkUserStatus = async () => { |
| 41 | + const token = document.cookie |
| 42 | + .split("; ") |
| 43 | + .find((row) => row.startsWith("hexToken=")) |
| 44 | + ?.split("=")[1]; |
| 45 | + |
| 46 | + if (!token) { |
| 47 | + setIsLogin(false); |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + try { |
| 52 | + const response = await trigger(); |
| 53 | + if (response.success) { |
| 54 | + setIsLogin(true); |
| 55 | + } else { |
| 56 | + setIsLogin(false); |
| 57 | + } |
| 58 | + } catch (error) { |
| 59 | + if (!abortController.signal.aborted) { |
| 60 | + console.log("檢查使用者狀態時發生錯誤:", error); |
| 61 | + setIsLogin(false); |
| 62 | + } |
| 63 | + } |
| 64 | + }; |
| 65 | + |
| 66 | + checkUserStatus(); |
| 67 | + |
| 68 | + return () => { |
| 69 | + abortController.abort(); |
| 70 | + }; |
| 71 | + }, [trigger]); |
| 72 | + |
| 73 | + const handleLogin = useCallback( |
| 74 | + (response: LoginResponseType) => { |
| 75 | + setIsLogin(true); |
| 76 | + |
| 77 | + const { token, expired } = response; |
| 78 | + document.cookie = `hexToken=${token};expires=${new Date( |
| 79 | + expired |
| 80 | + ).toUTCString()};`; |
| 81 | + }, |
| 82 | + [setIsLogin] |
| 83 | + ); |
| 84 | + |
| 85 | + return ( |
| 86 | + <AuthContext.Provider |
| 87 | + value={{ isLogin, isLoading: isMutating, handleLogin }} |
| 88 | + > |
| 89 | + {children} |
| 90 | + </AuthContext.Provider> |
| 91 | + ); |
| 92 | +} |
| 93 | + |
| 94 | +export function useAuth() { |
| 95 | + const context = useContext(AuthContext); |
| 96 | + |
| 97 | + if (context === undefined) { |
| 98 | + throw new Error("useAuth must be used within a AuthProvider"); |
| 99 | + } |
| 100 | + |
| 101 | + return context; |
| 102 | +} |
0 commit comments