Files
NetMapper2026-OLD/frontend/src/pages/LoginPage.tsx
T

65 lines
2.2 KiB
TypeScript

import { useState } from 'react';
import { setToken, setSessionUser } from '../lib/session';
type Props = { onLogin: () => void };
export function LoginPage({ onLogin }: Props) {
const [username, setUsername] = useState('admin');
const [password, setPassword] = useState('admin');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
const body = new URLSearchParams();
body.set('username', username);
body.set('password', password);
const res = await fetch('/backend/auth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: body.toString(),
});
if (!res.ok) {
const data = await res.json().catch(() => null);
throw new Error(data?.detail ?? 'Login fallito');
}
const { access_token } = await res.json();
setToken(access_token);
const meRes = await fetch('/backend/auth/me', {
headers: { Authorization: `Bearer ${access_token}` },
});
if (meRes.ok) setSessionUser(await meRes.json());
onLogin();
} catch (err) {
setError(err instanceof Error ? err.message : 'Login fallito');
} finally {
setLoading(false);
}
};
return (
<main className="login-page">
<section className="login-card">
<p className="login-eyebrow">NetMapper auth</p>
<h1>Accedi al book of truth</h1>
<p className="login-copy">L'accesso è protetto per impedire lettura e modifica dei dati da terzi.</p>
<form onSubmit={submit} className="login-form">
<label>
Username
<input value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="username" />
</label>
<label>
Password
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
</label>
{error && <p className="login-error">{error}</p>}
<button type="submit" disabled={loading}>{loading ? 'Accesso...' : 'Entra'}</button>
</form>
</section>
</main>
);
}