feat: add JWT authentication with auth pages and tests (M5)

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.
This commit is contained in:
Daniel Samson committed 2026-10-30 17:03:00 +00:00
1 parent ed7b30438e
commit b186d0f797
35 files changed
+2422 -36

No files matched your search

+36 -1
View File
@@ -16,10 +16,14 @@ import type {
HealthResponse,
VersionResponse,
} from '../types';
import type { MeResponse, TokenResponse } from '../types/auth';
export const API_BASE_URL: string =
(import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '/api/v1';
/** localStorage key under which the JWT session token is persisted. */
export const TOKEN_KEY = 'AUTH_TOKEN';
/** Error thrown for failed API requests (network or non-2xx responses). */
export class ApiError extends Error {
readonly status: number;
@@ -36,6 +40,8 @@ export class ApiError extends Error {
interface RequestOptions extends Omit<RequestInit, 'body'> {
/** JSON-serializable request body (stringified automatically). */
body?: unknown;
/** Use this Bearer token instead of the one stored under TOKEN_KEY. */
token?: string;
}
/**
@@ -43,15 +49,19 @@ interface RequestOptions extends Omit<RequestInit, 'body'> {
* response and converts failures into `ApiError`.
*/
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const { body, headers, ...rest } = options;
const { body, headers, token, ...rest } = options;
let response: Response;
try {
// Attach the JWT (explicit override or the stored session) so the
// backend can identify the caller on protected endpoints.
const bearer = token ?? localStorage.getItem(TOKEN_KEY);
response = await fetch(`${API_BASE_URL}${path}`, {
...rest,
headers: {
Accept: 'application/json',
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),
...headers,
},
body: body !== undefined ? JSON.stringify(body) : undefined,
@@ -61,6 +71,9 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T
}
if (!response.ok) {
// 401: the stored session is invalid/expired — drop it so the UI can
// redirect to login instead of retrying with a dead token.
if (response.status === 401) localStorage.removeItem(TOKEN_KEY);
let payload: ApiErrorPayload | null = null;
try {
payload = (await response.json()) as ApiErrorPayload;
@@ -159,6 +172,28 @@ export function getVersion(): Promise<VersionResponse> {
return api.get<VersionResponse>('/version');
}
/* --- Auth endpoints (JWT sessions, see `src/auth.tsx`) ------------------- */
/** `POST /api/v1/auth/register` — create an account; returns the JWT. */
export function register(username: string, password: string): Promise<TokenResponse> {
return api.post<TokenResponse>('/auth/register', { username, password });
}
/** `POST /api/v1/auth/login` — authenticate; returns the JWT. */
export function login(username: string, password: string): Promise<TokenResponse> {
return api.post<TokenResponse>('/auth/login', { username, password });
}
/** `GET /api/v1/auth/me` — current user for the explicit (or stored) token. */
export function me(token?: string): Promise<MeResponse> {
return api.get<MeResponse>('/auth/me', token !== undefined ? { token } : undefined);
}
/** `POST /api/v1/auth/logout` — stateless; the client discards the token. */
export function logout(): Promise<void> {
return api.post<void>('/auth/logout', undefined);
}
/**
* `GET /api/v1/articles` — list of published articles.
*