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:
1 parent
ed7b30438e
commit
b186d0f797
35 files changed
+2422
-36
No files matched your search
@@ -0,0 +1,198 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
|
||||
const TOKEN = 'mock-jwt-token';
|
||||
|
||||
const envelope = (detail: string, code: string) => JSON.stringify({ detail, code });
|
||||
|
||||
/**
|
||||
* Mock the auth API so the flows do not depend on a running backend
|
||||
* (same approach as api.spec.ts). The "server" accepts:
|
||||
* - register: any username except `taken`, any password
|
||||
* - login: alice / password123
|
||||
* - me: the mock token -> user `alice`
|
||||
*/
|
||||
function mockAuthApi(page: Page): void {
|
||||
page.route('**/api/v1/auth/register', (route) => {
|
||||
const body = route.request().postDataJSON();
|
||||
if (body.username === 'taken') {
|
||||
return route.fulfill({
|
||||
status: 400,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Username already exists', 'bad_request'),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 201,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ token: TOKEN, username: body.username }),
|
||||
});
|
||||
});
|
||||
|
||||
page.route('**/api/v1/auth/login', (route) => {
|
||||
const body = route.request().postDataJSON();
|
||||
if (body.username !== 'alice' || body.password !== 'password123') {
|
||||
return route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Invalid username or password', 'unauthorized'),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ token: TOKEN, username: body.username }),
|
||||
});
|
||||
});
|
||||
|
||||
page.route('**/api/v1/auth/me', (route) => {
|
||||
const header = route.request().headers()['authorization'];
|
||||
if (header !== `Bearer ${TOKEN}`) {
|
||||
return route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Invalid or expired token', 'unauthorized'),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ username: 'alice' }),
|
||||
});
|
||||
});
|
||||
|
||||
page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 }));
|
||||
}
|
||||
|
||||
/** Store a session token before the app boots (session-restore tests). */
|
||||
async function seedToken(page: Page, token: string): Promise<void> {
|
||||
await page.addInitScript((value) => localStorage.setItem('AUTH_TOKEN', value), token);
|
||||
}
|
||||
|
||||
const readToken = (page: Page) => page.evaluate(() => localStorage.getItem('AUTH_TOKEN'));
|
||||
|
||||
const accountNav = (page: Page) => page.getByRole('navigation', { name: 'Account' });
|
||||
|
||||
test.describe('auth flows', () => {
|
||||
test('register: creates an account, stores the token and signs the user in', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/register');
|
||||
await page.getByLabel('Username').fill('newuser');
|
||||
await page.getByLabel('Password', { exact: true }).fill('password123');
|
||||
await page.getByLabel('Confirm password').fill('password123');
|
||||
await page.getByRole('button', { name: /register/i }).click();
|
||||
|
||||
// Registration auto-signs in and redirects to home.
|
||||
await expect(page).toHaveURL('/');
|
||||
expect(await readToken(page)).toBe(TOKEN);
|
||||
await expect(accountNav(page).getByText('newuser')).toBeVisible();
|
||||
await expect(accountNav(page).getByRole('link', { name: /sign out/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('register: rejects a duplicate username with the backend error', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/register');
|
||||
await page.getByLabel('Username').fill('taken');
|
||||
await page.getByLabel('Password', { exact: true }).fill('password123');
|
||||
await page.getByLabel('Confirm password').fill('password123');
|
||||
await page.getByRole('button', { name: /register/i }).click();
|
||||
|
||||
await expect(page.getByRole('alert')).toContainText('Username already exists');
|
||||
expect(await readToken(page)).toBeNull();
|
||||
await expect(page).toHaveURL('/register');
|
||||
});
|
||||
|
||||
test('register: validates mismatched passwords client-side', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/register');
|
||||
await page.getByLabel('Username').fill('newuser');
|
||||
await page.getByLabel('Password', { exact: true }).fill('password123');
|
||||
await page.getByLabel('Confirm password').fill('different123');
|
||||
await page.getByRole('button', { name: /register/i }).click();
|
||||
|
||||
await expect(page.getByRole('alert')).toContainText('Passwords do not match.');
|
||||
expect(await readToken(page)).toBeNull();
|
||||
});
|
||||
|
||||
test('login: stores the token and signs the user in', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Username').fill('alice');
|
||||
await page.getByLabel('Password').fill('password123');
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
|
||||
await expect(page).toHaveURL('/');
|
||||
expect(await readToken(page)).toBe(TOKEN);
|
||||
await expect(accountNav(page).getByText('alice')).toBeVisible();
|
||||
});
|
||||
|
||||
test('login: shows the backend error for invalid credentials', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Username').fill('alice');
|
||||
await page.getByLabel('Password').fill('wrong-password');
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
|
||||
await expect(page.getByRole('alert')).toContainText('Invalid username or password');
|
||||
expect(await readToken(page)).toBeNull();
|
||||
await expect(page).toHaveURL('/login');
|
||||
});
|
||||
|
||||
test('restores the session from a stored token on page load', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
await seedToken(page, TOKEN);
|
||||
|
||||
await page.goto('/');
|
||||
|
||||
await expect(accountNav(page).getByText('alice')).toBeVisible();
|
||||
expect(await readToken(page)).toBe(TOKEN);
|
||||
});
|
||||
|
||||
test('clears an invalid stored token on page load', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
await seedToken(page, 'expired-or-forged-token');
|
||||
|
||||
await page.goto('/');
|
||||
|
||||
// Restore failed -> signed-out header, token removed.
|
||||
await expect(accountNav(page).getByRole('link', { name: 'Sign in' })).toBeVisible();
|
||||
expect(await readToken(page)).toBeNull();
|
||||
});
|
||||
|
||||
test('redirects unauthenticated users from /account to /login', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/account');
|
||||
|
||||
await expect(page).toHaveURL('/login');
|
||||
});
|
||||
|
||||
test('renders the protected /account page for a signed-in user', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
await seedToken(page, TOKEN);
|
||||
|
||||
await page.goto('/account');
|
||||
|
||||
await expect(page.getByTestId('account-page')).toBeVisible();
|
||||
await expect(page.getByRole('heading', { level: 1, name: 'Account' })).toBeVisible();
|
||||
await expect(page.getByTestId('account-page').getByText('alice')).toBeVisible();
|
||||
});
|
||||
|
||||
test('sign out clears the token and returns to the login page', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
await seedToken(page, TOKEN);
|
||||
|
||||
await page.goto('/');
|
||||
await accountNav(page).getByRole('link', { name: /sign out/i }).click();
|
||||
|
||||
await expect(page).toHaveURL('/login');
|
||||
expect(await readToken(page)).toBeNull();
|
||||
await expect(page.getByRole('status').getByText(/signed out/i)).toBeVisible();
|
||||
});
|
||||
});
|
||||
+33
-13
@@ -1,8 +1,13 @@
|
||||
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
|
||||
import { AuthProvider, RequireAuth } from './auth';
|
||||
import Layout from './components/ui/Layout';
|
||||
import Account from './pages/Account';
|
||||
import ArticlePage from './pages/ArticlePage';
|
||||
import CategoriesPage from './pages/CategoriesPage';
|
||||
import Home from './pages/Home';
|
||||
import Login from './pages/Login';
|
||||
import Register from './pages/Register';
|
||||
import SignOut from './pages/SignOut';
|
||||
|
||||
/** 404 fallback for unknown routes. */
|
||||
function NotFound() {
|
||||
@@ -20,11 +25,13 @@ function NotFound() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Root component: owns the React Router setup.
|
||||
* Root component: owns the React Router + auth setup.
|
||||
*
|
||||
* BrowserRouter wraps the whole app; Layout provides the shared shell
|
||||
* (header/footer); Routes maps URLs to page components in src/pages/.
|
||||
* In-app navigation always uses react-router-dom <Link>/<NavLink>.
|
||||
* BrowserRouter wraps the whole app; AuthProvider restores the JWT
|
||||
* session and exposes login/register/logout (see src/auth.tsx); Layout
|
||||
* provides the shared shell (header/footer); Routes maps URLs to page
|
||||
* components in src/pages/. In-app navigation always uses
|
||||
* react-router-dom <Link>/<NavLink>.
|
||||
*/
|
||||
export default function App() {
|
||||
return (
|
||||
@@ -34,15 +41,28 @@ export default function App() {
|
||||
v7_relativeSplatPath: true,
|
||||
}}
|
||||
>
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/articles" element={<ArticlePage />} />
|
||||
<Route path="/articles/:id" element={<ArticlePage />} />
|
||||
<Route path="/categories" element={<CategoriesPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
<AuthProvider>
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/articles" element={<ArticlePage />} />
|
||||
<Route path="/articles/:id" element={<ArticlePage />} />
|
||||
<Route path="/categories" element={<CategoriesPage />} />
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/sign-out" element={<SignOut />} />
|
||||
<Route
|
||||
path="/account"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<Account />
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
@@ -31,4 +31,49 @@
|
||||
.btn-secondary {
|
||||
@apply inline-flex items-center justify-center gap-2 rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50;
|
||||
}
|
||||
|
||||
/* --- Auth pages (login / register / sign out) ------------------------- */
|
||||
|
||||
/* Centered wrapper so auth cards sit in the middle of the viewport. */
|
||||
.auth-wrap {
|
||||
@apply flex min-h-[60vh] items-center justify-center px-4 py-12;
|
||||
}
|
||||
|
||||
/* Card holding an auth form. */
|
||||
.auth-card {
|
||||
@apply w-full max-w-sm rounded-xl border border-slate-200 bg-white p-6 shadow-sm;
|
||||
}
|
||||
|
||||
/* Auth card heading (icon + label). */
|
||||
.auth-title {
|
||||
@apply mb-4 flex items-center gap-2 text-lg font-semibold text-slate-900;
|
||||
}
|
||||
|
||||
/* Form field: label stacked above its input. */
|
||||
.field {
|
||||
@apply mb-4;
|
||||
}
|
||||
|
||||
.field label {
|
||||
@apply mb-1 block text-sm font-medium text-slate-700;
|
||||
}
|
||||
|
||||
/* Text input used by the auth forms. */
|
||||
.input {
|
||||
@apply w-full rounded-md border border-slate-300 px-3 py-2 text-sm text-slate-900 placeholder:text-slate-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/40;
|
||||
}
|
||||
|
||||
/* Inline error/success notices inside auth cards. */
|
||||
.auth-error {
|
||||
@apply mb-3 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700;
|
||||
}
|
||||
|
||||
.auth-success {
|
||||
@apply mb-3 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700;
|
||||
}
|
||||
|
||||
/* Cross-link line at the bottom of an auth card. */
|
||||
.auth-alt {
|
||||
@apply mt-4 text-center text-sm text-slate-600;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Authentication state for the app.
|
||||
*
|
||||
* - `AuthProvider` restores the session on load (validates the token
|
||||
* stored under `AUTH_TOKEN` against `GET /api/v1/auth/me`, drops it
|
||||
* when invalid/expired) and exposes `login` / `register` / `logout`.
|
||||
* - The JWT is attached to every API request automatically (see
|
||||
* `api/client.ts`); this module only owns the username + ready state.
|
||||
*/
|
||||
import {
|
||||
ReactNode,
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import {
|
||||
TOKEN_KEY,
|
||||
login as apiLogin,
|
||||
logout as apiLogout,
|
||||
me as apiMe,
|
||||
register as apiRegister,
|
||||
} from './api/client';
|
||||
|
||||
export interface AuthState {
|
||||
/** Logged-in username, or `null` when signed out. */
|
||||
username: string | null;
|
||||
/** `false` until the initial session-restore attempt has finished. */
|
||||
ready: boolean;
|
||||
/** Authenticate; stores the returned JWT and signs the user in. */
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
/** Register a new account; stores the returned JWT and signs in. */
|
||||
register: (username: string, password: string) => Promise<void>;
|
||||
/** Clear the stored token (best-effort server call) and sign out. */
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
// Restore the session on first load: validate the stored token and drop
|
||||
// it when the backend rejects it (expired, invalid or unknown user).
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(TOKEN_KEY);
|
||||
if (!stored) {
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
apiMe(stored)
|
||||
.then((user) => setUsername(user.username))
|
||||
.catch(() => localStorage.removeItem(TOKEN_KEY))
|
||||
.finally(() => setReady(true));
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (name: string, password: string) => {
|
||||
const res = await apiLogin(name, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
}, []);
|
||||
|
||||
const register = useCallback(async (name: string, password: string) => {
|
||||
const res = await apiRegister(name, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
// Best effort: the token is discarded client-side regardless of
|
||||
// whether the (stateless) server endpoint is reachable.
|
||||
apiLogout().catch(() => undefined);
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setUsername(null);
|
||||
}, []);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ username, ready, login, register, logout }),
|
||||
[username, ready, login, register, logout],
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth(): AuthState {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within <AuthProvider>');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route guard for authenticated users: shows a brief loading state while
|
||||
* the session is being restored, redirects to `/login` (remembering the
|
||||
* intended path in router state) when signed out, and renders `children`
|
||||
* otherwise.
|
||||
*/
|
||||
export function RequireAuth({ children }: { children: ReactNode }) {
|
||||
const { username, ready } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="container-page flex justify-center py-16" role="status">
|
||||
<span className="animate-pulse text-sm text-slate-500">Checking session…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (username === null) {
|
||||
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
|
||||
}
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { FileText, Home, Menu, Settings, X, type LucideIcon } from 'lucide-react';
|
||||
import { FileText, Home, LogOut, Menu, Settings, User, X, type LucideIcon } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import { Link, NavLink } from 'react-router-dom';
|
||||
import { useAuth } from '../../auth';
|
||||
import logo from '../../assets/logo.svg';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
@@ -31,6 +32,7 @@ const NAV_ITEMS: NavItem[] = [
|
||||
*/
|
||||
export function Header({ className }: HeaderProps) {
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const { username, ready } = useAuth();
|
||||
|
||||
const closeMenu = () => setMenuOpen(false);
|
||||
|
||||
@@ -41,6 +43,35 @@ export function Header({ className }: HeaderProps) {
|
||||
isActive && 'bg-blue-50 text-blue-700 hover:bg-blue-100 hover:text-blue-800',
|
||||
);
|
||||
|
||||
const plainLinkClasses =
|
||||
'inline-flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900';
|
||||
|
||||
// Auth links: sign-in/register when logged out, account/sign-out when
|
||||
// signed in (rendered once the session restore has settled).
|
||||
const renderAuthLinks = (onClick?: () => void) =>
|
||||
ready &&
|
||||
(username ? (
|
||||
<>
|
||||
<NavLink to="/account" className={linkClasses} onClick={onClick}>
|
||||
<User className="h-5 w-5" aria-hidden="true" />
|
||||
<span>{username}</span>
|
||||
</NavLink>
|
||||
<Link to="/sign-out" className={plainLinkClasses} onClick={onClick}>
|
||||
<LogOut className="h-5 w-5" aria-hidden="true" />
|
||||
<span>Sign out</span>
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link to="/login" className={plainLinkClasses} onClick={onClick}>
|
||||
<span>Sign in</span>
|
||||
</Link>
|
||||
<Link to="/register" className="btn !px-3 !py-2" onClick={onClick}>
|
||||
<span>Register</span>
|
||||
</Link>
|
||||
</>
|
||||
));
|
||||
|
||||
const renderNav = (id: string, itemClasses?: string) => (
|
||||
<nav id={id} aria-label={`${id === 'mobile-menu' ? 'Mobile' : 'Main'} navigation`} className={itemClasses}>
|
||||
{NAV_ITEMS.map(({ to, label, icon: Icon, end }) => (
|
||||
@@ -73,6 +104,11 @@ export function Header({ className }: HeaderProps) {
|
||||
{/* Desktop navigation */}
|
||||
{renderNav('main-nav', 'hidden items-center gap-1 md:flex')}
|
||||
|
||||
{/* Account (auth) links */}
|
||||
<nav aria-label="Account" className="hidden items-center gap-1 md:flex">
|
||||
{renderAuthLinks()}
|
||||
</nav>
|
||||
|
||||
{/* Mobile menu toggle */}
|
||||
<button
|
||||
type="button"
|
||||
@@ -91,7 +127,14 @@ export function Header({ className }: HeaderProps) {
|
||||
</div>
|
||||
|
||||
{/* Mobile navigation (rendered only while open) */}
|
||||
{menuOpen && renderNav('mobile-menu', 'flex flex-col gap-1 border-t border-slate-200 px-4 pb-4 pt-2 md:hidden')}
|
||||
{menuOpen && (
|
||||
<div className="flex flex-col border-t border-slate-200 px-4 pb-4 pt-2 md:hidden">
|
||||
{renderNav('mobile-menu', 'flex flex-col gap-1')}
|
||||
<div className="mt-1 flex flex-col gap-1 border-t border-slate-200 pt-2">
|
||||
{renderAuthLinks(closeMenu)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/**
|
||||
* Placeholder account page (protected by `RequireAuth`): proves the
|
||||
* auth-guarded routing works end-to-end. Real profile features arrive
|
||||
* in a later milestone.
|
||||
*/
|
||||
export default function Account() {
|
||||
const { username } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="container-page" data-testid="account-page">
|
||||
<h1 className="mb-2 text-3xl font-bold text-slate-900">Account</h1>
|
||||
<p className="text-sm text-slate-600">
|
||||
You are signed in as{' '}
|
||||
<strong className="font-semibold text-slate-900">{username}</strong>. Profile
|
||||
settings will live here.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { FormEvent, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { Loader2, UserPlus } from 'lucide-react';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/** Must match the backend `RegisterIn.username` pattern. */
|
||||
const USERNAME_PATTERN = /^[a-zA-Z0-9_]{3,20}$/;
|
||||
|
||||
/**
|
||||
* Registration page: validates the inputs client-side, then calls
|
||||
* `POST /api/v1/auth/register` via `useAuth` (which stores the JWT and
|
||||
* signs the user in). Backend rejections (e.g. duplicate username) are
|
||||
* shown verbatim.
|
||||
*/
|
||||
export default function Register() {
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const name = username.trim();
|
||||
if (!USERNAME_PATTERN.test(name)) {
|
||||
setError('Username must be 3–20 characters: letters, numbers or underscores.');
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters.');
|
||||
return;
|
||||
}
|
||||
if (password !== confirm) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await register(name, password);
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Registration failed');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<div className="auth-card" data-testid="register-card">
|
||||
<h1 className="auth-title">
|
||||
<UserPlus size={18} aria-hidden="true" />
|
||||
Create an account
|
||||
</h1>
|
||||
|
||||
{error && (
|
||||
<p className="auth-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={submit}>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-username">Username</label>
|
||||
<input
|
||||
id="reg-username"
|
||||
className="input"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
placeholder="3–20 letters, numbers or underscores"
|
||||
maxLength={20}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-password">Password</label>
|
||||
<input
|
||||
id="reg-password"
|
||||
type="password"
|
||||
className="input"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
placeholder="at least 8 characters"
|
||||
maxLength={200}
|
||||
minLength={8}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-confirm">Confirm password</label>
|
||||
<input
|
||||
id="reg-confirm"
|
||||
type="password"
|
||||
className="input"
|
||||
value={confirm}
|
||||
onChange={(event) => setConfirm(event.target.value)}
|
||||
placeholder="repeat the password"
|
||||
maxLength={200}
|
||||
minLength={8}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button className="btn" type="submit" disabled={busy}>
|
||||
{busy ? (
|
||||
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<UserPlus size={15} aria-hidden="true" />
|
||||
)}
|
||||
{busy ? 'Creating account…' : 'Register'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="auth-alt">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="font-medium text-blue-700 hover:underline">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { LogOut } from 'lucide-react';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/**
|
||||
* Sign-out page: clears the stored JWT (best-effort call to the
|
||||
* stateless `POST /api/v1/auth/logout`) and redirects to the login page
|
||||
* with a "signed out" notice.
|
||||
*/
|
||||
export default function SignOut() {
|
||||
const { logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
logout();
|
||||
navigate('/login', { replace: true, state: { signedOut: true } });
|
||||
}, [logout, navigate]);
|
||||
|
||||
return (
|
||||
<div className="auth-wrap" role="status">
|
||||
<div className="flex items-center gap-2 text-slate-600">
|
||||
<LogOut size={20} aria-hidden="true" />
|
||||
<span className="text-sm">Signing out…</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,33 @@
|
||||
import { fireEvent, screen, within } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { me } from '../api/client';
|
||||
import Header from '../components/ui/Header';
|
||||
import { renderWithRouter } from './utils';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Header', () => {
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the brand with the logo', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
const brand = screen.getByRole('link', { name: 'newzy' });
|
||||
expect(brand).toHaveAttribute('href', '/');
|
||||
expect(brand.querySelector('img')).toHaveAttribute('src', expect.stringContaining('logo'));
|
||||
});
|
||||
|
||||
it('renders the primary navigation with router links and lucide icons', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||
expect(within(nav).getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
|
||||
@@ -24,7 +39,7 @@ describe('Header', () => {
|
||||
});
|
||||
|
||||
it('marks the active route in the navigation', () => {
|
||||
renderWithRouter(<Header />, { route: '/categories' });
|
||||
renderWithAuth(<Header />, { route: '/categories' });
|
||||
|
||||
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveClass('bg-blue-50');
|
||||
@@ -32,7 +47,7 @@ describe('Header', () => {
|
||||
});
|
||||
|
||||
it('toggles the mobile menu', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
// Mobile menu is closed by default.
|
||||
expect(screen.queryByRole('navigation', { name: 'Mobile navigation' })).not.toBeInTheDocument();
|
||||
@@ -50,6 +65,35 @@ describe('Header', () => {
|
||||
screen.queryByRole('navigation', { name: 'Mobile navigation' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows sign-in and register links when signed out', async () => {
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const accountNav = screen.getByRole('navigation', { name: 'Account' });
|
||||
expect(await within(accountNav).findByRole('link', { name: 'Sign in' })).toHaveAttribute(
|
||||
'href',
|
||||
'/login',
|
||||
);
|
||||
expect(within(accountNav).getByRole('link', { name: /register/i })).toHaveAttribute(
|
||||
'href',
|
||||
'/register',
|
||||
);
|
||||
expect(within(accountNav).queryByRole('link', { name: /sign out/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the username and sign-out link when signed in', async () => {
|
||||
(me as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem('AUTH_TOKEN', 'stored-token');
|
||||
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const accountNav = screen.getByRole('navigation', { name: 'Account' });
|
||||
expect(await within(accountNav).findByText('alice')).toBeInTheDocument();
|
||||
expect(within(accountNav).getByRole('link', { name: 'Sign out' })).toHaveAttribute(
|
||||
'href',
|
||||
'/sign-out',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const NAV_ITEM_COUNT = 3;
|
||||
@@ -3,10 +3,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { getHealth } from '../api/client';
|
||||
import Layout from '../components/ui/Layout';
|
||||
import { renderWithRouter } from './utils';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
getHealth: vi.fn(),
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Layout', () => {
|
||||
@@ -17,7 +22,7 @@ describe('Layout', () => {
|
||||
it('renders the header, main content area and footer', () => {
|
||||
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>Page content</p>
|
||||
</Layout>,
|
||||
@@ -33,7 +38,7 @@ describe('Layout', () => {
|
||||
it('shows the API as online when the health check succeeds', async () => {
|
||||
(getHealth as Mock).mockResolvedValue({ status: 'ok', version: '0.1.0' });
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>content</p>
|
||||
</Layout>,
|
||||
@@ -46,7 +51,7 @@ describe('Layout', () => {
|
||||
it('shows the API as offline when the health check fails', async () => {
|
||||
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>content</p>
|
||||
</Layout>,
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import {
|
||||
TOKEN_KEY,
|
||||
login as clientLogin,
|
||||
logout as clientLogout,
|
||||
me as clientMe,
|
||||
register as clientRegister,
|
||||
} from '../api/client';
|
||||
import { AuthProvider, RequireAuth, useAuth } from '../auth';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
/** Renders the current auth state plus one trigger button per action. */
|
||||
function StateProbe() {
|
||||
const { username, ready, login, register, logout } = useAuth();
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="ready">{String(ready)}</span>
|
||||
<span data-testid="username">{username ?? 'null'}</span>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="do-login"
|
||||
onClick={() => {
|
||||
void login('login-user', 'password123');
|
||||
}}
|
||||
>
|
||||
login
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="do-register"
|
||||
onClick={() => {
|
||||
void register('register-user', 'password123');
|
||||
}}
|
||||
>
|
||||
register
|
||||
</button>
|
||||
<button type="button" data-testid="do-logout" onClick={logout}>
|
||||
logout
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe('AuthProvider', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('starts signed out without a stored token (no me() call)', async () => {
|
||||
renderWithAuth(<StateProbe />);
|
||||
expect(await screen.findByTestId('ready')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('null');
|
||||
expect(clientMe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restores the session from a valid stored token', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
|
||||
expect(await screen.findByTestId('username')).toHaveTextContent('alice');
|
||||
expect(clientMe).toHaveBeenCalledWith('valid-token');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('valid-token');
|
||||
});
|
||||
|
||||
it('clears an invalid stored token on restore failure', async () => {
|
||||
(clientMe as Mock).mockRejectedValue(new Error('401'));
|
||||
localStorage.setItem(TOKEN_KEY, 'expired-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
|
||||
expect(await screen.findByTestId('ready')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('null');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('login stores the returned token and sets the username', async () => {
|
||||
(clientLogin as Mock).mockResolvedValue({ token: 'new-token', username: 'login-user' });
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await screen.findByTestId('ready');
|
||||
screen.getByTestId('do-login').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('login-user'));
|
||||
expect(clientLogin).toHaveBeenCalledWith('login-user', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('new-token');
|
||||
});
|
||||
|
||||
it('register stores the returned token and sets the username', async () => {
|
||||
(clientRegister as Mock).mockResolvedValue({
|
||||
token: 'new-token',
|
||||
username: 'register-user',
|
||||
});
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await screen.findByTestId('ready');
|
||||
screen.getByTestId('do-register').click();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('register-user'),
|
||||
);
|
||||
expect(clientRegister).toHaveBeenCalledWith('register-user', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('new-token');
|
||||
});
|
||||
|
||||
it('logout calls the API best-effort and clears the session', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
(clientLogout as Mock).mockResolvedValue(undefined);
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('alice'));
|
||||
screen.getByTestId('do-logout').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('null'));
|
||||
expect(clientLogout).toHaveBeenCalledTimes(1);
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('logout still clears the session when the API call fails', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
(clientLogout as Mock).mockRejectedValue(new Error('network down'));
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('alice'));
|
||||
screen.getByTestId('do-logout').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('null'));
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RequireAuth', () => {
|
||||
const routes = (
|
||||
<Routes>
|
||||
<Route path="/login" element={<div>Login page</div>} />
|
||||
<Route
|
||||
path="/account"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<div>Account page</div>
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
const renderProtected = (initialPath: string) =>
|
||||
render(
|
||||
<MemoryRouter
|
||||
initialEntries={[initialPath]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>{routes}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users to /login', async () => {
|
||||
renderProtected('/account');
|
||||
expect(await screen.findByText('Login page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders protected content for a signed-in user', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderProtected('/account');
|
||||
expect(await screen.findByText('Account page')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Unit tests for the auth methods of the API client (token attachment,
|
||||
* 401 handling, request/response shapes).
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ApiError, login, logout, me, register, TOKEN_KEY } from '../api/client';
|
||||
|
||||
/** Minimal fetch Response look-alike for the client. */
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
statusText: 'OK',
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body),
|
||||
} as Response;
|
||||
}
|
||||
|
||||
describe('auth API client', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
});
|
||||
|
||||
it('login posts credentials to /auth/login and returns the token payload', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { token: 'tok', username: 'alice' }));
|
||||
|
||||
const res = await login('alice', 'password123');
|
||||
|
||||
expect(res).toEqual({ token: 'tok', username: 'alice' });
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/login');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
username: 'alice',
|
||||
password: 'password123',
|
||||
});
|
||||
});
|
||||
|
||||
it('register posts to /auth/register', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(201, { token: 'tok', username: 'bob' }));
|
||||
|
||||
await register('bob', 'password123');
|
||||
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/register');
|
||||
});
|
||||
|
||||
it('attaches the stored token as a Bearer Authorization header', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'stored-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me();
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer stored-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('sends no Authorization header without a stored token', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me();
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBeUndefined();
|
||||
});
|
||||
|
||||
it('me() prefers an explicit token over the stored one', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'stored-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me('explicit-token');
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer explicit-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the stored token on a 401 response', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'dead-token');
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(401, { detail: 'Invalid or expired token', code: 'unauthorized' }),
|
||||
);
|
||||
|
||||
await expect(me('dead-token')).rejects.toBeInstanceOf(ApiError);
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces the backend error detail for failed registrations', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(400, { detail: 'Username already exists', code: 'bad_request' }),
|
||||
);
|
||||
|
||||
const err = await register('alice', 'password123').catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(ApiError);
|
||||
expect((err as ApiError).status).toBe(400);
|
||||
expect((err as ApiError).code).toBe('bad_request');
|
||||
expect((err as ApiError).message).toBe('Username already exists');
|
||||
});
|
||||
|
||||
it('logout posts to /auth/logout and resolves to undefined', async () => {
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 204,
|
||||
statusText: 'No Content',
|
||||
} as Response);
|
||||
|
||||
await expect(logout()).resolves.toBeUndefined();
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/logout');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(init.body).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, login as clientLogin } from '../../api/client';
|
||||
import { AuthProvider } from '../../auth';
|
||||
import Login from '../../pages/Login';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderLogin() {
|
||||
return (
|
||||
<MemoryRouter
|
||||
initialEntries={['/login']}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={<div>Home page</div>} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
async function fillLoginForm(username: string, password: string) {
|
||||
fireEvent.change(screen.getByLabelText('Username'), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
|
||||
const form = screen.getByRole('button', { name: /sign in/i }).closest('form');
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
}
|
||||
|
||||
describe('Login page', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the form fields and a link to registration', () => {
|
||||
render(renderLogin());
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();
|
||||
expect(screen.getByRole('link', { name: /register/i })).toHaveAttribute('href', '/register');
|
||||
});
|
||||
|
||||
it('blocks submission with empty fields', async () => {
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
const form = screen.getByRole('button', { name: /sign in/i }).closest('form');
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'Please enter both username and password.',
|
||||
);
|
||||
expect(clientLogin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('signs in, stores the token and navigates to home', async () => {
|
||||
(clientLogin as Mock).mockResolvedValue({ token: 'tok-123', username: 'alice' });
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'password123');
|
||||
|
||||
expect(await screen.findByText('Home page')).toBeInTheDocument();
|
||||
expect(clientLogin).toHaveBeenCalledWith('alice', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('tok-123');
|
||||
});
|
||||
|
||||
it('shows the backend error on failed login and stores no token', async () => {
|
||||
(clientLogin as Mock).mockRejectedValue(
|
||||
new Error('Invalid username or password'),
|
||||
);
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'wrong-password');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Invalid username or password');
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a loading state while the login request is pending', async () => {
|
||||
(clientLogin as Mock).mockReturnValue(new Promise(() => undefined));
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'password123');
|
||||
|
||||
expect(await screen.findByText('Signing in…')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /signing in/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, register as clientRegister } from '../../api/client';
|
||||
import { AuthProvider } from '../../auth';
|
||||
import Register from '../../pages/Register';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderRegister() {
|
||||
return (
|
||||
<MemoryRouter
|
||||
initialEntries={['/register']}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<div>Home page</div>} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
async function fillRegisterForm(
|
||||
username: string,
|
||||
password: string,
|
||||
confirm: string,
|
||||
): Promise<void> {
|
||||
fireEvent.change(screen.getByLabelText('Username'), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
|
||||
fireEvent.change(screen.getByLabelText('Confirm password'), {
|
||||
target: { value: confirm },
|
||||
});
|
||||
const form = screen.getByRole('button', { name: /register/i }).closest('form');
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
}
|
||||
|
||||
describe('Register page', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the form fields and a link to login', () => {
|
||||
render(renderRegister());
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Confirm password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /sign in/i })).toHaveAttribute('href', '/login');
|
||||
});
|
||||
|
||||
it('rejects mismatched passwords without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'different123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Passwords do not match.');
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects invalid usernames without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('ab', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/3–20 characters/);
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects short passwords without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'short', 'short');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/at least 8 characters/);
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('registers, stores the token and navigates to home', async () => {
|
||||
(clientRegister as Mock).mockResolvedValue({ token: 'tok-456', username: 'newuser' });
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByText('Home page')).toBeInTheDocument();
|
||||
expect(clientRegister).toHaveBeenCalledWith('newuser', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('tok-456');
|
||||
});
|
||||
|
||||
it('shows the backend error for an existing username', async () => {
|
||||
(clientRegister as Mock).mockRejectedValue(
|
||||
new Error('Username already exists'),
|
||||
);
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Username already exists');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,52 @@
|
||||
/**
|
||||
* Vitest setup: registers jest-dom matchers and cleans up the DOM after
|
||||
* every test (React Testing Library auto-cleanup needs this when globals
|
||||
* are disabled).
|
||||
* Vitest setup: registers jest-dom matchers, provides a working
|
||||
* `localStorage` and cleans up the DOM after every test (React Testing
|
||||
* Library auto-cleanup needs this when globals are disabled).
|
||||
*/
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
import { afterEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* In-memory Storage. Node >= 22 exposes an experimental `localStorage`
|
||||
* global that is `undefined` without `--localstorage-file`, and the jsdom
|
||||
* environment does not override it — so the auth tests (which persist the
|
||||
* JWT under AUTH_TOKEN) get a real storage implementation here.
|
||||
*/
|
||||
class MemoryStorage implements Storage {
|
||||
private store = new Map<string, string>();
|
||||
|
||||
get length(): number {
|
||||
return this.store.size;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
getItem(key: string): string | null {
|
||||
return this.store.has(key) ? this.store.get(key)! : null;
|
||||
}
|
||||
|
||||
key(index: number): string | null {
|
||||
return Array.from(this.store.keys())[index] ?? null;
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
setItem(key: string, value: string): void {
|
||||
this.store.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: new MemoryStorage(),
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
@@ -1,12 +1,23 @@
|
||||
import { render, type RenderOptions } from '@testing-library/react';
|
||||
import type { ReactElement } from 'react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
export interface RenderWithRouterOptions extends Omit<RenderOptions, 'wrapper'> {
|
||||
/** Initial route (path only, e.g. "/articles/1"). */
|
||||
route?: string;
|
||||
}
|
||||
|
||||
interface RouterFutureFlags {
|
||||
v7_startTransition: boolean;
|
||||
v7_relativeSplatPath: boolean;
|
||||
}
|
||||
|
||||
const ROUTER_FUTURE: RouterFutureFlags = {
|
||||
v7_startTransition: true,
|
||||
v7_relativeSplatPath: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Render helper that wraps the UI in a MemoryRouter so components using
|
||||
* react-router-dom (Link, NavLink, useParams) can be tested in isolation.
|
||||
@@ -15,12 +26,26 @@ export function renderWithRouter(ui: ReactElement, options: RenderWithRouterOpti
|
||||
const { route = '/', ...renderOptions } = options;
|
||||
|
||||
return render(
|
||||
<MemoryRouter
|
||||
initialEntries={[route]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<MemoryRouter initialEntries={[route]} future={ROUTER_FUTURE}>
|
||||
{ui}
|
||||
</MemoryRouter>,
|
||||
renderOptions,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render helper for auth-aware components: additionally wraps the UI in
|
||||
* the app's `AuthProvider`. Tests that care about the auth API should
|
||||
* mock `../api/client`; with an empty localStorage no network calls are
|
||||
* made during session restore.
|
||||
*/
|
||||
export function renderWithAuth(ui: ReactElement, options: RenderWithRouterOptions = {}) {
|
||||
const { route = '/', ...renderOptions } = options;
|
||||
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[route]} future={ROUTER_FUTURE}>
|
||||
<AuthProvider>{ui}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
renderOptions,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Auth API types (mirror the backend `schemas.auth` payloads).
|
||||
*/
|
||||
|
||||
/** Payload of `POST /api/v1/auth/register` and `POST /api/v1/auth/login`. */
|
||||
export interface TokenResponse {
|
||||
/** Signed JWT (7-day expiry) — store and send back as `Bearer` token. */
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
/** Payload of `GET /api/v1/auth/me`. */
|
||||
export interface MeResponse {
|
||||
username: string;
|
||||
}
|
||||
Reference in new issue
Block a user