import { useEffect, useState, createContext, useContext } from 'react' import type { User } from '../types' interface AuthCtx { user: User } const Ctx = createContext(null) export function useAuth() { const ctx = useContext(Ctx) if (!ctx) throw new Error('useAuth must be used inside AuthGate') return ctx } export default function AuthGate({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null) const [error, setError] = useState(null) useEffect(() => { fetch('/api/auth/verify?app=room-planner', { credentials: 'include' }) .then(r => { if (r.status === 401 || r.status === 403) { window.location.href = `/portal?redirect=${encodeURIComponent(window.location.href)}` return null } if (!r.ok) throw new Error(`Auth check failed: ${r.status}`) return r.json() }) .then(data => { if (data) setUser(data) }) .catch(err => setError(err.message)) }, []) if (error) { return (
Authentication error: {error}
) } if (!user) { return (
Loading…
) } return {children} }