/* ═══════════════════════════════════════════════════════════════ AUTH CONTEXT One fetch of /api/auth/me at mount decides whether anyone is signed in. There's no token to store: the session cookie is HttpOnly, so this code can't read it and neither can anything injected into the page. "Am I signed in" is always a question for the server. RequireAuth guards routes. Worth being clear about what that does and doesn't do: it hides the interface, not the data. The protection is the 401 from /api/admin, this only stops someone staring at an empty table. ═══════════════════════════════════════════════════════════════ */ import { createContext, useCallback, useContext, useEffect, useState } from "react"; import { Navigate, Outlet, useLocation } from "react-router-dom"; import { get, post, ApiError } from "./api.ts"; const AuthContext = createContext(null); export function AuthProvider({ children }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { let ignore = false; get("/auth/me", { ttl: 0 }) .then((data) => { if (!ignore) setUser(data.user); }) .catch(() => { if (!ignore) setUser(null); // 401 is the normal case }) .finally(() => { if (!ignore) setLoading(false); }); return () => { ignore = true; }; }, []); const login = useCallback(async (email, password) => { const data = await post("/auth/login", { email, password }); setUser(data.user); return data.user; }, []); const logout = useCallback(async () => { try { await post("/auth/logout", {}); } finally { // Whatever the server said, this browser is done. setUser(null); } }, []); return ( {children} ); } export function useAuth() { const value = useContext(AuthContext); if (!value) throw new Error("useAuth used outside AuthProvider"); return value; } /* Signals a session that ended while the page was open, the admin pages call this when a request comes back 401. */ export function isUnauthorized(error) { return error instanceof ApiError && error.status === 401; } export function RequireAuth() { const { user, loading } = useAuth(); const location = useLocation(); if (loading) { return (
Checking your session…
); } if (!user) { // `from` lets the login page send them back where they aimed. return ; } return ; }