import React, { createContext, useContext, useState, useEffect, type ReactNode } from 'react'; interface User { email: string; name?: string; } interface AuthContextType { user: User | null; loading: boolean; login: (email: string, password: string) => Promise; logout: () => void; token: string | null; } const AuthContext = createContext({ user: null, loading: true, login: async () => false, logout: () => {}, token: null, }); export function useAuth() { return useContext(AuthContext); } export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null); const [token, setToken] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { // Check auth via HttpOnly cookie — no localStorage needed fetch('/api/admin/auth/session', { credentials: 'same-origin' }) .then(r => r.ok ? r.json() : null) .then(data => { if (data?.authenticated) setUser(data.user); }) .catch(() => {}) .finally(() => setLoading(false)); }, []); const login = async (email: string, password: string) => { const res = await fetch('/api/admin/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ email, password }), }); if (!res.ok) return false; const data = await res.json(); setToken(data.token); setUser(data.user); // Token is also set as HttpOnly cookie by the server return true; }; const logout = () => { setUser(null); setToken(null); document.cookie = 'admin_token=; Path=/; Max-Age=0'; }; return ( {children} ); } export function AuthGuard({ children }: { children: ReactNode }) { const { user, loading } = useAuth(); if (loading) return (
); if (!user) { window.location.href = '/admin/login'; return null; } return <>{children}; }