Files
newz-qwen-27b/frontend/playwright/e2e/admin.spec.ts
T
Daniel Samson b440809548 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.
2026-10-30 21:36:15 +00:00

409 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { expect, test, type Page } from '@playwright/test';
/**
* E2E tests for the admin area (M6) with a fully mocked backend
* (in-memory item store + token-based auth), following the approach of
* the other specs in this directory.
*/
const ADMIN_TOKEN = 'mock-admin-token';
const USER_TOKEN = 'mock-user-token';
const TOKEN_KEY = 'AUTH_TOKEN';
interface Item {
id: number;
title: string;
url: string;
points: number;
username: string;
content: string;
created_at: string;
}
const envelope = (detail: string, code: string) => JSON.stringify({ detail, code });
/** Build the auth + admin API mock with a per-test item store. */
function mockAdminApi(page: Page): { store: Item[]; nextId: () => number } {
let idCounter = 100;
const store: Item[] = [
{
id: 1,
title: 'Breaking: local cat discovers keyboard',
url: 'https://example.com/cat-keyboard',
points: 42,
username: 'alice',
content: '<p>Amazing news.</p>',
created_at: '2024-05-01T10:00:00Z',
},
{
id: 2,
title: 'Study: coffee improves code reviews',
url: 'https://example.com/coffee-reviews',
points: 17,
username: 'bob',
content: '<p>Peer-reviewed.</p>',
created_at: '2024-05-02T11:30:00Z',
},
{
id: 3,
title: 'Show HN: I built a tiny news app',
url: 'https://example.com/show-hn-newz',
points: 5,
username: 'alice',
content: '<p>Feedback welcome.</p>',
created_at: '2024-05-03T09:15:00Z',
},
];
const requireAdmin = (route: Parameters<Parameters<Page['route']>[1]>[0]): boolean => {
const header = route.request().headers()['authorization'];
if (header !== `Bearer ${ADMIN_TOKEN}`) {
route.fulfill({
status: 403,
contentType: 'application/json',
body: envelope('Admin access required', 'forbidden'),
});
return false;
}
return true;
};
page.route('**/api/v1/auth/me', (route) => {
const header = route.request().headers()['authorization'];
if (header === `Bearer ${ADMIN_TOKEN}`) {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ username: 'alice', is_admin: true }),
});
}
if (header === `Bearer ${USER_TOKEN}`) {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ username: 'bob', is_admin: false }),
});
}
return route.fulfill({
status: 401,
contentType: 'application/json',
body: envelope('Invalid or expired token', 'unauthorized'),
});
});
page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 }));
// Collection endpoint: GET (list) + POST (create).
page.route(/\/api\/v1\/admin\/items(\?.*)?$/, (route) => {
const request = route.request();
if (request.method() === 'GET') {
if (!requireAdmin(route)) return;
const url = new URL(request.url());
const search = (url.searchParams.get('search') ?? '').toLowerCase();
const sortBy = (url.searchParams.get('sort_by') ?? 'created_at') as keyof Item;
const sortOrder = url.searchParams.get('sort_order') ?? 'desc';
const pageSize = Number(url.searchParams.get('page_size') ?? 20);
const page_ = Number(url.searchParams.get('page') ?? 1);
const filtered = store.filter(
(item) =>
!search ||
item.title.toLowerCase().includes(search) ||
item.url.toLowerCase().includes(search),
);
filtered.sort((a, b) => {
const cmp = String(a[sortBy]).localeCompare(String(b[sortBy]));
return sortOrder === 'asc' ? cmp : -cmp;
});
const start = (page_ - 1) * pageSize;
const slice = filtered.slice(start, start + pageSize);
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
items: slice,
total: filtered.length,
page: page_,
page_size: pageSize,
total_pages: Math.ceil(filtered.length / pageSize) || 0,
}),
});
}
if (request.method() === 'POST') {
if (!requireAdmin(route)) return;
const body = request.postDataJSON() as Partial<Item>;
const item: Item = {
id: ++idCounter,
title: body.title ?? '',
url: body.url ?? '',
points: body.points ?? 0,
username: body.username ?? 'alice',
content: body.content ?? '',
created_at: new Date().toISOString(),
};
store.push(item);
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify(item),
});
}
return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') });
});
// Item endpoint: GET / PUT / DELETE by id.
page.route('**/api/v1/admin/items/*', (route) => {
const request = route.request();
const id = Number(request.url().split('/').pop());
if (!requireAdmin(route)) return;
const item = store.find((entry) => entry.id === id);
if (request.method() === 'GET') {
if (!item) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: envelope('Item not found', 'not_found'),
});
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) });
}
if (request.method() === 'PUT') {
if (!item) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: envelope('Item not found', 'not_found'),
});
}
const body = request.postDataJSON() as Partial<Item>;
Object.assign(item, body);
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) });
}
if (request.method() === 'DELETE') {
if (!item) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: envelope('Item not found', 'not_found'),
});
}
store.splice(store.indexOf(item), 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') });
});
return { store, nextId: () => idCounter };
}
async function seedToken(page: Page, token: string | null): Promise<void> {
if (token === null) {
await page.addInitScript((key) => localStorage.removeItem(key), TOKEN_KEY);
} else {
await page.addInitScript(
([key, value]) => localStorage.setItem(key, value),
[TOKEN_KEY, token] as const,
);
}
}
test.describe('admin area (M6)', () => {
test('signed-out users are redirected to /login', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, null);
await page.goto('/admin');
await expect(page).toHaveURL('/login');
});
test('non-admins see the 403 page', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, USER_TOKEN);
await page.goto('/admin');
await expect(page.getByRole('heading', { level: 1, name: '403' })).toBeVisible();
await expect(
page.getByTestId('forbidden-page').getByText(/admin area/i),
).toBeVisible();
});
test('admins see the dashboard with all items and an Admin header link', async ({
page,
}) => {
mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
// The header exposes the admin link for admin accounts.
await page.goto('/');
await expect(page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i })).toBeVisible();
await page.goto('/admin');
await expect(page.getByRole('heading', { level: 1, name: 'Items' })).toBeVisible();
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible();
await expect(page.getByText('Show HN: I built a tiny news app')).toBeVisible();
await expect(page.getByText('Showing 1–3 of 3')).toBeVisible();
});
test('non-admin accounts do not get the Admin header link', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, USER_TOKEN);
await page.goto('/');
await expect(
page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i }),
).toHaveCount(0);
});
test('search filters the list by title or URL', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
await page.getByLabel('Search items').fill('coffee');
await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible();
await expect(
page.getByText('Breaking: local cat discovers keyboard'),
).toHaveCount(0);
// URL search (case-insensitive on the server side).
await page.getByLabel('Search items').fill('EXAMPLE.COM/CAT');
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
await expect(page.getByText('Showing 1–1 of 1')).toBeVisible();
});
test('sorting by title toggles direction', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
const firstTitle = page.locator('tbody tr').first().locator('td').first().locator('span, a').first();
// Default: created_at desc -> newest first.
await expect(firstTitle).toHaveText('Show HN: I built a tiny news app');
await page.getByRole('button', { name: /sort by title/i }).click();
await expect(firstTitle).toHaveText('Breaking: local cat discovers keyboard');
await page.getByRole('button', { name: /sort by title/i }).click();
await expect(firstTitle).toHaveText('Study: coffee improves code reviews');
});
test('create: fills the form, saves with the Lexical editor and lists the item', async ({
page,
}) => {
const { store } = mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin/items/new');
await expect(page.getByRole('heading', { level: 1, name: 'New item' })).toBeVisible();
await page.getByLabel(/^Title/).fill('E2E: fresh story from the admin area');
await page.getByLabel(/^URL/).fill('https://example.com/e2e-story');
await page.getByLabel('Points').fill('3');
// The author is pre-filled from the session.
await expect(page.getByLabel('Author')).toHaveValue('alice');
// Type into the Lexical contenteditable (rich text editor).
await page.getByLabel('Item content').click();
await page.keyboard.type('Written with the Lexical editor.');
await page.getByRole('button', { name: /create item/i }).click();
// Back on the dashboard with the success notice.
await expect(page).toHaveURL('/admin');
await expect(page.getByRole('status')).toHaveText(/was saved/i);
await expect(page.getByText('E2E: fresh story from the admin area', { exact: true })).toBeVisible();
// The backend received the rich content.
const created = store.find((item) =>
item.title.includes('E2E: fresh story'),
);
expect(created).toBeTruthy();
expect(created?.content).toContain('Written with the Lexical editor.');
expect(created?.points).toBe(3);
expect(created?.username).toBe('alice');
});
test('edit: loads the item, updates fields and saves', async ({ page }) => {
const { store } = mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
await page.locator('tbody tr', { hasText: 'Breaking: local cat' }).getByRole('link', { name: /edit/i }).click();
await expect(page.getByRole('heading', { level: 1, name: /edit item/i })).toBeVisible();
await expect(page.getByLabel(/^Title/)).toHaveValue('Breaking: local cat discovers keyboard');
await expect(page.getByLabel('Points')).toHaveValue('42');
await page.getByLabel(/^Title/).fill('Breaking: local cat becomes famous');
await page.getByRole('button', { name: /save changes/i }).click();
await expect(page).toHaveURL('/admin');
await expect(page.getByRole('status')).toHaveText(/was saved/i);
await expect(page.getByRole('cell', { name: 'Breaking: local cat becomes famous', exact: true })).toBeVisible();
const updated = store.find((item) => item.id === 1);
expect(updated?.title).toBe('Breaking: local cat becomes famous');
// Untouched fields survive the partial save.
expect(updated?.points).toBe(42);
});
test('delete: requires confirmation, then removes the item', async ({ page }) => {
const { store } = mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
const target = page.getByText('Study: coffee improves code reviews');
await expect(target).toBeVisible();
// Open the confirmation dialog (first row's delete button).
page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(
dialog.getByRole('heading', { name: /are you sure you want to delete/i }),
).toBeVisible();
await expect(dialog.getByText(/cannot be undone/i)).toBeVisible();
// Cancel keeps the item.
await dialog.getByRole('button', { name: /cancel/i }).click();
await expect(dialog).toHaveCount(0);
await expect(target).toBeVisible();
expect(store).toHaveLength(3);
// Confirm with the explicit "Yes, delete" action.
page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click();
await expect(page.getByRole('dialog')).toBeVisible();
await page.getByRole('button', { name: /yes, delete/i }).click();
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
await expect(page.getByRole('cell', { name: 'Study: coffee improves code reviews', exact: true })).toHaveCount(0);
await expect(page.getByRole('status')).toHaveText(/was deleted/i);
expect(store).toHaveLength(2);
});
test('pagination: next/previous and the page size selector work', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
// 3 seeded items fit on one page: navigation is disabled.
await expect(page.getByRole('button', { name: /next/i })).toBeDisabled();
await expect(page.getByRole('button', { name: /previous/i })).toBeDisabled();
// Smaller page size splits the list across pages.
await page.getByLabel('Rows per page').selectOption('10');
await expect(page).toHaveURL(/\/admin/);
// (Still one page for 3 items — assert the selector round-trips.)
await expect(page.getByLabel('Rows per page')).toHaveValue('10');
});
});