import { useEffect } from 'react'; import { useNavigate } from '@tanstack/react-router'; import { useAuthStore } from './store'; /** * Watches the auth store and redirects to `/login` if the user becomes * anonymous mid-session (e.g. logout in another tab, refresh-cookie expiry, * server-side revocation). * * Used inside the `_authed` route layout (lands in 1.7) as belt-and-braces * alongside TanStack Router's `beforeLoad` guard. * * Does nothing while auth state is `unknown` or `authenticating` — the * layout shows a loading spinner during those windows. */ export function useRequireAuth() { const status = useAuthStore((s) => s.status); const navigate = useNavigate(); useEffect(() => { if (status === 'anonymous') { void navigate({ to: '/login' }); } }, [status, navigate]); return status; } /** * Role-aware guard. Bounces the user to `/` if their `role` is not in the * allowed list. No-op while not authenticated (the surrounding layout * already handles the anonymous case). * * Phase 1 has no role-restricted routes — every authenticated user is * effectively admin until [[directus]] Phase 4. Reserved for Phase 2+. * * Example (Phase 2): * useRequireRole(['race-director', 'org-admin']); */ export function useRequireRole(allowedRoles: readonly string[]) { const user = useAuthStore((s) => (s.status === 'authenticated' ? s.user : null)); const navigate = useNavigate(); useEffect(() => { if (!user) return; if (user.role && !allowedRoles.includes(user.role)) { void navigate({ to: '/', replace: true }); } }, [user, allowedRoles, navigate]); }