Backend (FastAPI): - core/auth.py: PBKDF2-HMAC-SHA256 password hashing (120k iterations, random salt), HS256 JWT creation/verification (7-day expiry, HN_SECRET_KEY via config) and get_current_user Bearer dependency - models/user.py: User model (username unique/indexed, password_hash, created_at); schemas/auth.py: register/login/token/user schemas - api/v1/auth.py: POST /api/v1/auth/register (201), /login, /logout (204), GET /me; 400 on duplicate username, 401 on bad credentials, invalid/expired/unknown tokens - requirements: PyJWT; env templates + docker-compose expose HN_SECRET_KEY (dev default, override in production) - tests: 24 new backend tests (hashing, tokens, all endpoints) Frontend (React + TypeScript): - api/client.ts: AUTH_TOKEN localStorage persistence, automatic Bearer token attachment, 401 clears the stored token, typed login/register/logout/me helpers - auth.tsx: AuthProvider (session restore + login/register/logout) and RequireAuth route guard - pages: Login, Register, SignOut and a protected /account placeholder; header shows sign-in/register or user/sign-out - styles: auth component classes in globals.css - tests: unit tests for the client, provider and pages; Playwright E2E spec covering register/login/logout, session restore, invalid token cleanup and protected-route redirects (API mocked) Note: the milestone's /api/auth/* paths map to the project's established /api/v1/* prefix (see M2); the HN_SECRET_KEY default is newzy-dev-secret-change-me.
115 lines
3.4 KiB
TypeScript
115 lines
3.4 KiB
TypeScript
import { FormEvent, useState } from 'react';
|
|
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
|
import { Loader2, LogIn } from 'lucide-react';
|
|
import { useAuth } from '../auth';
|
|
|
|
interface LoginLocationState {
|
|
/** Route the user was trying to reach (set by `RequireAuth`). */
|
|
from?: string;
|
|
/** `true` when arriving here right after a sign-out. */
|
|
signedOut?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Login page: authenticates against `POST /api/v1/auth/login` via
|
|
* `useAuth` (which stores the JWT) and redirects back to the intended
|
|
* page, or to home.
|
|
*/
|
|
export default function Login() {
|
|
const { login } = useAuth();
|
|
const navigate = useNavigate();
|
|
const location = useLocation();
|
|
const state = (location.state ?? null) as LoginLocationState | null;
|
|
|
|
const [username, setUsername] = useState('');
|
|
const [password, setPassword] = useState('');
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
|
|
const submit = async (event: FormEvent) => {
|
|
event.preventDefault();
|
|
if (!username.trim() || !password) {
|
|
setError('Please enter both username and password.');
|
|
return;
|
|
}
|
|
setBusy(true);
|
|
setError(null);
|
|
try {
|
|
await login(username.trim(), password);
|
|
const from = state?.from;
|
|
navigate(from && from !== '/login' ? from : '/', { replace: true });
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : 'Sign in failed');
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="auth-wrap">
|
|
<div className="auth-card" data-testid="login-card">
|
|
<h1 className="auth-title">
|
|
<LogIn size={18} aria-hidden="true" />
|
|
Sign in
|
|
</h1>
|
|
|
|
{state?.signedOut && (
|
|
<p className="auth-success" role="status">
|
|
You have been signed out.
|
|
</p>
|
|
)}
|
|
{error && (
|
|
<p className="auth-error" role="alert">
|
|
{error}
|
|
</p>
|
|
)}
|
|
|
|
<form onSubmit={submit}>
|
|
<div className="field">
|
|
<label htmlFor="login-username">Username</label>
|
|
<input
|
|
id="login-username"
|
|
className="input"
|
|
value={username}
|
|
onChange={(event) => setUsername(event.target.value)}
|
|
placeholder="your username"
|
|
maxLength={60}
|
|
autoComplete="username"
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="field">
|
|
<label htmlFor="login-password">Password</label>
|
|
<input
|
|
id="login-password"
|
|
type="password"
|
|
className="input"
|
|
value={password}
|
|
onChange={(event) => setPassword(event.target.value)}
|
|
placeholder="your password"
|
|
maxLength={200}
|
|
autoComplete="current-password"
|
|
required
|
|
/>
|
|
</div>
|
|
<button className="btn" type="submit" disabled={busy}>
|
|
{busy ? (
|
|
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
|
) : (
|
|
<LogIn size={15} aria-hidden="true" />
|
|
)}
|
|
{busy ? 'Signing in…' : 'Sign in'}
|
|
</button>
|
|
</form>
|
|
|
|
<p className="auth-alt">
|
|
No account yet?{' '}
|
|
<Link to="/register" className="font-medium text-blue-700 hover:underline">
|
|
Register
|
|
</Link>
|
|
</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|