| // src/context/AuthContext.tsx | |
| "use client"; | |
| import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from "react"; | |
| import api, { setCsrfToken } from "@/lib/api"; | |
| import type { User } from "@/types"; | |
| // ============================================ | |
| // Types | |
| // ============================================ | |
| interface AuthContextType { | |
| user: User | null; | |
| accessToken: string | null; | |
| isAuthenticated: boolean; | |
| login: (username: string, password: string) => Promise<"online" | "offline" | "twoFactor">; | |
| verifyTwoFactor: (code: string) => Promise<void>; | |
| twoFactorChallenge: { tempToken: string; username: string } | null; | |
| clearTwoFactorChallenge: () => void; | |
| logout: () => Promise<void>; | |
| isLoading: boolean; | |
| isOfflineMode: boolean; | |
| refreshUser: () => Promise<void>; | |
| updateUserStatus: (status: 'online' | 'away' | 'busy' | 'offline') => Promise<void>; | |
| } | |
| // ============================================ | |
| // Constants | |
| // ============================================ | |
| const AUTH_TOKEN_KEY = "auth_token"; | |
| const AUTH_USER_CACHE_KEY = "auth_user_cache"; | |
| const OFFLINE_SESSION_KEY = "auth_offline_session"; | |
| // ============================================ | |
| // Context | |
| // ============================================ | |
| const AuthContext = createContext<AuthContextType | null>(null); | |
| export const AuthProvider = ({ children }: { children: ReactNode }) => { | |
| const [user, setUser] = useState<User | null>(null); | |
| const [accessToken, setAccessToken] = useState<string | null>(() => | |
| localStorage.getItem(AUTH_TOKEN_KEY) | |
| ); | |
| const [isLoading, setIsLoading] = useState(true); | |
| const [isOfflineMode, setIsOfflineMode] = useState(false); | |
| const [twoFactorChallenge, setTwoFactorChallenge] = useState<{ tempToken: string; username: string } | null>(null); | |
| // ============================================ | |
| // Cache Helpers | |
| // ============================================ | |
| const cacheUser = useCallback((nextUser: User | null) => { | |
| if (nextUser) { | |
| localStorage.setItem(AUTH_USER_CACHE_KEY, JSON.stringify(nextUser)); | |
| } else { | |
| localStorage.removeItem(AUTH_USER_CACHE_KEY); | |
| } | |
| }, []); | |
| const readCachedUser = useCallback((): User | null => { | |
| try { | |
| const raw = localStorage.getItem(AUTH_USER_CACHE_KEY); | |
| return raw ? (JSON.parse(raw) as User) : null; | |
| } catch { | |
| localStorage.removeItem(AUTH_USER_CACHE_KEY); | |
| return null; | |
| } | |
| }, []); | |
| const isNetworkError = (err: any) => !err?.response; | |
| // ============================================ | |
| // Offline Session | |
| // ============================================ | |
| const startOfflineSession = useCallback((cachedUser: User) => { | |
| setUser(cachedUser); | |
| setIsOfflineMode(true); | |
| setTwoFactorChallenge(null); | |
| localStorage.setItem(OFFLINE_SESSION_KEY, "true"); | |
| }, []); | |
| // ============================================ | |
| // Apply Authenticated Session | |
| // ============================================ | |
| const applyAuthenticatedSession = useCallback(async (data: any) => { | |
| const token = data.token || data.access_token; | |
| if (token) { | |
| localStorage.setItem(AUTH_TOKEN_KEY, token); | |
| setAccessToken(token); | |
| // Save token in cookie | |
| document.cookie = `${AUTH_TOKEN_KEY}=${token}; path=/; max-age=604800; SameSite=Lax`; | |
| } else { | |
| console.warn("Auth response missing token", data); | |
| } | |
| if (data.csrfToken || data.csrf_token) { | |
| setCsrfToken(data.csrfToken || data.csrf_token); | |
| } | |
| if (data.user) { | |
| setUser(data.user); | |
| cacheUser(data.user); | |
| } else { | |
| const me = await api.get("/auth/me"); | |
| setUser(me.data); | |
| cacheUser(me.data); | |
| } | |
| setTwoFactorChallenge(null); | |
| setIsOfflineMode(false); | |
| localStorage.removeItem(OFFLINE_SESSION_KEY); | |
| }, [cacheUser]); | |
| // ============================================ | |
| // Fetch User | |
| // ============================================ | |
| const fetchUser = useCallback(async () => { | |
| const token = localStorage.getItem(AUTH_TOKEN_KEY); | |
| setAccessToken(token); | |
| if (!token) { | |
| const cachedUser = readCachedUser(); | |
| const wantsOfflineSession = localStorage.getItem(OFFLINE_SESSION_KEY) === "true"; | |
| if (cachedUser && (wantsOfflineSession || (typeof navigator !== "undefined" && !navigator.onLine))) { | |
| startOfflineSession(cachedUser); | |
| } else { | |
| setUser(null); | |
| setIsOfflineMode(false); | |
| localStorage.removeItem(OFFLINE_SESSION_KEY); | |
| } | |
| setIsLoading(false); | |
| return; | |
| } | |
| try { | |
| const res = await api.get("/auth/me"); | |
| setUser(res.data); | |
| cacheUser(res.data); | |
| setIsOfflineMode(false); | |
| localStorage.removeItem(OFFLINE_SESSION_KEY); | |
| } catch (err: any) { | |
| console.error("Failed to fetch user:", err); | |
| if (isNetworkError(err)) { | |
| const cachedUser = readCachedUser(); | |
| if (cachedUser) { | |
| startOfflineSession(cachedUser); | |
| setIsLoading(false); | |
| return; | |
| } | |
| } | |
| setUser(null); | |
| setIsOfflineMode(false); | |
| localStorage.removeItem(OFFLINE_SESSION_KEY); | |
| if (err.response?.status === 401) { | |
| localStorage.removeItem(AUTH_TOKEN_KEY); | |
| setAccessToken(null); | |
| cacheUser(null); | |
| setCsrfToken(null as any); | |
| } | |
| } finally { | |
| setIsLoading(false); | |
| } | |
| }, [cacheUser, readCachedUser, startOfflineSession]); | |
| // ============================================ | |
| // Login | |
| // ============================================ | |
| const login = async (username: string, password: string): Promise<"online" | "offline" | "twoFactor"> => { | |
| setIsLoading(true); | |
| try { | |
| const res = await api.post("/auth/login", { username, password }); | |
| if (res.data?.requiresTwoFactor && res.data?.tempToken) { | |
| setTwoFactorChallenge({ | |
| tempToken: res.data.tempToken, | |
| username: res.data.username || username, | |
| }); | |
| return "twoFactor"; | |
| } | |
| await applyAuthenticatedSession(res.data); | |
| return "online"; | |
| } catch (error) { | |
| if (isNetworkError(error)) { | |
| const cachedUser = readCachedUser(); | |
| const requested = username.trim().toLowerCase(); | |
| const matchesCachedUser = cachedUser && | |
| [cachedUser.username, cachedUser.email] | |
| .filter(Boolean) | |
| .some((value) => value!.toLowerCase() === requested); | |
| if (cachedUser && matchesCachedUser) { | |
| startOfflineSession(cachedUser); | |
| return "offline"; | |
| } | |
| } | |
| console.error("Login failed:", error); | |
| throw error; | |
| } finally { | |
| setIsLoading(false); | |
| } | |
| }; | |
| // ============================================ | |
| // Verify Two-Factor | |
| // ============================================ | |
| const verifyTwoFactor = async (code: string) => { | |
| if (!twoFactorChallenge) { | |
| throw new Error("No two-factor challenge is active"); | |
| } | |
| setIsLoading(true); | |
| try { | |
| const res = await api.post("/auth/login/2fa", { | |
| tempToken: twoFactorChallenge.tempToken, | |
| code, | |
| }); | |
| await applyAuthenticatedSession(res.data); | |
| } finally { | |
| setIsLoading(false); | |
| } | |
| }; | |
| const clearTwoFactorChallenge = useCallback(() => setTwoFactorChallenge(null), []); | |
| // ============================================ | |
| // Logout | |
| // ============================================ | |
| const logout = async () => { | |
| setIsLoading(true); | |
| try { | |
| await api.post("/auth/logout"); | |
| } catch (error) { | |
| console.error("Logout API error:", error); | |
| } finally { | |
| setUser(null); | |
| setIsOfflineMode(false); | |
| setTwoFactorChallenge(null); | |
| localStorage.removeItem(AUTH_TOKEN_KEY); | |
| setAccessToken(null); | |
| localStorage.removeItem(OFFLINE_SESSION_KEY); | |
| setCsrfToken(null as any); | |
| // Remove cookie | |
| document.cookie = `${AUTH_TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`; | |
| window.dispatchEvent(new CustomEvent("auth:session-expired")); | |
| } | |
| }; | |
| const refreshUser = async () => { | |
| await fetchUser(); | |
| }; | |
| const updateUserStatus = async (status: 'online' | 'away' | 'busy' | 'offline') => { | |
| if (!user) return; | |
| try { | |
| setUser({ ...user, status }); | |
| cacheUser({ ...user, status }); | |
| document.cookie = `user_status=${status}; path=/; max-age=604800; SameSite=Lax`; | |
| await api.patch('/auth/me/status', { status }).catch(() => {}); | |
| } catch (error) { | |
| console.warn("Could not update user status", error); | |
| } | |
| }; | |
| // ============================================ | |
| // Effects | |
| // ============================================ | |
| useEffect(() => { | |
| fetchUser(); | |
| }, [fetchUser]); | |
| useEffect(() => { | |
| const handleSessionExpired = () => { | |
| setUser(null); | |
| setIsOfflineMode(false); | |
| setTwoFactorChallenge(null); | |
| localStorage.removeItem(AUTH_TOKEN_KEY); | |
| setAccessToken(null); | |
| localStorage.removeItem(OFFLINE_SESSION_KEY); | |
| setCsrfToken(null as any); | |
| setIsLoading(false); | |
| }; | |
| window.addEventListener("auth:session-expired", handleSessionExpired); | |
| return () => window.removeEventListener("auth:session-expired", handleSessionExpired); | |
| }, []); | |
| // ============================================ | |
| // Provider Value | |
| // ============================================ | |
| const value: AuthContextType = { | |
| user, | |
| accessToken, | |
| isAuthenticated: !!user, | |
| login, | |
| verifyTwoFactor, | |
| twoFactorChallenge, | |
| clearTwoFactorChallenge, | |
| logout, | |
| isLoading, | |
| isOfflineMode, | |
| refreshUser, | |
| updateUserStatus, | |
| }; | |
| return ( | |
| <AuthContext.Provider value={value}> | |
| {children} | |
| </AuthContext.Provider> | |
| ); | |
| }; | |
| export const useAuth = () => { | |
| const ctx = useContext(AuthContext); | |
| if (!ctx) throw new Error("useAuth must be used within AuthProvider"); | |
| return ctx; | |
| }; |
Xet Storage Details
- Size:
- 9.94 kB
- Xet hash:
- 328f4692bdc937ec7fd09031ac047c149b57ad747f80fb7fc2ae356723c54c1c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.