Files
newz-qwen-27b/frontend/src/tests/client.auth.test.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

123 lines
4.1 KiB
TypeScript

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