import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from 'react'; import { API_BASE_URL } from '@/lib/api'; export function AuthGate({ children }: { children: ReactNode }) { const [role, setRole] = useState(null); const [checking, setChecking] = useState(true); const [token, setToken] = useState(''); const [error, setError] = useState(''); const [busy, setBusy] = useState(false); const checkSession = useCallback(async () => { try { const response = await fetch(`${API_BASE_URL}/api/auth/session`, { credentials: 'include' }); const session = await response.json(); setRole(response.ok && session.authenticated ? session.role : null); } catch { setError('Cannot reach the API. Check its URL and service status.'); } finally { setChecking(false); } }, []); useEffect(() => { void checkSession(); const expired = () => setRole(null); window.addEventListener('stock-bot-auth-required', expired); return () => window.removeEventListener('stock-bot-auth-required', expired); }, [checkSession]); const signIn = async (event: FormEvent) => { event.preventDefault(); setBusy(true); setError(''); try { const response = await fetch(`${API_BASE_URL}/api/auth/session`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); if (!response.ok) { throw new Error( response.status === 429 ? 'Too many attempts. Try again in a minute.' : 'Sign-in failed. Check your access token.' ); } const session = await response.json(); setRole(session.role); } catch (failure) { setError(failure instanceof Error ? failure.message : 'Sign-in failed'); } finally { setToken(''); setBusy(false); } }; const signOut = async () => { try { const response = await fetch(`${API_BASE_URL}/api/auth/session`, { method: 'DELETE', credentials: 'include', }); if (!response.ok) { throw new Error('Sign-out failed'); } setRole(null); } catch { setError('Sign-out failed. Please try again.'); } }; if (checking) { return (

Checking access…

); } if (role) { return ( <> {children}
{role === 'read' ? 'Read-only access' : 'Administrator access'} {error && ( {error} )}
); } return (
void signIn(event)} className="w-full max-w-sm space-y-4">

Stock Bot access

Enter your administrator or read-only access token. It is not stored in your browser.

setToken(event.target.value)} className="w-full rounded border p-2 bg-surface" /> {error &&

{error}

}
); }