import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import { useQueryClient } from '@tanstack/react-query'; import { ApiError, auth as authApi, type AuthUser } from '../api/client'; import { refreshManifest } from '../lib/manifest'; import { useManifest } from '../hooks/useManifest'; import { loginPath, safeReturnTo } from './returnTo'; import { AuthContext } from './context'; import type { AuthStatus } from './context'; export function AuthProvider({ children }: { children: ReactNode }) { const { auth: manifestAuth } = useManifest(); const enabled = manifestAuth.enabled; const location = useLocation(); const navigate = useNavigate(); const queryClient = useQueryClient(); const [status, setStatus] = useState('checking'); const [user, setUser] = useState(null); const statusRef = useRef(status); const enabledRef = useRef(enabled); const handledUnauthorized = useRef(false); const checkInFlight = useRef | null>(null); useEffect(() => { enabledRef.current = enabled; statusRef.current = status; }, [enabled, status]); const updateStatus = useCallback((next: AuthStatus) => { statusRef.current = next; setStatus(next); }, []); const checkSession = useCallback(async () => { if (!enabledRef.current) { setUser(null); updateStatus('disabled'); return; } if (checkInFlight.current) return checkInFlight.current; updateStatus('checking'); const check = authApi .me() .then((account) => { setUser(account); handledUnauthorized.current = false; updateStatus('authenticated'); }) .catch((error: unknown) => { setUser(null); updateStatus( error instanceof ApiError && error.status === 401 ? 'unauthenticated' : 'error', ); }) .finally(() => { checkInFlight.current = null; }); checkInFlight.current = check; return check; }, [updateStatus]); useEffect(() => { if (!enabled) { // This synchronizes the session state with the server's feature flag. // eslint-disable-next-line react-hooks/set-state-in-effect setUser(null); updateStatus('disabled'); queryClient.clear(); return; } void checkSession(); }, [enabled, checkSession, queryClient, updateStatus]); useEffect(() => { const onUnauthorized = (event: Event) => { if (!enabledRef.current) return; if (handledUnauthorized.current) { event.preventDefault(); return; } if (statusRef.current !== 'authenticated') return; event.preventDefault(); handledUnauthorized.current = true; queryClient.clear(); setUser(null); updateStatus('unauthenticated'); const target = safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios'; navigate(loginPath(target, true), { replace: true }); }; window.addEventListener('liqa:unauthorized', onUnauthorized); return () => window.removeEventListener('liqa:unauthorized', onUnauthorized); }, [location.hash, location.pathname, location.search, navigate, queryClient, updateStatus]); const login = useCallback( async (username: string, password: string) => { let account: AuthUser; try { account = await authApi.login(username, password); } catch (error) { if (error instanceof ApiError && error.status === 404) await refreshManifest(); throw error; } queryClient.clear(); handledUnauthorized.current = false; setUser(account); updateStatus('authenticated'); }, [queryClient, updateStatus], ); const logout = useCallback(async () => { try { await authApi.logout(); } catch (error) { if (!(error instanceof ApiError && error.status === 401)) { await checkSession(); throw error; } } queryClient.clear(); setUser(null); updateStatus('unauthenticated'); handledUnauthorized.current = false; navigate('/login?notice=signedOut', { replace: true }); }, [checkSession, navigate, queryClient, updateStatus]); return ( {children} ); }