import React, { createContext, useContext, useEffect, useState } from "react"; import toast from "react-hot-toast"; import apiService, { AUTH_CLEARED_EVENT, AUTH_INVALIDATED_EVENT, type CurrentUser } from "~/lib/api"; interface User { id: string; name: string; family: string; email: string; username: string; status: boolean; roles: string[]; } // Existing route guards only need a truthy accessToken. Authentication itself is // held by the HttpOnly Identity cookie and never copied to browser storage. interface SessionMarker { accessToken: "cookie-session"; } interface AuthContextType { user: User | null; token: SessionMarker | null; isAuthenticated: boolean; isLoading: boolean; login: (username: string, password: string) => Promise; logout: () => Promise; validateToken: () => Promise; } const AuthContext = createContext(undefined); const marker: SessionMarker = { accessToken: "cookie-session" }; function toUser(current: CurrentUser): User { return { id: current.id, name: current.displayName || current.userName, family: "", email: "", username: current.userName, status: true, roles: current.roles, }; } export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [token, setToken] = useState(null); const [isLoading, setIsLoading] = useState(true); const clearAuthData = () => { setUser(null); setToken(null); // Remove legacy bearer credentials left by earlier versions. localStorage.removeItem("auth_user"); localStorage.removeItem("auth_token"); }; useEffect(() => { const clear = () => clearAuthData(); window.addEventListener(AUTH_INVALIDATED_EVENT, clear); window.addEventListener(AUTH_CLEARED_EVENT, clear); return () => { window.removeEventListener(AUTH_INVALIDATED_EVENT, clear); window.removeEventListener(AUTH_CLEARED_EVENT, clear); }; }, []); const applySession = (current: CurrentUser) => { setUser(toUser(current)); setToken(marker); }; const validateToken = async (): Promise => { try { applySession(await apiService.currentUser()); return true; } catch { clearAuthData(); return false; } }; useEffect(() => { void (async () => { await validateToken(); setIsLoading(false); })(); }, []); useEffect(() => { if (!user) return; const interval = window.setInterval(() => void validateToken(), 5 * 60 * 1000); return () => window.clearInterval(interval); }, [user?.id]); const login = async (username: string, password: string): Promise => { if (!username || !password) { toast.error("لطفاً تمام فیلدها را پر کنید"); return false; } setIsLoading(true); try { const current = await apiService.login(username, password); applySession(current); toast.success(`خوش آمدید ${current.displayName || current.userName}`); return true; } catch (error) { clearAuthData(); toast.error(error instanceof Error ? error.message : "ورود ناموفق بود"); return false; } finally { setIsLoading(false); } }; const logout = async () => { try { await apiService.logout(); } catch { // The local session is cleared even if the network request fails. } finally { try { sessionStorage.setItem("justLoggedOut", "1"); } catch {} clearAuthData(); window.location.assign(window.location.pathname.startsWith("/admin") ? "/admin/login" : "/login"); toast.success("با موفقیت خارج شدید", { id: "logout-success" }); } }; return ( {children} ); } export function useAuth() { const context = useContext(AuthContext); if (!context) throw new Error("useAuth must be used within an AuthProvider"); return context; }