Files
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

199 lines
7.0 KiB
TypeScript

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();
});
});