inogen/app/contexts/auth-context.tsx
2026-10-18 18:12:59 +03:30

135 lines
3.6 KiB
TypeScript

import React, { createContext, useContext, useEffect, useState } from "react";
import toast from "react-hot-toast";
import apiService, { 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<boolean>;
logout: () => Promise<void>;
validateToken: () => Promise<boolean>;
}
const AuthContext = createContext<AuthContextType | undefined>(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<User | null>(null);
const [token, setToken] = useState<SessionMarker | null>(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");
};
const applySession = (current: CurrentUser) => {
setUser(toUser(current));
setToken(marker);
};
const validateToken = async (): Promise<boolean> => {
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<boolean> => {
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 (error) {
console.error("Logout API call failed:", error);
} finally {
try {
sessionStorage.setItem("justLoggedOut", "1");
} catch {}
clearAuthData();
toast.success("با موفقیت خارج شدید", { id: "logout-success" });
}
};
return (
<AuthContext.Provider
value={{ user, token, isAuthenticated: !!user, isLoading, login, logout, validateToken }}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) throw new Error("useAuth must be used within an AuthProvider");
return context;
}