stock-bot/apps/stock/web-app/src/app/AuthGate.tsx
2026-10-20 18:36:19 -04:00

118 lines
3.8 KiB
TypeScript

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<string | null>(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 (
<p className="p-8" role="status">
Checking access…
</p>
);
}
if (role) {
return (
<>
{children}
<div className="fixed bottom-3 right-3 z-50 rounded bg-surface p-2 text-xs border border-border">
{role === 'read' ? 'Read-only access' : 'Administrator access'}
<button className="ml-3 underline" onClick={() => void signOut()}>
Sign out
</button>
{error && (
<span role="alert" className="ml-3">
{error}
</span>
)}
</div>
</>
);
}
return (
<main className="min-h-screen flex items-center justify-center p-6">
<form onSubmit={event => void signIn(event)} className="w-full max-w-sm space-y-4">
<h1 className="text-xl">Stock Bot access</h1>
<p>Enter your administrator or read-only access token. It is not stored in your browser.</p>
<label className="block" htmlFor="access-token">
Access token
</label>
<input
id="access-token"
type="password"
autoComplete="off"
required
value={token}
onChange={event => setToken(event.target.value)}
className="w-full rounded border p-2 bg-surface"
/>
{error && <p role="alert">{error}</p>}
<button type="submit" disabled={busy} className="rounded border px-4 py-2">
{busy ? 'Signing in…' : 'Sign in'}
</button>
</form>
</main>
);
}