Files
newz-qwen-27b/frontend/src/api/client.ts
T
Daniel Samson b186d0f797 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.
2026-10-30 17:03:00 +00:00

208 lines
6.5 KiB
TypeScript

/**
* Typed API client for the newzy backend.
*
* - Base URL: `/api/v1` by default (overridable via `VITE_API_BASE_URL`).
* In development the Vite dev server proxies `/api` to
* `http://localhost:8000` (see `vite.config.ts`); in Docker the Nginx
* container proxies `/api/` to the `backend` service (see `nginx.conf`).
* - All non-2xx responses throw `ApiError` carrying the backend's
* standardized error envelope (`{ detail, code, errors? }`).
*/
import type {
ApiErrorPayload,
Article,
Author,
Category,
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;
readonly code?: string;
constructor(status: number, message: string, code?: string) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
}
}
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;
}
/**
* Low-level fetch wrapper: prepends the base URL, sends JSON, parses the
* response and converts failures into `ApiError`.
*/
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
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,
});
} catch {
throw new ApiError(0, 'Network error: unable to reach the newzy API.', 'network_error');
}
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;
} catch {
// Non-JSON error body — fall back to the status line.
}
throw new ApiError(
response.status,
payload?.detail ?? `Request to ${path} failed with status ${response.status}.`,
payload?.code,
);
}
if (response.status === 204) {
return undefined as T;
}
return (await response.json()) as T;
}
/** Type-safe request helpers. */
export const api = {
get: <T>(path: string, init?: RequestOptions) => request<T>(path, init),
post: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'POST', body }),
put: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'PUT', body }),
patch: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'PATCH', body }),
delete: <T>(path: string, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'DELETE' }),
};
/* --- Backend wire formats (snake_case, see backend/schemas) ------------- */
interface BackendCategory {
id: number;
name: string;
slug: string;
}
interface BackendAuthor {
id: number;
name: string;
email: string;
bio: string | null;
}
interface BackendArticle {
id: number;
title: string;
content: string;
author_id: number;
category_id: number;
created_at: string;
published: boolean;
author?: BackendAuthor;
category?: BackendCategory;
}
function toCategory(category: BackendCategory): Category {
return { id: category.id, name: category.name, slug: category.slug };
}
function toAuthor(author: BackendAuthor): Author {
return {
id: author.id,
name: author.name,
email: author.email,
bio: author.bio ?? undefined,
};
}
function toArticle(article: BackendArticle): Article {
return {
id: article.id,
title: article.title,
content: article.content,
authorId: article.author_id,
author: article.author ? toAuthor(article.author) : undefined,
categoryId: article.category_id,
category: article.category ? toCategory(article.category) : undefined,
createdAt: article.created_at,
published: article.published,
};
}
/* --- Typed endpoint helpers --------------------------------------------- */
/** `GET /api/v1/health` — service liveness probe. */
export function getHealth(): Promise<HealthResponse> {
return api.get<HealthResponse>('/health');
}
/** `GET /api/v1/version` — application name and version. */
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.
*
* The endpoint is provided by a later backend milestone; until then the
* UI falls back to sample data (see `src/data/sample.ts`).
*/
export function getArticles(): Promise<Article[]> {
return api.get<BackendArticle[]>('/articles').then((articles) =>
articles.map(toArticle),
);
}