feat: add admin area with item CRUD, Lexical editor and access control (M6)

Backend:
- Item model (title, url, points, username, content, created_at)
- is_admin flag on User + startup migration for pre-existing DBs
- get_current_admin dependency (401 without/invalid token, 403 for
  non-admins); server-side check on every admin endpoint
- /api/v1/admin/items CRUD: pagination, case-insensitive title/url
  search, sort by title/created_at/points, in-memory rate limiting
  (1000 req/60s per admin -> 429)
- seed_admin.py (ADMIN_USERNAME/ADMIN_PASSWORD), documented in
  backend/.env.example

Frontend:
- Auth context exposes is_admin; RequireAdmin route guard (redirects
  signed-out users, renders 403 page for non-admins)
- AdminLayout with responsive dark sidebar; Admin link in header for
  admins only
- AdminDashboard: paginated table (page size 10/20/50), 300ms
  debounced search, sortable title/points/created_at columns,
  edit/delete row actions
- EditItemPage: create + edit with client-side validation and a
  Lexical (0.25) WYSIWYG editor (bold/italic/underline, H1-H6,
  lists, code blocks, links, undo/redo), optional debounced auto-save
- DeleteConfirmation modal with warning icon and explicit
  "Yes, delete" confirmation
- Unit tests (34) and mocked E2E workflow tests (10)

All acceptance criteria for milestones/m6-setup-admin-area-prompt.md
verified: 108 backend, 87 frontend unit and 29 E2E tests pass.
This commit is contained in:
Daniel Samson committed 2026-10-30 21:36:15 +00:00
1 parent b186d0f797
commit b440809548
38 files changed
+5415 -50

No files matched your search

+176
View File
@@ -0,0 +1,176 @@
/**
* Unit tests for the admin API client (URL/parameter building, methods,
* response parsing, error propagation).
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
adminCreateItem,
adminDeleteItem,
adminGetItem,
adminListItems,
adminUpdateItem,
} from '../../api/admin';
import { ApiError, TOKEN_KEY } from '../../api/client';
import type { AdminItemsPage } from '../../types/admin';
const SAMPLE_PAGE: AdminItemsPage = {
items: [
{
id: 1,
title: 'First story',
url: 'https://example.com/first',
points: 3,
username: 'alice',
content: '<p>Hello</p>',
created_at: '2024-05-01T12:00:00Z',
},
],
total: 1,
page: 1,
page_size: 20,
total_pages: 1,
};
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('admin API client', () => {
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
localStorage.clear();
fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
});
it('listItems builds the query string from all parameters', async () => {
localStorage.setItem(TOKEN_KEY, 'admin-token');
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
const res = await adminListItems({
page: 2,
pageSize: 50,
search: ' breaking news ',
sortBy: 'title',
sortOrder: 'asc',
});
expect(res).toEqual(SAMPLE_PAGE);
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
// URLSearchParams encodes spaces as `+`.
expect(url).toBe(
'/api/v1/admin/items?page=2&page_size=50&search=breaking+news&sort_by=title&sort_order=asc',
);
expect(init.method).toBeUndefined();
// The JWT is attached as a Bearer token.
expect((init.headers as Record<string, string>).Authorization).toBe(
'Bearer admin-token',
);
});
it('listItems omits the search parameter when empty', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
await adminListItems({
page: 1,
pageSize: 20,
search: ' ',
sortBy: 'created_at',
sortOrder: 'desc',
});
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe(
'/api/v1/admin/items?page=1&page_size=20&sort_by=created_at&sort_order=desc',
);
});
it('getItem requests the item by id', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
await adminGetItem(7);
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
});
it('createItem POSTs the payload', async () => {
fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.items[0]));
await adminCreateItem({
title: 'New story',
url: '',
points: 0,
username: 'root',
content: '<p>Body</p>',
});
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body as string)).toEqual({
title: 'New story',
url: '',
points: 0,
username: 'root',
content: '<p>Body</p>',
});
});
it('updateItem PUTs the payload to the item route', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
await adminUpdateItem(7, {
title: 'Updated',
url: 'https://example.com/new',
points: 9,
username: 'root',
content: '',
});
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
expect(init.method).toBe('PUT');
});
it('deleteItem sends DELETE and resolves to undefined on 204', async () => {
fetchMock.mockResolvedValue({
ok: true,
status: 204,
statusText: 'No Content',
} as Response);
await expect(adminDeleteItem(7)).resolves.toBeUndefined();
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
expect(init.method).toBe('DELETE');
});
it('surfaces the backend error for non-admin access (403)', async () => {
localStorage.setItem(TOKEN_KEY, 'non-admin-token');
fetchMock.mockResolvedValue(
jsonResponse(403, { detail: 'Admin access required', code: 'forbidden' }),
);
const err = await adminListItems({
page: 1,
pageSize: 20,
search: '',
sortBy: 'created_at',
sortOrder: 'desc',
}).catch((e: unknown) => e);
expect(err).toBeInstanceOf(ApiError);
expect((err as ApiError).status).toBe(403);
expect((err as ApiError).code).toBe('forbidden');
expect((err as ApiError).message).toBe('Admin access required');
});
});