import { useState, useEffect, createContext, useContext } from "react"; export interface User { did: string; handle: string; email?: string; } export interface SessionData { authenticated: boolean; user?: User; accessToken?: string; } // Export context and hook for use in other components export const SessionContext = createContext<{ session: SessionData | null; isLoading: boolean; } | null>(null); export function useSessionContext() { const context = useContext(SessionContext); if (!context) { throw new Error("useSessionContext must be used within SessionProvider"); } return context; } /** * Hook to check session status from the server. * * This replaces the client-side AuthProvider from @slices/react. * Instead of managing OAuth tokens in the browser, we check the * server session which is managed via HTTP-only cookies. */ export function useSession() { const [session, setSession] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { async function checkSession() { try { const response = await fetch("/api/session", { credentials: "include", // Important: include cookies }); if (response.ok) { const data = await response.json(); setSession(data); } else { setSession({ authenticated: false }); } } catch (error) { console.error("Failed to check session:", error); setSession({ authenticated: false }); } finally { setIsLoading(false); } } checkSession(); }, []); return { session, isLoading }; } /** * Simple logout function that calls the server logout endpoint. */ export async function logout() { try { await fetch("/logout", { method: "POST", credentials: "include", }); // Redirect to login page globalThis.location.href = "/login"; } catch (error) { console.error("Logout failed:", error); } }