From afa399776f8c6ef8c6b2d8e73b13213a69c8c29c Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:31:05 +0000 Subject: [PATCH] feat(admin): rebuild admin area around the Article domain The admin area was managing a Hacker News-style Item model that the public site never consumed, so the homepage always fell back to sample data. Rebuild the admin area around the real public content model. Backend: - Remove the Item model, schema and admin API - Admin API now manages articles at /api/v1/admin/articles (CRUD) with /api/v1/admin/authors and /api/v1/admin/categories reference data - Add public read-only article endpoints (/api/v1/articles, /api/v1/articles/{id}): no auth, published-only, newest-first - Rewrite Article schemas; ArticleRead embeds author and category - Add idempotent seed_content.py dev seeder (3 authors, 4 categories, 6 published articles) Frontend: - Admin UI rewritten around articles: AdminDashboard list, new EditArticlePage (create/edit, author/category selects, published toggle, Lexical editor, debounced auto-save) - Replace AdminItem types and api client with the article domain - Update App routes, AdminLayout sidebar, DeleteConfirmation, Lexical editor labels and Home/client comments to article terminology Tests: - Rewrite admin unit tests and the Playwright admin e2e spec for the article domain; add test_articles.py for the public endpoints and seeder --- backend/api/v1/__init__.py | 6 +- backend/api/v1/admin.py | 229 ++++-- backend/api/v1/articles.py | 55 ++ backend/models/__init__.py | 3 +- backend/models/item.py | 43 -- backend/schemas/__init__.py | 21 +- backend/schemas/article.py | 24 +- backend/schemas/item.py | 102 --- backend/seed_content.py | 197 +++++ backend/tests/test_admin.py | 480 ++++++++---- backend/tests/test_articles.py | 176 +++++ backend/tests/test_models.py | 33 +- frontend/playwright/e2e/admin.spec.ts | 714 +++++++++++------- frontend/src/App.tsx | 6 +- frontend/src/api/admin.ts | 54 +- frontend/src/api/client.ts | 6 +- frontend/src/components/AdminLayout.tsx | 6 +- .../src/components/DeleteConfirmation.tsx | 12 +- frontend/src/components/LexicalEditor.tsx | 4 +- frontend/src/pages/AdminDashboard.tsx | 131 ++-- frontend/src/pages/EditArticlePage.tsx | 516 +++++++++++++ frontend/src/pages/EditItemPage.tsx | 441 ----------- frontend/src/pages/Home.tsx | 9 +- frontend/src/tests/admin/admin-api.test.ts | 112 +-- .../src/tests/admin/admin-dashboard.test.tsx | 110 +-- .../tests/admin/delete-confirmation.test.tsx | 20 +- .../tests/admin/edit-article-page.test.tsx | 289 +++++++ .../src/tests/admin/edit-item-page.test.tsx | 275 ------- frontend/src/types/admin.ts | 49 +- 29 files changed, 2465 insertions(+), 1658 deletions(-) create mode 100644 backend/api/v1/articles.py delete mode 100644 backend/models/item.py delete mode 100644 backend/schemas/item.py create mode 100644 backend/seed_content.py create mode 100644 backend/tests/test_articles.py create mode 100644 frontend/src/pages/EditArticlePage.tsx delete mode 100644 frontend/src/pages/EditItemPage.tsx create mode 100644 frontend/src/tests/admin/edit-article-page.test.tsx delete mode 100644 frontend/src/tests/admin/edit-item-page.test.tsx diff --git a/backend/api/v1/__init__.py b/backend/api/v1/__init__.py index fe0df20..8a80f67 100644 --- a/backend/api/v1/__init__.py +++ b/backend/api/v1/__init__.py @@ -6,16 +6,20 @@ Mounted under ``/api/v1`` (see ``core.app.create_app``). from fastapi import APIRouter from api.v1 import admin as admin_routes +from api.v1 import articles as articles_routes from api.v1 import auth as auth_routes from config import APP_NAME, APP_VERSION from schemas import HealthResponse, VersionResponse router = APIRouter() +# Public article feed (no auth) under /api/v1/articles. +router.include_router(articles_routes.router) + # Authentication (register / login / logout / me) under /api/v1/auth. router.include_router(auth_routes.router) -# Admin area (item CRUD, admin-only) under /api/v1/admin. +# Admin area (article CRUD, admin-only) under /api/v1/admin. router.include_router(admin_routes.router) diff --git a/backend/api/v1/admin.py b/backend/api/v1/admin.py index bdb60e9..71410e4 100644 --- a/backend/api/v1/admin.py +++ b/backend/api/v1/admin.py @@ -1,4 +1,4 @@ -"""Admin area endpoints: item CRUD for site administrators. +"""Admin area endpoints: article CRUD for site administrators. Every route requires a valid Bearer token **and** ``User.is_admin`` (see ``core.auth.get_current_admin``); non-admins receive 403. A simple @@ -6,13 +6,20 @@ in-memory rate limiter (``_RateLimiter``) caps the request volume per admin account — a deliberately light-weight placeholder that can be replaced by a production-grade limiter later. +The admin area manages the content readers see: every article has a title, +an HTML body, an ``Author``, a ``Category`` and a ``published`` flag. +Two read-only reference endpoints (``/authors``, ``/categories``) feed the +article form's select boxes. + Routes (mounted under ``/api/v1/admin``): -- ``GET /items`` paginated list with search and sorting -- ``POST /items`` create an item -- ``GET /items/{id}`` fetch a single item -- ``PUT /items/{id}`` update an item (partial updates supported) -- ``DELETE /items/{id}`` delete an item +- ``GET /articles`` paginated list with search and sorting +- ``POST /articles`` create an article +- ``GET /articles/{id}`` fetch a single article +- ``PUT /articles/{id}`` update an article (partial updates supported) +- ``DELETE /articles/{id}`` delete an article +- ``GET /authors`` all authors (form reference data) +- ``GET /categories`` all categories (form reference data) """ from __future__ import annotations @@ -23,12 +30,15 @@ from typing import Literal from fastapi import APIRouter, Depends, HTTPException, Query, status from sqlalchemy import asc, desc, or_ -from sqlalchemy.orm import Session +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session, joinedload from core import auth from db.session import get_db -from models import Item, User -from schemas import ItemAdminList, ItemCreate, ItemRead, ItemUpdate +from models import Article, Author, Category, User +from schemas import ArticleAdminList, ArticleCreate, ArticleRead, ArticleUpdate +from schemas.author import AuthorRead +from schemas.category import CategoryRead router = APIRouter(prefix="/admin", tags=["admin"]) @@ -41,8 +51,8 @@ class _RateLimiter: """Fixed-window request limiter keyed by an arbitrary string. Thread-safe (the admin endpoints run in FastAPI's threadpool). Kept - intentionally simple — a "placeholder" per the M6 milestone that can - be swapped for a shared/production limiter without touching routes. + intentionally simple — a "placeholder" per the M6 milestone that can be + swapped for a shared/production limiter without touching routes. """ def __init__(self, limit: int = 1000, window_seconds: float = 60.0) -> None: @@ -86,54 +96,90 @@ def _rate_limit(admin: User = Depends(auth.get_current_admin)) -> User: # --------------------------------------------------------------------------- -def _get_item_or_404(db: Session, item_id: int) -> Item: - item = db.query(Item).filter(Item.id == item_id).first() - if item is None: - raise HTTPException(status_code=404, detail="Item not found") - return item +def _get_article_or_404(db: Session, article_id: int) -> Article: + article = ( + db.query(Article) + .options(joinedload(Article.author), joinedload(Article.category)) + .filter(Article.id == article_id) + .first() + ) + if article is None: + raise HTTPException(status_code=404, detail="Article not found") + return article def _apply_search(query, search: str): - """Filter by ``title`` OR ``url`` (case-insensitive substring match).""" + """Filter by ``title`` OR ``content`` (case-insensitive substring match).""" if not search: return query pattern = f"%{search}%" - return query.filter(or_(Item.title.ilike(pattern), Item.url.ilike(pattern))) + return query.filter( + or_(Article.title.ilike(pattern), Article.content.ilike(pattern)) + ) def _apply_sort(query, sort_by: str, sort_order: str): - column = getattr(Item, sort_by) + column = getattr(Article, sort_by) return query.order_by(asc(column) if sort_order == "asc" else desc(column)) +def _validate_author(db: Session, author_id: int) -> None: + """422 with a clear message when the author does not exist.""" + if db.get(Author, author_id) is None: + raise HTTPException(status_code=422, detail=f"Author {author_id} not found") + + +def _validate_category(db: Session, category_id: int) -> None: + """422 with a clear message when the category does not exist.""" + if db.get(Category, category_id) is None: + raise HTTPException(status_code=422, detail=f"Category {category_id} not found") + + +def _commit(db: Session, action: str) -> None: + """Commit, converting a title collision into a 409 conflict.""" + try: + db.commit() + except IntegrityError: + db.rollback() + raise HTTPException( + status_code=409, + detail=f"An article with this title already exists ({action}).", + ) + + # --------------------------------------------------------------------------- # Endpoints # --------------------------------------------------------------------------- @router.get( - "/items", - response_model=ItemAdminList, - summary="List items (paginated, searchable, sortable)", + "/articles", + response_model=ArticleAdminList, + summary="List articles (paginated, searchable, sortable)", ) -def list_items( +def list_articles( page: int = Query(default=1, ge=1, description="1-based page number"), page_size: int = Query( - default=20, ge=1, le=100, description="Items per page (1-100)" + default=20, ge=1, le=100, description="Articles per page (1-100)" ), - search: str = Query(default="", max_length=200, description="Match title or URL"), - sort_by: Literal["title", "created_at", "points"] = "created_at", + search: str = Query( + default="", max_length=200, description="Match title or content" + ), + sort_by: Literal["title", "created_at"] = "created_at", sort_order: Literal["asc", "desc"] = "desc", admin: User = Depends(_rate_limit), db: Session = Depends(get_db), -) -> ItemAdminList: - """List all items with pagination, case-insensitive search and sorting.""" - query = _apply_sort(_apply_search(db.query(Item), search), sort_by, sort_order) +) -> ArticleAdminList: + """List all articles with pagination, case-insensitive search and sorting.""" + query = db.query(Article).options( + joinedload(Article.author), joinedload(Article.category) + ) + query = _apply_sort(_apply_search(query, search), sort_by, sort_order) total = query.count() - items = query.offset((page - 1) * page_size).limit(page_size).all() + articles = query.offset((page - 1) * page_size).limit(page_size).all() total_pages = (total + page_size - 1) // page_size - return ItemAdminList( - items=[ItemRead.model_validate(item) for item in items], + return ArticleAdminList( + articles=[ArticleRead.model_validate(article) for article in articles], total=total, page=page, page_size=page_size, @@ -142,83 +188,112 @@ def list_items( @router.post( - "/items", - response_model=ItemRead, + "/articles", + response_model=ArticleRead, status_code=status.HTTP_201_CREATED, - summary="Create a new item", + summary="Create a new article", ) -def create_item( - payload: ItemCreate, +def create_article( + payload: ArticleCreate, admin: User = Depends(_rate_limit), db: Session = Depends(get_db), -) -> ItemRead: - """Create an item; it belongs to ``username`` or the admin when omitted.""" - item = Item( +) -> ArticleRead: + """Create an article (draft by default unless ``published`` is set).""" + _validate_author(db, payload.author_id) + _validate_category(db, payload.category_id) + article = Article( title=payload.title, - url=payload.url, - points=payload.points, - username=(payload.username or admin.username).strip(), content=payload.content, + author_id=payload.author_id, + category_id=payload.category_id, + published=payload.published, ) - db.add(item) - db.commit() - db.refresh(item) - return ItemRead.model_validate(item) + db.add(article) + _commit(db, action="create") + db.refresh(article) + return ArticleRead.model_validate(article) @router.get( - "/items/{item_id}", - response_model=ItemRead, - summary="Get a single item", + "/articles/{article_id}", + response_model=ArticleRead, + summary="Get a single article", ) -def get_item( - item_id: int, +def get_article( + article_id: int, admin: User = Depends(_rate_limit), db: Session = Depends(get_db), -) -> ItemRead: - """Fetch one item by id (404 when it does not exist).""" - return ItemRead.model_validate(_get_item_or_404(db, item_id)) +) -> ArticleRead: + """Fetch one article by id (404 when it does not exist).""" + return ArticleRead.model_validate(_get_article_or_404(db, article_id)) @router.put( - "/items/{item_id}", - response_model=ItemRead, - summary="Update an item", + "/articles/{article_id}", + response_model=ArticleRead, + summary="Update an article", ) -def update_item( - item_id: int, - payload: ItemUpdate, +def update_article( + article_id: int, + payload: ArticleUpdate, admin: User = Depends(_rate_limit), db: Session = Depends(get_db), -) -> ItemRead: - """Update an item; only the provided fields change (partial update).""" - item = _get_item_or_404(db, item_id) +) -> ArticleRead: + """Update an article; only the provided fields change (partial update).""" + article = _get_article_or_404(db, article_id) updates = payload.model_dump(exclude_unset=True) - if "username" in updates and updates["username"] is not None: - updates["username"] = updates["username"].strip() + if updates.get("author_id") is not None: + _validate_author(db, updates["author_id"]) + if updates.get("category_id") is not None: + _validate_category(db, updates["category_id"]) for field, value in updates.items(): - setattr(item, field, value) - db.commit() - db.refresh(item) - return ItemRead.model_validate(item) + setattr(article, field, value) + _commit(db, action="update") + db.refresh(article) + return ArticleRead.model_validate(article) @router.delete( - "/items/{item_id}", + "/articles/{article_id}", status_code=status.HTTP_204_NO_CONTENT, - summary="Delete an item", + summary="Delete an article", ) -def delete_item( - item_id: int, +def delete_article( + article_id: int, admin: User = Depends(_rate_limit), db: Session = Depends(get_db), ) -> None: - """Hard-delete an item (404 when it does not exist).""" - item = _get_item_or_404(db, item_id) - db.delete(item) + """Hard-delete an article (404 when it does not exist).""" + article = _get_article_or_404(db, article_id) + db.delete(article) db.commit() return None +# --------------------------------------------------------------------------- +# Reference data for the article form +# --------------------------------------------------------------------------- + + +@router.get("/authors", response_model=list[AuthorRead], summary="List authors") +def list_authors( + admin: User = Depends(_rate_limit), + db: Session = Depends(get_db), +) -> list[Author]: + """All authors, ordered by name (feeds the article form's author select).""" + return db.query(Author).order_by(asc(Author.name)).all() + + +@router.get( + "/categories", response_model=list[CategoryRead], summary="List categories" +) +def list_categories( + admin: User = Depends(_rate_limit), + db: Session = Depends(get_db), +) -> list[Category]: + """All categories, ordered by name (feeds the article form's category select).""" + return db.query(Category).order_by(asc(Category.name)).all() + + # Re-exported for tests and documentation. __all__ = ["router", "_limiter", "_rate_limit"] diff --git a/backend/api/v1/articles.py b/backend/api/v1/articles.py new file mode 100644 index 0000000..cf38ef5 --- /dev/null +++ b/backend/api/v1/articles.py @@ -0,0 +1,55 @@ +"""Public read API for articles. + +No authentication required — these endpoints power the site front end: + +* ``GET /api/v1/articles`` — the home page feed. Returns *published* articles + newest-first, each with its author and category embedded. +* ``GET /api/v1/articles/{id}`` — a single published article (404 when missing + or still a draft). + +Drafts (``published=False``) are never exposed here; admins manage them via +the admin area (``api.v1.admin``). +""" + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session, joinedload + +from db.session import get_db +from models import Article +from schemas import ArticleRead + +router = APIRouter(prefix="/articles", tags=["articles"]) + + +def _load_published_article(db: Session, article_id: int) -> Article: + article = ( + db.query(Article) + .options(joinedload(Article.author), joinedload(Article.category)) + .filter(Article.id == article_id, Article.published.is_(True)) + .first() + ) + if article is None: + raise HTTPException(status_code=404, detail="Article not found") + return article + + +@router.get("", response_model=list[ArticleRead], summary="List published articles") +def list_published_articles( + db: Session = Depends(get_db), +) -> list[Article]: + """Published articles, newest first, with author and category embedded.""" + return ( + db.query(Article) + .options(joinedload(Article.author), joinedload(Article.category)) + .filter(Article.published.is_(True)) + .order_by(Article.created_at.desc()) + .all() + ) + + +@router.get("/{article_id}", response_model=ArticleRead, summary="Get a published article") +def get_published_article( + article_id: int, + db: Session = Depends(get_db), +) -> Article: + return _load_published_article(db, article_id) diff --git a/backend/models/__init__.py b/backend/models/__init__.py index c8a071c..db1aaae 100644 --- a/backend/models/__init__.py +++ b/backend/models/__init__.py @@ -4,7 +4,6 @@ from models.article import Article from models.author import Author from models.base import Base from models.category import Category, slugify -from models.item import Item from models.user import User -__all__ = ["Article", "Author", "Base", "Category", "Item", "User", "slugify"] +__all__ = ["Article", "Author", "Base", "Category", "User", "slugify"] diff --git a/backend/models/item.py b/backend/models/item.py deleted file mode 100644 index c12200e..0000000 --- a/backend/models/item.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Item model: a news story managed through the admin area. - -Unlike ``Article`` (long-form pieces filed under an author and category), -an ``Item`` is a lightweight news entry — headline, optional external URL, -community points and an optional HTML body — created and maintained by -administrators through the admin API (see ``api.v1.admin``). -""" - -from __future__ import annotations - -from datetime import datetime, timezone - -from sqlalchemy import DateTime, Integer, String, Text -from sqlalchemy.orm import Mapped, mapped_column - -from models.base import Base - - -def _utcnow() -> datetime: - return datetime.now(timezone.utc) - - -class Item(Base): - """A news item (story) listed on the front page and managed by admins. - - ``username`` stores the (denormalized) name of the user the item - belongs to, defaulting to the account that created it. - """ - - __tablename__ = "items" - - id: Mapped[int] = mapped_column(primary_key=True) - title: Mapped[str] = mapped_column(String(300), nullable=False, index=True) - url: Mapped[str] = mapped_column(String(500), default="", nullable=False) - points: Mapped[int] = mapped_column(Integer, default=0, nullable=False) - username: Mapped[str] = mapped_column(String(60), default="anonymous", nullable=False) - content: Mapped[str] = mapped_column(Text, default="", nullable=False) - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), default=_utcnow, nullable=False - ) - - def __repr__(self) -> str: # pragma: no cover - return f"" diff --git a/backend/schemas/__init__.py b/backend/schemas/__init__.py index 5461b37..f6ecf98 100644 --- a/backend/schemas/__init__.py +++ b/backend/schemas/__init__.py @@ -1,13 +1,24 @@ """Pydantic request/response schemas for newzy.""" -from schemas.article import ArticleBase, ArticleCreate, ArticleRead, ArticleUpdate +from schemas.article import ( + ArticleAdminList, + ArticleBase, + ArticleCreate, + ArticleRead, + ArticleUpdate, +) from schemas.auth import LoginIn, RegisterIn, TokenOut, UserOut from schemas.author import AuthorBase, AuthorCreate, AuthorRead, AuthorUpdate -from schemas.category import CategoryBase, CategoryCreate, CategoryRead, CategoryUpdate +from schemas.category import ( + CategoryBase, + CategoryCreate, + CategoryRead, + CategoryUpdate, +) from schemas.common import ErrorDetail, HealthResponse, VersionResponse -from schemas.item import ItemAdminList, ItemCreate, ItemRead, ItemUpdate __all__ = [ + "ArticleAdminList", "ArticleBase", "ArticleCreate", "ArticleRead", @@ -22,10 +33,6 @@ __all__ = [ "CategoryUpdate", "ErrorDetail", "HealthResponse", - "ItemAdminList", - "ItemCreate", - "ItemRead", - "ItemUpdate", "LoginIn", "RegisterIn", "TokenOut", diff --git a/backend/schemas/article.py b/backend/schemas/article.py index 7585b9c..fe2b36b 100644 --- a/backend/schemas/article.py +++ b/backend/schemas/article.py @@ -1,9 +1,17 @@ -"""Schemas for the Article model.""" +"""Schemas for the Article model. + +``ArticleRead`` embeds the related ``author`` and ``category`` so both the +public feed and the admin area can render full article details from a single +payload (the ORM relationships are loaded via ``from_attributes``). +""" from datetime import datetime from pydantic import BaseModel, ConfigDict, Field +from schemas.author import AuthorRead +from schemas.category import CategoryRead + class ArticleBase(BaseModel): """Fields shared by create/update/read article schemas.""" @@ -31,7 +39,7 @@ class ArticleUpdate(BaseModel): class ArticleRead(BaseModel): - """Article as returned by the API.""" + """Article as returned by the API, with related author/category.""" model_config = ConfigDict(from_attributes=True) @@ -42,3 +50,15 @@ class ArticleRead(BaseModel): category_id: int created_at: datetime published: bool + author: AuthorRead + category: CategoryRead + + +class ArticleAdminList(BaseModel): + """Paginated article list of ``GET /api/v1/admin/articles``.""" + + articles: list[ArticleRead] + total: int + page: int + page_size: int + total_pages: int diff --git a/backend/schemas/item.py b/backend/schemas/item.py deleted file mode 100644 index d959c64..0000000 --- a/backend/schemas/item.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Schemas for the Item model (admin area, see ``api.v1.admin``).""" - -from datetime import datetime -from urllib.parse import urlsplit - -from pydantic import BaseModel, ConfigDict, Field, field_validator - - -def _clean_title(value: str) -> str: - stripped = value.strip() - if not stripped: - raise ValueError("title must not be empty") - return stripped - - -def _clean_url(value: str | None) -> str: - """Normalize an optional URL: empty/blank -> ``""``, otherwise it must - be an absolute ``http://`` or ``https://`` URL.""" - if value is None: - return "" - stripped = value.strip() - if not stripped: - return "" - parsed = urlsplit(stripped) - if parsed.scheme not in ("http", "https") or not parsed.netloc: - raise ValueError("must be an absolute http:// or https:// URL") - return stripped - - -class ItemBase(BaseModel): - """Fields shared by the item create schema and the read model.""" - - title: str = Field(..., min_length=1, max_length=300) - url: str = Field(default="", max_length=500) - points: int = Field(default=0, ge=0) - content: str = Field(default="", description="HTML body from the Lexical editor.") - - @field_validator("title") - @classmethod - def _strip_title(cls, value: str) -> str: - return _clean_title(value) - - @field_validator("url") - @classmethod - def _validate_url(cls, value: str) -> str: - return _clean_url(value) - - -class ItemCreate(ItemBase): - """Payload of ``POST /api/v1/admin/items``. - - ``username`` is optional: when omitted the item belongs to the - authenticated admin. - """ - - username: str | None = Field(default=None, min_length=1, max_length=60) - - -class ItemUpdate(BaseModel): - """Payload of ``PUT /api/v1/admin/items/{id}`` (all fields optional).""" - - title: str | None = Field(default=None, max_length=300) - url: str | None = Field(default=None, max_length=500) - points: int | None = Field(default=None, ge=0) - username: str | None = Field(default=None, min_length=1, max_length=60) - content: str | None = None - - @field_validator("title") - @classmethod - def _strip_title(cls, value: str | None) -> str | None: - if value is None: - return None - return _clean_title(value) - - @field_validator("url") - @classmethod - def _validate_url(cls, value: str | None) -> str | None: - return None if value is None else _clean_url(value) - - -class ItemRead(BaseModel): - """Item as returned by the admin API.""" - - model_config = ConfigDict(from_attributes=True) - - id: int - title: str - url: str - points: int - username: str - content: str - created_at: datetime - - -class ItemAdminList(BaseModel): - """Paginated item list of ``GET /api/v1/admin/items``.""" - - items: list[ItemRead] - total: int - page: int - page_size: int - total_pages: int diff --git a/backend/seed_content.py b/backend/seed_content.py new file mode 100644 index 0000000..1e2be74 --- /dev/null +++ b/backend/seed_content.py @@ -0,0 +1,197 @@ +"""Seed demo content: authors, categories and published articles. + +Usage (inside the backend container or with the backend venv):: + + python seed_content.py + +Idempotent — safe to re-run. Existing authors (matched by email), +categories (matched by slug) and articles (matched by title) are left +untouched; only missing rows are created. The seeded dataset mirrors the +front end's sample data (``frontend/src/data/sample.ts``) so the site has +real content to serve until the admin area is used. +""" + +from __future__ import annotations + +from datetime import datetime + +from db.session import SessionLocal +from models import Article, Author, Category + +AUTHORS: list[dict] = [ + { + "name": "Ada Lovelace", + "email": "ada@example.com", + "bio": "Writes about technology and computation.", + }, + { + "name": "Grace Hopper", + "email": "grace@example.com", + "bio": "Covers science and engineering.", + }, + { + "name": "Alan Turing", + "email": "alan@example.com", + "bio": "Follows sports and culture.", + }, +] + +CATEGORIES: list[dict] = [ + {"name": "Technology", "slug": "technology"}, + {"name": "Science", "slug": "science"}, + {"name": "Sports", "slug": "sports"}, + {"name": "Culture", "slug": "culture"}, +] + +# (title, body, author_email, category_slug, created_at, published) +ARTICLES: list[tuple[str, str, str, str, str, bool]] = [ + ( + "Inside the new wave of open-source language models", + 'Open-source language models are closing the gap with proprietary systems, ' + "and the ecosystem around them is growing fast. Researchers now release " + "pretrained weights alongside detailed training recipes, letting smaller " + 'teams fine-tune models for narrow tasks that once required large budgets. ' + 'The result is a new layer of the AI stack: community-maintained tooling ' + 'for evaluation, deployment, and safety testing that moves at a pace big ' + 'vendors struggle to match. As hardware costs keep falling, expect the line ' + 'between "research model" and "production model" to blur further this year.', + "ada@example.com", + "technology", + "2025-06-02T09:30:00Z", + True, + ), + ( + "Fusion milestone: net energy gain repeated for the third time", + "Scientists have repeated a net-energy-gain fusion reaction for the third " + "consecutive time, confirming that last months breakthrough was not a fluke. " + "The latest run sustained the plasma for a record duration and produced " + "energy output within a few percent of the original measurement. Engineers " + "now say the remaining challenges are engineering, not physics: materials " + "that survive repeated shots and power systems that deliver pulses on " + "demand. A commercial demonstration plant could enter the design phase as " + "early as next decade.", + "grace@example.com", + "science", + "2025-05-28T14:10:00Z", + True, + ), + ( + "City marathon sets record turnout as first-timers flood the course", + "More than 40,000 runners started this weekend city marathon, a record that " + "organizers attributed to a wave of first-time participants. The 21-kilometer " + "fun run sold out in under an hour, and volunteers reported the most positive " + "start-line atmosphere in the events history. Pacing groups, music zones, and " + "a free post-race breakfast kept the mood festive even in the rain. Officials " + "are already planning capacity expansions for next year, with an eye on adding " + "a night race.", + "alan@example.com", + "sports", + "2025-05-25T08:00:00Z", + True, + ), + ( + "The quiet return of the neighborhood library", + "After years of budget cuts, the neighborhood library is staging an unlikely " + "comeback. Community volunteers now staff the Saturday makerspace, where 3D " + "printing, sewing machines, and a small recording studio are booked weeks in " + "advance. Librarians report that circulation is up, but the real story is " + "programming: repair cafés, language tables, and civic workshops that have " + "made the building a second living room for the district. City planners are " + "taking note, and two more branches are slated for renovation this fall.", + "ada@example.com", + "culture", + "2025-05-20T17:45:00Z", + True, + ), + ( + "Rust keeps climbing the systems programming charts", + "Rust has moved up again in the annual systems programming survey, now the " + "most-wanted language for kernel and infrastructure work among respondents. " + "Adoption is no longer limited to startups: several large platforms report " + "that new storage and networking services are written in Rust by default. The " + "ecosystems memory-safety guarantees, combined with a mature async story, " + "continue to draw engineers from C and C++. Tooling improvements in debugging " + "and profiling have been the most cited reasons for teams crossing over this " + "year.", + "grace@example.com", + "technology", + "2025-05-15T11:20:00Z", + True, + ), + ( + "Ocean robots map the deepest trenches in record time", + "A fleet of autonomous underwater vehicles has completed the most detailed " + "survey of the ocean trench yet, mapping 80 percent of the basin floor in six " + "weeks. The robots, equipped with multibeam sonar and high-resolution " + "cameras, collected terabytes of data that reveal previously unknown " + "seamounts and hydrothermal vent fields. Biologists have already flagged " + "three candidate species from the first batch of imagery. The team plans to " + "return next winter with sampling landers to study the vent communities up " + "close.", + "alan@example.com", + "science", + "2025-05-10T19:05:00Z", + True, + ), +] + + +def main() -> int: + db = SessionLocal() + try: + authors: dict[str, Author] = {} + for spec in AUTHORS: + existing = ( + db.query(Author).filter(Author.email == spec["email"]).first() + ) + if existing is not None: + authors[spec["email"]] = existing + continue + author = Author(**spec) + db.add(author) + db.flush() + authors[spec["email"]] = author + print(f"Created author '{spec['name']}'.") + + categories: dict[str, Category] = {} + for spec in CATEGORIES: + existing = ( + db.query(Category).filter(Category.slug == spec["slug"]).first() + ) + if existing is not None: + categories[spec["slug"]] = existing + continue + category = Category(**spec) + db.add(category) + db.flush() + categories[spec["slug"]] = category + print(f"Created category '{spec['name']}'.") + + for title, content, email, slug, created, published in ARTICLES: + if db.query(Article).filter(Article.title == title).first() is not None: + continue + article = Article( + title=title, + content=content, + author_id=authors[email].id, + category_id=categories[slug].id, + created_at=datetime.fromisoformat(created.replace("Z", "+00:00")), + published=published, + ) + db.add(article) + print(f"Created article '{title}'.") + + db.commit() + print( + "Done. " + f"{db.query(Author).count()} authors, " + f"{db.query(Category).count()} categories, " + f"{db.query(Article).count()} articles." + ) + return 0 + finally: + db.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 9adce82..5a42563 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -1,7 +1,9 @@ -"""Tests for the admin area: /api/v1/admin/items CRUD, access control. +"""Tests for the admin area (M6): /api/v1/admin/articles CRUD, reference +data (authors/categories), access control, rate limiting, and the is_admin +startup migration. Covers the M6 acceptance criteria: 401/403 handling for the admin -dependency, pagination/search/sort on the list endpoint, item creation, +dependency, pagination/search/sort on the list endpoint, article creation, partial updates, deletion and input validation. """ @@ -13,9 +15,9 @@ import pytest from api.v1 import admin as admin_api from core import auth -from models import Item, User +from models import Article, Author, Category, User -BASE = "/api/v1/admin/items" +BASE = "/api/v1/admin/articles" def _make_user(session, username: str, is_admin: bool = False) -> User: @@ -30,37 +32,65 @@ def _headers(session, username: str) -> dict: return {"Authorization": f"Bearer {auth.create_token(username)}"} -def _seed_items(session, count: int, prefix: str = "Story") -> list[Item]: - items = [] - for i in range(count): - item = Item( - title=f"{prefix} {i:02d}", - url=f"https://example.com/story-{i}", - points=i, - username="alice", - content=f"

Body {i}

", - ) - session.add(item) - items.append(item) +def _make_author( + session, name: str = "Byline Writer", email: str = "writer@example.com" +) -> Author: + author = Author(name=name, email=email) + session.add(author) session.commit() - return items + return author + + +def _make_category( + session, name: str = "Technology", slug: str = "technology" +) -> Category: + category = Category(name=name, slug=slug) + session.add(category) + session.commit() + return category + + +def _seed_articles( + session, + count: int, + prefix: str = "Story", + author: Author | None = None, + category: Category | None = None, +) -> list[Article]: + author = author or _make_author(session) + category = category or _make_category(session) + articles = [] + for i in range(count): + article = Article( + title=f"{prefix} {i:02d}", + content=f"

Body {i}

", + author_id=author.id, + category_id=category.id, + published=True, + ) + session.add(article) + articles.append(article) + session.commit() + return articles + + +ADMIN_ROUTES = [ + ("GET", f"{BASE}"), + ("POST", BASE), + ("GET", f"{BASE}/1"), + ("PUT", f"{BASE}/1"), + ("DELETE", f"{BASE}/1"), + ("GET", "/api/v1/admin/authors"), + ("GET", "/api/v1/admin/categories"), +] class TestAdminAccessControl: """The admin dependency validates the JWT AND the is_admin flag.""" - @pytest.mark.parametrize( - "method, path", - [ - ("GET", f"{BASE}"), - ("POST", BASE), - ("GET", f"{BASE}/1"), - ("PUT", f"{BASE}/1"), - ("DELETE", f"{BASE}/1"), - ], - ) + @pytest.mark.parametrize("method, path", ADMIN_ROUTES) def test_missing_token_returns_401(self, client, method, path) -> None: - payload = {"title": "x"} if method == "POST" else ({"title": "y"} if method == "PUT" else None) + payload = {"title": "x"} if method in ("POST", "PUT") else None response = client.request(method, path, json=payload) assert response.status_code == 401 assert response.json()["code"] == "unauthorized" @@ -82,27 +112,18 @@ class TestAdminAccessControl: assert response.status_code == 401 def test_token_for_deleted_user_returns_401(self, client, session) -> None: - user = _make_user(session, "admin", is_admin=True) + _make_user(session, "admin", is_admin=True) headers = _headers(session, "admin") - session.delete(user) + session.delete(session.query(User).filter(User.username == "admin").one()) session.commit() response = client.get(BASE, headers=headers) assert response.status_code == 401 assert response.json()["detail"] == "Unknown user" - @pytest.mark.parametrize( - "method, path", - [ - ("GET", f"{BASE}"), - ("POST", BASE), - ("GET", f"{BASE}/1"), - ("PUT", f"{BASE}/1"), - ("DELETE", f"{BASE}/1"), - ], - ) + @pytest.mark.parametrize("method, path", ADMIN_ROUTES) def test_non_admin_receives_403(self, client, session, method, path) -> None: _make_user(session, "alice", is_admin=False) - payload = {"title": "x"} if method == "POST" else ({"title": "y"} if method == "PUT" else None) + payload = {"title": "x"} if method in ("POST", "PUT") else None response = client.request( method, path, json=payload, headers=_headers(session, "alice") ) @@ -111,21 +132,14 @@ class TestAdminAccessControl: assert body["code"] == "forbidden" assert body["detail"] == "Admin access required" - def test_admin_dependency_returns_the_user_object(self, client, session) -> None: - """get_current_admin yields the ORM user (used for audit logging later).""" - admin = _make_user(session, "root", is_admin=True) - response = client.get(BASE, headers=_headers(session, "root")) - assert response.status_code == 200 - assert admin.is_admin is True - -class TestListItems: +class TestListArticles: def test_empty_list(self, client, session) -> None: _make_user(session, "root", is_admin=True) response = client.get(BASE, headers=_headers(session, "root")) assert response.status_code == 200 body = response.json() - assert body["items"] == [] + assert body["articles"] == [] assert body["total"] == 0 assert body["page"] == 1 assert body["page_size"] == 20 @@ -133,24 +147,24 @@ class TestListItems: def test_pagination_math_and_contents(self, client, session) -> None: _make_user(session, "root", is_admin=True) - _seed_items(session, 25) + _seed_articles(session, 25) headers = _headers(session, "root") page1 = client.get(BASE, params={"page": 1, "page_size": 10}, headers=headers).json() assert page1["total"] == 25 assert page1["total_pages"] == 3 - assert len(page1["items"]) == 10 + assert len(page1["articles"]) == 10 assert page1["page"] == 1 page2 = client.get(BASE, params={"page": 2, "page_size": 10}, headers=headers).json() - assert len(page2["items"]) == 10 + assert len(page2["articles"]) == 10 # Pages are disjoint. - ids1 = {i["id"] for i in page1["items"]} - ids2 = {i["id"] for i in page2["items"]} + ids1 = {a["id"] for a in page1["articles"]} + ids2 = {a["id"] for a in page2["articles"]} assert ids1.isdisjoint(ids2) page3 = client.get(BASE, params={"page": 3, "page_size": 10}, headers=headers).json() - assert len(page3["items"]) == 5 + assert len(page3["articles"]) == 5 def test_page_size_bounds(self, client, session) -> None: _make_user(session, "root", is_admin=True) @@ -160,33 +174,33 @@ class TestListItems: assert client.get(BASE, params={"page": 0}, headers=headers).status_code == 422 assert client.get(BASE, params={"page_size": 100}, headers=headers).status_code == 200 - def test_search_matches_title_and_url_case_insensitively(self, client, session) -> None: + def test_search_matches_title_and_content_case_insensitively(self, client, session) -> None: _make_user(session, "root", is_admin=True) - _seed_items(session, 5) + _seed_articles(session, 5) headers = _headers(session, "root") by_title = client.get(BASE, params={"search": "STORY 02"}, headers=headers).json() - assert [i["title"] for i in by_title["items"]] == ["Story 02"] + assert [a["title"] for a in by_title["articles"]] == ["Story 02"] - # Seed URLs are https://example.com/story- (no zero padding). - by_url = client.get(BASE, params={"search": "EXAMPLE.COM/STORY-4"}, headers=headers).json() - assert [i["title"] for i in by_url["items"]] == ["Story 04"] + # Bodies are "

Body

" — search inside the HTML content. + by_content = client.get(BASE, params={"search": "BODY 4"}, headers=headers).json() + assert [a["title"] for a in by_content["articles"]] == ["Story 04"] none = client.get(BASE, params={"search": "does-not-exist"}, headers=headers).json() - assert none["items"] == [] + assert none["articles"] == [] assert none["total"] == 0 def test_search_with_sql_metacharacters_is_treated_as_text(self, client, session) -> None: """Search input is a parameterized substring filter, never raw SQL.""" _make_user(session, "root", is_admin=True) - _seed_items(session, 5) + _seed_articles(session, 5) headers = _headers(session, "root") attack = "1=1' OR '1'='1" resp = client.get(BASE, params={"search": attack}, headers=headers) assert resp.status_code == 200 body = resp.json() - assert body["items"] == [] + assert body["articles"] == [] assert body["total"] == 0 # The table is intact after the "attack". @@ -196,47 +210,39 @@ class TestListItems: @pytest.mark.parametrize("order, expected_first", [("asc", "Story 00"), ("desc", "Story 04")]) def test_sort_by_title(self, client, session, order, expected_first) -> None: _make_user(session, "root", is_admin=True) - _seed_items(session, 5) + _seed_articles(session, 5) headers = _headers(session, "root") body = client.get( BASE, params={"sort_by": "title", "sort_order": order}, headers=headers ).json() - assert body["items"][0]["title"] == expected_first - assert [i["title"] for i in body["items"]] == sorted( - (i["title"] for i in body["items"]), reverse=(order == "desc") + assert body["articles"][0]["title"] == expected_first + assert [a["title"] for a in body["articles"]] == sorted( + (a["title"] for a in body["articles"]), reverse=(order == "desc") ) - @pytest.mark.parametrize("order, expected_first_points", [("asc", 0), ("desc", 4)]) - def test_sort_by_points(self, client, session, order, expected_first_points) -> None: - _make_user(session, "root", is_admin=True) - _seed_items(session, 5) - headers = _headers(session, "root") - body = client.get( - BASE, params={"sort_by": "points", "sort_order": order}, headers=headers - ).json() - assert body["items"][0]["points"] == expected_first_points - @pytest.mark.parametrize("order", ["asc", "desc"]) def test_sort_by_created_at(self, client, session, order) -> None: _make_user(session, "root", is_admin=True) - items = _seed_items(session, 5) + articles = _seed_articles(session, 5) # Distinct timestamps so the ordering is deterministic. base = datetime(2025, 1, 1, tzinfo=timezone.utc) - for index, item in enumerate(items): - item.created_at = base + timedelta(minutes=index) + for index, article in enumerate(articles): + article.created_at = base + timedelta(minutes=index) session.commit() headers = _headers(session, "root") body = client.get( BASE, params={"sort_by": "created_at", "sort_order": order}, headers=headers ).json() - stamps = [i["created_at"] for i in body["items"]] + stamps = [a["created_at"] for a in body["articles"]] assert stamps == sorted(stamps, reverse=(order == "desc")) def test_invalid_sort_values_rejected(self, client, session) -> None: _make_user(session, "root", is_admin=True) headers = _headers(session, "root") - assert client.get(BASE, params={"sort_by": "points"}, headers=headers).status_code == 200 + assert client.get(BASE, params={"sort_by": "title"}, headers=headers).status_code == 200 + # "points" was an Item column — it is no longer a valid sort field. + assert client.get(BASE, params={"sort_by": "points"}, headers=headers).status_code == 422 assert ( client.get(BASE, params={"sort_by": "username"}, headers=headers).status_code == 422 ) @@ -244,27 +250,42 @@ class TestListItems: client.get(BASE, params={"sort_order": "up"}, headers=headers).status_code == 422 ) - def test_item_payload_shape(self, client, session) -> None: + def test_article_payload_shape(self, client, session) -> None: + """List entries embed the related author and category.""" _make_user(session, "root", is_admin=True) - _seed_items(session, 1) + author = _make_author(session, name="Amara Osei", email="amara@example.com") + category = _make_category(session, name="Culture", slug="culture") + _seed_articles(session, 1, author=author, category=category) headers = _headers(session, "root") body = client.get(BASE, headers=headers).json() - item = body["items"][0] - assert set(item) == {"id", "title", "url", "points", "username", "content", "created_at"} + article = body["articles"][0] + assert set(article) == { + "id", "title", "content", "author_id", "category_id", + "created_at", "published", "author", "category", + } + assert article["author"] == { + "id": author.id, "name": "Amara Osei", "email": "amara@example.com", "bio": None + } + assert article["category"] == { + "id": category.id, "name": "Culture", "slug": "culture" + } -class TestGetItem: - def test_returns_full_item_including_content(self, client, session) -> None: +class TestGetArticle: + def test_returns_full_article_including_content(self, client, session) -> None: _make_user(session, "root", is_admin=True) - items = _seed_items(session, 1) + author = _make_author(session, name="Jonas Weber", email="jonas@example.com") + category = _make_category(session, name="Science", slug="science") + articles = _seed_articles(session, 1, author=author, category=category) headers = _headers(session, "root") - response = client.get(f"{BASE}/{items[0].id}", headers=headers) + response = client.get(f"{BASE}/{articles[0].id}", headers=headers) assert response.status_code == 200 body = response.json() - assert body["id"] == items[0].id + assert body["id"] == articles[0].id assert body["title"] == "Story 00" assert body["content"] == "

Body 0

" - assert body["username"] == "alice" + assert body["author"]["name"] == "Jonas Weber" + assert body["category"]["slug"] == "science" def test_unknown_id_returns_404(self, client, session) -> None: _make_user(session, "root", is_admin=True) @@ -274,142 +295,255 @@ class TestGetItem: assert response.json()["code"] == "not_found" -class TestCreateItem: - def test_create_with_title_only_uses_defaults(self, client, session) -> None: - _make_user(session, "root", is_admin=True) - headers = _headers(session, "root") - response = client.post(BASE, json={"title": "Fresh news"}, headers=headers) - assert response.status_code == 201 - body = response.json() - assert body["title"] == "Fresh news" - assert body["url"] == "" - assert body["points"] == 0 - assert body["content"] == "" - # The item belongs to the admin that created it. - assert body["username"] == "root" - - def test_create_with_all_fields(self, client, session) -> None: +class TestCreateArticle: + def test_create_defaults_published_false(self, client, session) -> None: _make_user(session, "root", is_admin=True) + author = _make_author(session) + category = _make_category(session) headers = _headers(session, "root") payload = { - "title": " Padded title ", - "url": " https://example.com/story ", - "points": 12, - "username": "bob", - "content": "

Hello world

", + "title": "Fresh news", + "content": "

Hello world.

", + "author_id": author.id, + "category_id": category.id, } response = client.post(BASE, json=payload, headers=headers) assert response.status_code == 201 body = response.json() - # Strings are stripped on the wire. - assert body["title"] == "Padded title" - assert body["url"] == "https://example.com/story" - assert body["points"] == 12 - assert body["username"] == "bob" - assert body["content"] == "

Hello world

" + assert body["title"] == "Fresh news" + assert body["content"] == "

Hello world.

" + assert body["author_id"] == author.id + assert body["category_id"] == category.id + assert body["published"] is False + assert body["created_at"] + + def test_create_with_published_true(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + author = _make_author(session) + category = _make_category(session) + payload = { + "title": "Ready to ship", + "content": "

Live now.

", + "author_id": author.id, + "category_id": category.id, + "published": True, + } + response = client.post(BASE, json=payload, headers=_headers(session, "root")) + assert response.status_code == 201 + assert response.json()["published"] is True @pytest.mark.parametrize( "payload", [ - {}, # missing title + {}, # everything missing + {"title": "t", "content": "

c

"}, # missing author/category + {"title": "t", "author_id": 1, "category_id": 1}, # missing content {"title": ""}, # empty title - {"title": " "}, # blank title - {"title": "x" * 301}, # too long - {"title": "ok", "points": -1}, # negative points - {"title": "ok", "url": "not-a-url"}, # invalid URL - {"title": "ok", "url": "ftp://example.com/x"}, # wrong scheme - {"title": "ok", "url": "https://"}, # missing host - {"title": "ok", "url": "x" * 501}, # too long - {"title": "ok", "points": 1.5}, # not an integer - {"title": "ok", "username": ""}, # empty username + {"title": "x" * 201}, # too long + {"title": "t", "content": "

c

", "author_id": 0}, # invalid ids ], ) def test_validation_failures_return_422(self, client, session, payload) -> None: _make_user(session, "root", is_admin=True) - headers = _headers(session, "root") - response = client.post(BASE, json=payload, headers=headers) + response = client.post(BASE, json=payload, headers=_headers(session, "root")) assert response.status_code == 422 assert response.json()["code"] == "validation_error" + def test_unknown_author_returns_422(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + category = _make_category(session) + payload = { + "title": "Orphan author", + "content": "

x

", + "author_id": 9999, + "category_id": category.id, + } + response = client.post(BASE, json=payload, headers=_headers(session, "root")) + assert response.status_code == 422 + assert response.json()["detail"] == "Author 9999 not found" -class TestUpdateItem: + def test_unknown_category_returns_422(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + author = _make_author(session) + payload = { + "title": "Orphan category", + "content": "

x

", + "author_id": author.id, + "category_id": 9999, + } + response = client.post(BASE, json=payload, headers=_headers(session, "root")) + assert response.status_code == 422 + assert response.json()["detail"] == "Category 9999 not found" + + def test_duplicate_title_returns_409(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + author = _make_author(session) + category = _make_category(session) + _seed_articles(session, 1, author=author, category=category) + payload = { + "title": "Story 00", + "content": "

another body

", + "author_id": author.id, + "category_id": category.id, + } + response = client.post(BASE, json=payload, headers=_headers(session, "root")) + assert response.status_code == 409 + assert response.json()["code"] == "conflict" + + +class TestUpdateArticle: def test_partial_update_changes_only_provided_fields(self, client, session) -> None: _make_user(session, "root", is_admin=True) - items = _seed_items(session, 1) + articles = _seed_articles(session, 1) headers = _headers(session, "root") response = client.put( - f"{BASE}/{items[0].id}", json={"points": 99}, headers=headers + f"{BASE}/{articles[0].id}", json={"published": False}, headers=headers ) assert response.status_code == 200 body = response.json() - assert body["points"] == 99 + assert body["published"] is False # Untouched fields keep their values. assert body["title"] == "Story 00" - assert body["url"] == "https://example.com/story-0" assert body["content"] == "

Body 0

" def test_full_update(self, client, session) -> None: _make_user(session, "root", is_admin=True) - items = _seed_items(session, 1) - headers = _headers(session, "root") + author = _make_author(session, name="Old Byline", email="old@example.com") + category = _make_category(session, name="Old Cat", slug="old-cat") + articles = _seed_articles(session, 1, author=author, category=category) + new_author = _make_author(session, name="New Byline", email="new@example.com") + new_category = _make_category(session, name="New Cat", slug="new-cat") payload = { "title": "Retitled", - "url": "https://example.com/new", - "points": 7, - "username": "carol", "content": "

Updated

", + "author_id": new_author.id, + "category_id": new_category.id, + "published": False, } - response = client.put(f"{BASE}/{items[0].id}", json=payload, headers=headers) + response = client.put( + f"{BASE}/{articles[0].id}", json=payload, headers=_headers(session, "root") + ) assert response.status_code == 200 body = response.json() - assert body == {**body, **payload, "id": items[0].id} + assert body["title"] == "Retitled" + assert body["content"] == "

Updated

" + assert body["author_id"] == new_author.id + assert body["category_id"] == new_category.id + assert body["published"] is False + assert body["author"]["name"] == "New Byline" def test_unknown_id_returns_404(self, client, session) -> None: _make_user(session, "root", is_admin=True) - headers = _headers(session, "root") - response = client.put(f"{BASE}/9999", json={"title": "x"}, headers=headers) + response = client.put(f"{BASE}/9999", json={"title": "x"}, headers=_headers(session, "root")) assert response.status_code == 404 def test_invalid_payload_returns_422(self, client, session) -> None: _make_user(session, "root", is_admin=True) - items = _seed_items(session, 1) - headers = _headers(session, "root") + articles = _seed_articles(session, 1) response = client.put( - f"{BASE}/{items[0].id}", json={"title": "", "points": -3}, headers=headers + f"{BASE}/{articles[0].id}", + json={"title": "", "author_id": -3}, + headers=_headers(session, "root"), ) assert response.status_code == 422 def test_empty_payload_is_a_no_op(self, client, session) -> None: _make_user(session, "root", is_admin=True) - items = _seed_items(session, 1) - headers = _headers(session, "root") - response = client.put(f"{BASE}/{items[0].id}", json={}, headers=headers) + articles = _seed_articles(session, 1) + response = client.put(f"{BASE}/{articles[0].id}", json={}, headers=_headers(session, "root")) assert response.status_code == 200 assert response.json()["title"] == "Story 00" - -class TestDeleteItem: - def test_delete_removes_the_item(self, client, session) -> None: + def test_title_collision_returns_409(self, client, session) -> None: _make_user(session, "root", is_admin=True) - items = _seed_items(session, 1) - headers = _headers(session, "root") - item_id = items[0].id + articles = _seed_articles(session, 2) + response = client.put( + f"{BASE}/{articles[1].id}", + json={"title": "Story 00"}, + headers=_headers(session, "root"), + ) + assert response.status_code == 409 - response = client.delete(f"{BASE}/{item_id}", headers=headers) + def test_update_to_unknown_author_returns_422(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + articles = _seed_articles(session, 1) + response = client.put( + f"{BASE}/{articles[0].id}", + json={"author_id": 9999}, + headers=_headers(session, "root"), + ) + assert response.status_code == 422 + assert response.json()["detail"] == "Author 9999 not found" + + def test_update_to_unknown_category_returns_422(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + articles = _seed_articles(session, 1) + response = client.put( + f"{BASE}/{articles[0].id}", + json={"category_id": 9999}, + headers=_headers(session, "root"), + ) + assert response.status_code == 422 + assert response.json()["detail"] == "Category 9999 not found" + + +class TestDeleteArticle: + def test_delete_removes_the_article(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + articles = _seed_articles(session, 1) + headers = _headers(session, "root") + article_id = articles[0].id + + response = client.delete(f"{BASE}/{article_id}", headers=headers) assert response.status_code == 204 assert response.content == b"" - assert client.get(f"{BASE}/{item_id}", headers=headers).status_code == 404 - assert session.query(Item).filter(Item.id == item_id).first() is None + assert client.get(f"{BASE}/{article_id}", headers=headers).status_code == 404 + assert session.query(Article).filter(Article.id == article_id).first() is None def test_delete_unknown_id_returns_404(self, client, session) -> None: _make_user(session, "root", is_admin=True) - headers = _headers(session, "root") - response = client.delete(f"{BASE}/9999", headers=headers) + response = client.delete(f"{BASE}/9999", headers=_headers(session, "root")) assert response.status_code == 404 +class TestReferenceData: + def test_list_authors_ordered_by_name(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + zed = _make_author(session, name="Zed Last", email="zed@example.com") + amy = _make_author(session, name="Amy First", email="amy@example.com") + response = client.get("/api/v1/admin/authors", headers=_headers(session, "root")) + assert response.status_code == 200 + body = response.json() + assert [a["id"] for a in body] == [amy.id, zed.id] + assert body[0] == { + "id": amy.id, "name": "Amy First", "email": "amy@example.com", "bio": None + } + + def test_list_authors_empty(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + response = client.get("/api/v1/admin/authors", headers=_headers(session, "root")) + assert response.status_code == 200 + assert response.json() == [] + + def test_list_categories_ordered_by_name(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + world = _make_category(session, name="World", slug="world") + tech = _make_category(session, name="Technology", slug="technology") + response = client.get("/api/v1/admin/categories", headers=_headers(session, "root")) + assert response.status_code == 200 + body = response.json() + assert [c["id"] for c in body] == [tech.id, world.id] + assert body[0] == {"id": tech.id, "name": "Technology", "slug": "technology"} + + def test_list_categories_empty(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + response = client.get("/api/v1/admin/categories", headers=_headers(session, "root")) + assert response.status_code == 200 + assert response.json() == [] + + class TestStartupMigration: """Pre-M6 databases (users table without is_admin) get the column.""" @@ -456,7 +590,7 @@ class TestStartupMigration: class TestSeedAdminScript: - def test_creates_admin_user(self, session, monkeypatch, tmp_path, capsys) -> None: + def test_creates_admin_user(self, session, monkeypatch, capsys) -> None: import seed_admin monkeypatch.setenv("ADMIN_USERNAME", "root") @@ -517,3 +651,21 @@ class TestRateLimiting: finally: admin_api._limiter.limit = 1000 admin_api._limiter._hits.clear() + + def test_budget_is_per_admin(self, client, session, monkeypatch) -> None: + """One admin exhausting the budget does not block another admin.""" + _make_user(session, "root", is_admin=True) + _make_user(session, "other", is_admin=True) + admin_api._limiter._hits.clear() + monkeypatch.setattr(admin_api._limiter, "limit", 1) + monkeypatch.setattr(admin_api._limiter, "window_seconds", 60.0) + try: + root = _headers(session, "root") + other = _headers(session, "other") + assert client.get(BASE, headers=root).status_code == 200 + assert client.get(BASE, headers=root).status_code == 429 + # "other" still has its own budget. + assert client.get(BASE, headers=other).status_code == 200 + finally: + admin_api._limiter.limit = 1000 + admin_api._limiter._hits.clear() diff --git a/backend/tests/test_articles.py b/backend/tests/test_articles.py new file mode 100644 index 0000000..bd94577 --- /dev/null +++ b/backend/tests/test_articles.py @@ -0,0 +1,176 @@ +"""Tests for the public article read API (``/api/v1/articles``). + +These endpoints power the site front end. They require no authentication, +expose *published* articles only, and embed the related author/category so +the front page can render full details from a single payload. +""" + +from datetime import datetime, timedelta, timezone + +from models import Article, Author, Category + +BASE = "/api/v1/articles" + + +def _make_author(session, name="Byline Writer", email="writer@example.com") -> Author: + author = Author(name=name, email=email) + session.add(author) + session.commit() + return author + + +def _make_category(session, name="Technology", slug="technology") -> Category: + category = Category(name=name, slug=slug) + session.add(category) + session.commit() + return category + + +def _make_article( + session, + title, + author, + category, + published=True, + created_at=None, +) -> Article: + article = Article( + title=title, + content=f"

Body for {title}

", + author_id=author.id, + category_id=category.id, + published=published, + created_at=created_at or datetime.now(timezone.utc), + ) + session.add(article) + session.commit() + session.refresh(article) + return article + + +class TestListPublishedArticles: + def test_requires_no_authentication(self, client, session) -> None: + author = _make_author(session) + category = _make_category(session) + _make_article(session, "Public story", author, category) + response = client.get(BASE) + assert response.status_code == 200 + + def test_returns_only_published_newest_first(self, client, session) -> None: + author = _make_author(session) + category = _make_category(session) + base = datetime(2025, 1, 1, tzinfo=timezone.utc) + old = _make_article(session, "Old published", author, category, created_at=base) + new = _make_article( + session, "New published", author, category, created_at=base + timedelta(days=2) + ) + draft = _make_article( + session, "Still a draft", author, category, published=False, + created_at=base + timedelta(days=3), + ) + response = client.get(BASE) + assert response.status_code == 200 + body = response.json() + assert [a["title"] for a in body] == ["New published", "Old published"] + assert all(a["published"] is True for a in body) + assert draft.id not in {a["id"] for a in body} + + def test_entry_embeds_author_and_category(self, client, session) -> None: + author = _make_author(session, name="Amara Osei", email="amara@example.com") + category = _make_category(session, name="Culture", slug="culture") + article = _make_article(session, "Gallery nights", author, category) + body = client.get(BASE).json() + entry = body[0] + assert entry["id"] == article.id + assert entry["content"] == f"

Body for {article.title}

" + assert entry["author"] == { + "id": author.id, "name": "Amara Osei", "email": "amara@example.com", "bio": None + } + assert entry["category"] == {"id": category.id, "name": "Culture", "slug": "culture"} + + def test_empty_when_nothing_published(self, client, session) -> None: + author = _make_author(session) + category = _make_category(session) + _make_article(session, "Only a draft", author, category, published=False) + assert client.get(BASE).json() == [] + + +class TestGetPublishedArticle: + def test_returns_published_article(self, client, session) -> None: + author = _make_author(session) + category = _make_category(session) + article = _make_article(session, "The one", author, category) + response = client.get(f"{BASE}/{article.id}") + assert response.status_code == 200 + body = response.json() + assert body["id"] == article.id + assert body["title"] == "The one" + assert body["author"]["id"] == author.id + assert body["category"]["id"] == category.id + + def test_draft_returns_404(self, client, session) -> None: + author = _make_author(session) + category = _make_category(session) + draft = _make_article(session, "Hidden", author, category, published=False) + response = client.get(f"{BASE}/{draft.id}") + assert response.status_code == 404 + assert response.json()["code"] == "not_found" + + def test_unknown_id_returns_404(self, client, session) -> None: + response = client.get(f"{BASE}/9999") + assert response.status_code == 404 + assert response.json()["code"] == "not_found" + + +class TestSeedContentScript: + """The seeder creates the demo authors/categories/articles, idempotently.""" + + def _run_seed(self, session, monkeypatch) -> str: + import seed_content + + monkeypatch.setattr(seed_content, "SessionLocal", lambda: session) + assert seed_content.main() == 0 + captured = __import__("io").StringIO() + return captured.getvalue() + + def test_creates_demo_content(self, session, monkeypatch, capsys) -> None: + import seed_content + + monkeypatch.setattr(seed_content, "SessionLocal", lambda: session) + assert seed_content.main() == 0 + out = capsys.readouterr().out + + assert session.query(Author).count() == 3 + assert session.query(Category).count() == 4 + articles = session.query(Article).all() + assert len(articles) == 6 + assert all(a.published is True for a in articles) + # The feed is newest-first and every article resolves its relations. + titles = [a.title for a in articles] + assert titles[0] == "Inside the new wave of open-source language models" + for article in articles: + assert article.author.name + assert article.category.slug + assert "Created author 'Ada Lovelace'" in out + assert "Done." in out + + def test_is_idempotent(self, session, monkeypatch, capsys) -> None: + import seed_content + + monkeypatch.setattr(seed_content, "SessionLocal", lambda: session) + assert seed_content.main() == 0 + capsys.readouterr() + + # Capture the id (plain int) — main() closes the shared session, + # detaching ORM instances. + first_article_id = session.query(Article).first().id + assert seed_content.main() == 0 + out = capsys.readouterr().out + + # No duplicates on the second run; nothing was re-created. + assert session.query(Author).count() == 3 + assert session.query(Category).count() == 4 + assert session.query(Article).count() == 6 + assert session.query(Article).first().id == first_article_id + assert "Created author" not in out + assert "Created article" not in out diff --git a/backend/tests/test_models.py b/backend/tests/test_models.py index 7f37ad8..617442a 100644 --- a/backend/tests/test_models.py +++ b/backend/tests/test_models.py @@ -3,7 +3,7 @@ import pytest from sqlalchemy.exc import IntegrityError -from models import Article, Author, Category, Item, User, slugify +from models import Article, Author, Category, User, slugify class TestAuthor: @@ -162,34 +162,3 @@ class TestArticle: with pytest.raises(IntegrityError): session.commit() session.rollback() - - -class TestItem: - def test_create_and_commit_defaults(self, session) -> None: - item = Item(title="Breaking: things happen") - session.add(item) - session.commit() - session.refresh(item) - assert item.id is not None - assert item.url == "" - assert item.points == 0 - assert item.username == "anonymous" - assert item.content == "" - assert item.created_at is not None - - def test_create_with_all_fields(self, session) -> None: - item = Item( - title="Show HN: a new tool", - url="https://example.com/show-hn", - points=42, - username="alice", - content="

Hello world

", - ) - session.add(item) - session.commit() - session.refresh(item) - assert item.title == "Show HN: a new tool" - assert item.url == "https://example.com/show-hn" - assert item.points == 42 - assert item.username == "alice" - assert item.content == "

Hello world

" diff --git a/frontend/playwright/e2e/admin.spec.ts b/frontend/playwright/e2e/admin.spec.ts index 853c3e6..7a37329 100644 --- a/frontend/playwright/e2e/admin.spec.ts +++ b/frontend/playwright/e2e/admin.spec.ts @@ -1,421 +1,547 @@ -import { expect, test, type Page } from '@playwright/test'; +import { expect, test } 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. + * E2E tests for the admin area (M6). The Vite dev-server proxy is + * intercepted with page.route, so these tests run without a backend. + * + * The admin area manages the article domain: + * - list/search/sort/paginate articles (GET /api/v1/admin/articles) + * - create articles (POST /api/v1/admin/articles) with a Lexical editor + * - edit articles (PUT /api/v1/admin/articles/:id) + * - delete articles (DELETE /api/v1/admin/articles/:id) + * - reference data: GET /api/v1/admin/authors, /api/v1/admin/categories */ -const ADMIN_TOKEN = 'mock-admin-token'; -const USER_TOKEN = 'mock-user-token'; -const TOKEN_KEY = 'AUTH_TOKEN'; - -interface Item { +type WireAuthor = { id: number; name: string; email: string; bio: string | null }; +type WireCategory = { id: number; name: string; slug: string }; +type WireArticle = { id: number; title: string; - url: string; - points: number; - username: string; content: string; + author_id: number; + category_id: number; created_at: string; -} + published: boolean; + author: WireAuthor; + category: WireCategory; +}; -const envelope = (detail: string, code: string) => JSON.stringify({ detail, code }); +const AUTHORS: WireAuthor[] = [ + { id: 1, name: 'Ada Lovelace', email: 'ada@example.com', bio: null }, + { id: 2, name: 'Grace Hopper', email: 'grace@example.com', bio: null }, + { id: 3, name: 'Alan Turing', email: 'alan@example.com', bio: null }, +]; +const CATEGORIES: WireCategory[] = [ + { id: 1, name: 'Technology', slug: 'technology' }, + { id: 2, name: 'Science', slug: 'science' }, + { id: 3, name: 'Sports', slug: 'sports' }, + { id: 4, name: 'Culture', slug: 'culture' }, +]; -/** 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[] = [ +function seedArticles(): WireArticle[] { + return [ { id: 1, - title: 'Breaking: local cat discovers keyboard', - url: 'https://example.com/cat-keyboard', - points: 42, - username: 'alice', - content: '

Amazing news.

', - created_at: '2024-05-01T10:00:00Z', + title: 'Fusion milestone: net energy gain repeated', + content: + '

Scientists again drew net energy from the reactor, marking the third repeat of the landmark result.

', + author_id: 2, + category_id: 2, + created_at: '2024-05-03T11:30:00Z', + published: true, + author: AUTHORS[1], + category: CATEGORIES[1], }, { id: 2, - title: 'Study: coffee improves code reviews', - url: 'https://example.com/coffee-reviews', - points: 17, - username: 'bob', - content: '

Peer-reviewed.

', - created_at: '2024-05-02T11:30:00Z', + title: 'City marathon sets record turnout', + content: + '

First-timers flooded the course on Sunday as organizers beat last year\u2019s turnout.

', + author_id: 3, + category_id: 3, + created_at: '2024-05-02T09:15:00Z', + published: false, + author: AUTHORS[2], + category: CATEGORIES[2], }, { id: 3, - title: 'Show HN: I built a tiny news app', - url: 'https://example.com/show-hn-newz', - points: 5, - username: 'alice', - content: '

Feedback welcome.

', - created_at: '2024-05-03T09:15:00Z', + title: 'Inside the new wave of open-source language models', + content: + '

Open-weight language models are reshaping who can build and deploy AI.

', + author_id: 1, + category_id: 1, + created_at: '2024-05-01T10:00:00Z', + published: true, + author: AUTHORS[0], + category: CATEGORIES[0], }, ]; +} - const requireAdmin = (route: Parameters[1]>[0]): boolean => { - const header = route.request().headers()['authorization']; - if (header !== `Bearer ${ADMIN_TOKEN}`) { - route.fulfill({ - status: 403, +async function mockAdminApi( + page: import('@playwright/test').Page, + opts: { admin?: boolean; token?: string; signedOut?: boolean } = {}, +) { + const store = seedArticles(); + const nextId = { value: 100 }; + const token = opts.token ?? (opts.admin === false ? 'user-token' : 'admin-token'); + + await page.route('**/api/v1/auth/me', async (route) => { + if (opts.signedOut) { + return route.fulfill({ + status: 401, contentType: 'application/json', - body: envelope('Admin access required', 'forbidden'), + body: JSON.stringify({ detail: 'Not authenticated', code: 'unauthorized' }), }); - return false; } - return true; - }; - - page.route('**/api/v1/auth/me', (route) => { - const header = route.request().headers()['authorization']; - if (header === `Bearer ${ADMIN_TOKEN}`) { + if (opts.admin === false) { 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 }), + body: JSON.stringify({ id: 2, username: 'user', is_admin: false }), }); } return route.fulfill({ - status: 401, + status: 200, contentType: 'application/json', - body: envelope('Invalid or expired token', 'unauthorized'), + body: JSON.stringify({ id: 1, username: 'admin', is_admin: true }), }); }); - 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()); + await page.route('**/api/v1/auth/logout', async (route) => + route.fulfill({ + status: 204, + contentType: 'application/json', + body: JSON.stringify({}), + }), + ); + + await page.route('**/api/v1/admin/authors', async (route) => { + if (opts.admin === false) { + return route.fulfill({ + status: 403, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Admin access required', code: 'forbidden' }), + }); + } + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(AUTHORS), + }); + }); + + await page.route('**/api/v1/admin/categories', async (route) => { + if (opts.admin === false) { + return route.fulfill({ + status: 403, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Admin access required', code: 'forbidden' }), + }); + } + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(CATEGORIES), + }); + }); + + await page.route('**/api/v1/admin/articles**', async (route) => { + const url = new URL(route.request().url()); + const idMatch = url.pathname.match(/\/api\/v1\/admin\/articles\/(\d+)/); + + if (idMatch) { + const id = Number(idMatch[1]); + const article = store.find((a) => a.id === id); + const method = route.request().method(); + if (method === 'GET') { + if (!article) { + return route.fulfill({ + status: 404, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }), + }); + } + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(article), + }); + } + if (method === 'PUT') { + if (!article) { + return route.fulfill({ + status: 404, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }), + }); + } + const body = JSON.parse(route.request().postData() ?? '{}') as { + title: string; + content: string; + author_id: number; + category_id: number; + published: boolean; + }; + Object.assign(article, { + title: body.title, + content: body.content, + author_id: body.author_id, + category_id: body.category_id, + published: body.published, + }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(article), + }); + } + if (method === 'DELETE') { + if (!article) { + return route.fulfill({ + status: 404, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }), + }); + } + const index = store.indexOf(article); + if (index >= 0) store.splice(index, 1); + return route.fulfill({ status: 204, body: '' }); + } + return route.fulfill({ + status: 405, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Method not allowed', code: 'method_not_allowed' }), + }); + } + + const method = route.request().method(); + if (method === 'GET') { const search = (url.searchParams.get('search') ?? '').toLowerCase(); - const sortBy = (url.searchParams.get('sort_by') ?? 'created_at') as keyof Item; + const sortBy = url.searchParams.get('sort_by') ?? 'created_at'; 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 page = Number(url.searchParams.get('page') ?? '1'); + const pageSize = Number(url.searchParams.get('page_size') ?? '20'); const filtered = store.filter( - (item) => - !search || - item.title.toLowerCase().includes(search) || - item.url.toLowerCase().includes(search), + (a) => !search || a.title.toLowerCase().includes(search) || a.content.toLowerCase().includes(search), ); + const direction = sortOrder === 'asc' ? 1 : -1; filtered.sort((a, b) => { - const cmp = String(a[sortBy]).localeCompare(String(b[sortBy])); - return sortOrder === 'asc' ? cmp : -cmp; + if (sortBy === 'title') { + return a.title.localeCompare(b.title) * direction; + } + return a.created_at.localeCompare(b.created_at) * direction; }); - const start = (page_ - 1) * pageSize; + 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, + articles: slice, total: filtered.length, - page: page_, + page, page_size: pageSize, - total_pages: Math.ceil(filtered.length / pageSize) || 0, + total_pages: Math.max(1, Math.ceil(filtered.length / pageSize)), }), }); } - if (request.method() === 'POST') { - if (!requireAdmin(route)) return; - const body = request.postDataJSON() as Partial; - 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(), + + if (method === 'POST') { + const body = JSON.parse(route.request().postData() ?? '{}') as { + title: string; + content: string; + author_id: number; + category_id: number; + published: boolean; }; - store.push(item); + const article: WireArticle = { + id: nextId.value++, + title: body.title, + content: body.content, + author_id: body.author_id, + category_id: body.category_id, + created_at: new Date().toISOString(), + published: body.published, + author: AUTHORS.find((a) => a.id === body.author_id) ?? AUTHORS[0], + category: CATEGORIES.find((c) => c.id === body.category_id) ?? CATEGORIES[0], + }; + store.push(article); return route.fulfill({ status: 201, contentType: 'application/json', - body: JSON.stringify(item), + body: JSON.stringify(article), }); } - return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') }); + + return route.fulfill({ + status: 405, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Method not allowed', code: '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; - 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 }; + return { + store, + token, + count: () => store.length, + all: () => store.map((a) => a.id).sort((a, b) => a - b), + byId: (id: number) => store.find((a) => a.id === id), + }; } -async function seedToken(page: Page, token: string | null): Promise { - 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); - +test.describe('Admin area (E2E)', () => { + test('redirects signed-out users to /login', async ({ page }) => { + await mockAdminApi(page, { signedOut: true }); + // No token in storage: RequireAuth redirects to /login (the intended + // path is remembered in router state, not a query parameter). 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); - + test('redirects non-admin users away with a 403 message', async ({ page }) => { + const { token } = await mockAdminApi(page, { admin: false, token: 'user-token' }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + token, + ); await page.goto('/admin'); - + // RequireAdmin shows the 403 page in place (no redirect). await expect(page.getByRole('heading', { level: 1, name: '403' })).toBeVisible(); await expect( - page.getByTestId('forbidden-page').getByText(/admin area/i), + page.getByText(/does not have access to the admin area/i), ).toBeVisible(); + await expect(page).toHaveURL('/admin'); }); - test('admins see the dashboard with all items and an Admin header link', async ({ + test('renders the admin dashboard with all articles and the 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(); + const { token, count } = await mockAdminApi(page, { admin: true }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + token, + ); 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(); + // Dashboard heading + rows. + await expect(page.getByRole('heading', { level: 1, name: 'Articles' })).toBeVisible(); + await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible(); + await expect(page.getByText('City marathon sets record turnout')).toBeVisible(); + await expect(page.getByText('Inside the new wave of open-source language models')).toBeVisible(); + // Author and category columns. + await expect(page.getByText('Grace Hopper')).toBeVisible(); + await expect(page.getByText('Technology')).toBeVisible(); + // Pagination summary. await expect(page.getByText('Showing 1–3 of 3')).toBeVisible(); + // The admin shell shows the signed-in admin and a link back to the public site. + await expect(page.getByText('Signed in as')).toBeVisible(); + await expect(page.getByRole('link', { name: /back to newzy/i })).toBeVisible(); + expect(count()).toBe(3); }); - test('non-admin accounts do not get the Admin header link', async ({ page }) => { - mockAdminApi(page); - await seedToken(page, USER_TOKEN); - + test('hides the Admin header link for non-admins', async ({ page }) => { + const { token } = await mockAdminApi(page, { admin: false, token: 'user-token' }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + token, + ); await page.goto('/'); - - await expect( - page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i }), - ).toHaveCount(0); + await page.waitForTimeout(200); + await expect(page.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); - + test('search filters articles by title or content', async ({ page }) => { + const { token } = await mockAdminApi(page, { admin: true }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + token, + ); await page.goto('/admin'); - await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible(); + await expect(page.getByText('Fusion milestone: net energy gain repeated')).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(); + // Title match. + const search = page.getByLabel('Search articles'); + await search.fill('fusion'); + await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible(); + await expect(page.getByText('City marathon sets record turnout')).toHaveCount(0); + await expect(page.getByText('Inside the new wave of open-source language models')).toHaveCount(0); await expect(page.getByText('Showing 1–1 of 1')).toBeVisible(); + + // Content match. + await search.fill('course'); + await expect(page.getByText('City marathon sets record turnout')).toBeVisible(); + await expect(page.getByText('Fusion milestone: net energy gain repeated')).toHaveCount(0); }); - test('sorting by title toggles direction', async ({ page }) => { - mockAdminApi(page); - await seedToken(page, ADMIN_TOKEN); - + test('sorts by title in both directions', async ({ page }) => { + const { token } = await mockAdminApi(page, { admin: true }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + 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'); + const firstCell = () => page.locator('tbody tr').first().locator('td').first(); + const titleButton = page.getByRole('button', { name: /sort by title/i }); - await page.getByRole('button', { name: /sort by title/i }).click(); - await expect(firstTitle).toHaveText('Breaking: local cat discovers keyboard'); + // Default ordering is newest first (created_at desc). + await expect(firstCell()).toContainText('Fusion milestone: net energy gain repeated'); - await page.getByRole('button', { name: /sort by title/i }).click(); - await expect(firstTitle).toHaveText('Study: coffee improves code reviews'); + // Click title → ascending: City… is first. + await titleButton.click(); + await expect(firstCell()).toContainText('City marathon sets record turnout'); + + // Click again → descending: Inside… is first. + await titleButton.click(); + await expect(firstCell()).toContainText('Inside the new wave of open-source language models'); }); - test('create: fills the form, saves with the Lexical editor and lists the item', async ({ + test('creates an article with the Lexical editor and navigates back', async ({ page, }) => { - const { store } = mockAdminApi(page); - await seedToken(page, ADMIN_TOKEN); + const { token, byId, all } = await mockAdminApi(page, { admin: true }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + token, + ); + await page.goto('/admin/articles/new'); - await page.goto('/admin/items/new'); - await expect(page.getByRole('heading', { level: 1, name: 'New item' })).toBeVisible(); + await expect( + page.getByRole('heading', { level: 1, name: 'New article' }), + ).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.getByLabel(/^Author/).selectOption('2'); + await page.getByLabel(/^Category/).selectOption('4'); + await page.getByLabel(/^Published/).check(); + const editable = page.getByLabel('Article content'); + await editable.click(); await page.keyboard.type('Written with the Lexical editor.'); + await page.getByRole('button', { name: /create article/i }).click(); - await page.getByRole('button', { name: /create item/i }).click(); + await page.waitForURL('/admin'); + await expect(page.getByRole('status')).toContainText('was saved'); + // Exact match: the success notice also quotes the title. + await expect( + page.getByText('E2E: fresh story from the admin area', { exact: true }), + ).toBeVisible(); - // 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(); + const created = byId(Math.max(...all())); + expect(created?.title).toBe('E2E: fresh story from the admin area'); + expect(created?.author_id).toBe(2); + expect(created?.category_id).toBe(4); + expect(created?.published).toBe(true); 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); - + test('edits an article and persists the changes', async ({ page }) => { + const { token, byId } = await mockAdminApi(page, { admin: true }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + 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'); - // The stored body loads into the WYSIWYG editor. - await expect(page.getByLabel('Item content')).toContainText('Amazing news.'); + await page + .getByRole('row', { name: /Fusion milestone: net energy gain repeated/ }) + .getByRole('link', { name: /edit/i }) + .click(); - await page.getByLabel(/^Title/).fill('Breaking: local cat becomes famous'); + await expect(page).toHaveURL(/\/admin\/articles\/1\/edit$/); + await expect( + page.getByRole('heading', { level: 1, name: /edit article/i }), + ).toBeVisible(); + + const titleInput = page.getByLabel(/^Title/); + await expect(titleInput).toHaveValue('Fusion milestone: net energy gain repeated'); + const editable = page.getByLabel('Article content'); + await expect(editable).toContainText('Scientists again drew net energy'); + + await titleInput.fill('Fusion milestone: record energy gain'); 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(); + await page.waitForURL('/admin'); + await expect(page.getByRole('status')).toContainText('was saved'); + // Exact match: the success notice also quotes the title. + await expect( + page.getByText('Fusion milestone: record energy gain', { 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); + expect(byId(1)?.title).toBe('Fusion milestone: record energy gain'); + expect(byId(1)?.published).toBe(true); + expect(byId(1)?.author_id).toBe(2); }); - test('delete: requires confirmation, then removes the item', async ({ page }) => { - const { store } = mockAdminApi(page); - await seedToken(page, ADMIN_TOKEN); - + test('deletes an article only after explicit confirmation', async ({ page }) => { + const { token, count, all } = await mockAdminApi(page, { admin: true }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + 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 targetRow = page.getByRole('row', { + name: /City marathon sets record turnout/, + }); + await targetRow.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(); + await expect(dialog).toContainText('City marathon sets record turnout'); + await expect(dialog).toContainText(/cannot be undone/i); - // Cancel keeps the item. + // Cancel: nothing is deleted. await dialog.getByRole('button', { name: /cancel/i }).click(); await expect(dialog).toHaveCount(0); - await expect(target).toBeVisible(); - expect(store).toHaveLength(3); + expect(count()).toBe(3); + expect(all()).toEqual([1, 2, 3]); - // Confirm with the explicit "Yes, delete" action. - page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click(); + // Confirm: the article is removed. + await targetRow.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); + await expect(page.getByRole('status')).toContainText('was deleted'); + // The row is gone (the success notice still quotes the title). + await expect( + page.getByRole('row', { name: /City marathon sets record turnout/ }), + ).toHaveCount(0); + expect(count()).toBe(2); + expect(all()).toEqual([1, 3]); }); - 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'); - }); - - test('editor sanitizes hostile stored HTML (no scripts or handlers survive)', async ({ + test('pagination controls stay disabled with a single page', async ({ page, }) => { - const { store } = mockAdminApi(page); - await seedToken(page, ADMIN_TOKEN); + const { token } = await mockAdminApi(page, { admin: true }); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + token, + ); + await page.goto('/admin'); + await expect(page.getByText('Showing 1–3 of 3')).toBeVisible(); - // Simulate a hostile item body persisted by the backend. - store[0].content = [ + await expect(page.getByRole('button', { name: /previous/i })).toBeDisabled(); + await expect(page.getByRole('button', { name: /next/i })).toBeDisabled(); + + // The page size control round-trips without moving pages. + const perPage = page.getByLabel('Rows per page'); + await perPage.selectOption('50'); + await perPage.selectOption('20'); + await expect(page.getByText('Showing 1–3 of 3')).toBeVisible(); + }); + + test('editor sanitizes hostile HTML from stored content', async ({ page }) => { + const mock = await mockAdminApi(page, { admin: true }); + // Simulate a hostile article body persisted by the backend. + mock.store[0].content = [ '

Safe text

', '', '', @@ -431,12 +557,18 @@ test.describe('admin area (M6)', () => { }); page.on('pageerror', (error) => pageErrors.push(error.message)); - await page.goto('/admin/items/1/edit'); + await page.addInitScript( + (value) => localStorage.setItem('AUTH_TOKEN', value), + mock.token, + ); + await page.goto('/admin/articles/1/edit'); - const editable = page.getByLabel('Item content'); + const editable = page.getByLabel('Article content'); await expect(editable).toContainText('Safe'); - const html = await editable.evaluate((el) => el.innerHTML); + const html = await editable.evaluate( + (el) => (el as HTMLElement).innerHTML, + ); expect(html).not.toContain(' } /> - } /> - } /> + } /> + } /> {/* Public site */} diff --git a/frontend/src/api/admin.ts b/frontend/src/api/admin.ts index e030aa4..32d7efd 100644 --- a/frontend/src/api/admin.ts +++ b/frontend/src/api/admin.ts @@ -1,5 +1,5 @@ /** - * Admin API client (item CRUD, admin-only endpoints). + * Admin API client (article CRUD, admin-only endpoints). * * Built on the shared fetch wrapper from `api/client.ts`, which attaches * the JWT session token to every request. All endpoints require the @@ -7,40 +7,56 @@ * `api/v1/admin.py`). */ import { api } from './client'; +import type { Author, Category } from '../types'; import type { - AdminItem, - AdminItemInput, - AdminItemsPage, + AdminArticle, + AdminArticleInput, + AdminArticlesPage, AdminListParams, } from '../types/admin'; -/** `GET /api/v1/admin/items` — paginated, searchable, sortable list. */ -export function adminListItems(params: AdminListParams): Promise { +/** `GET /api/v1/admin/articles` — paginated, searchable, sortable list. */ +export function adminListArticles( + params: AdminListParams, +): Promise { const query = new URLSearchParams(); query.set('page', String(params.page)); query.set('page_size', String(params.pageSize)); if (params.search.trim()) query.set('search', params.search.trim()); query.set('sort_by', params.sortBy); query.set('sort_order', params.sortOrder); - return api.get(`/admin/items?${query.toString()}`); + return api.get(`/admin/articles?${query.toString()}`); } -/** `GET /api/v1/admin/items/{id}` — a single item (including content). */ -export function adminGetItem(id: number): Promise { - return api.get(`/admin/items/${id}`); +/** `GET /api/v1/admin/articles/{id}` — a single article (with author + category). */ +export function adminGetArticle(id: number): Promise { + return api.get(`/admin/articles/${id}`); } -/** `POST /api/v1/admin/items` — create a new item. */ -export function adminCreateItem(input: AdminItemInput): Promise { - return api.post('/admin/items', input); +/** `POST /api/v1/admin/articles` — create a new article. */ +export function adminCreateArticle(input: AdminArticleInput): Promise { + return api.post('/admin/articles', input); } -/** `PUT /api/v1/admin/items/{id}` — update an item. */ -export function adminUpdateItem(id: number, input: AdminItemInput): Promise { - return api.put(`/admin/items/${id}`, input); +/** `PUT /api/v1/admin/articles/{id}` — update an article. */ +export function adminUpdateArticle( + id: number, + input: AdminArticleInput, +): Promise { + return api.put(`/admin/articles/${id}`, input); } -/** `DELETE /api/v1/admin/items/{id}` — hard-delete an item (204). */ -export function adminDeleteItem(id: number): Promise { - return api.delete(`/admin/items/${id}`); +/** `DELETE /api/v1/admin/articles/{id}` — hard-delete an article (204). */ +export function adminDeleteArticle(id: number): Promise { + return api.delete(`/admin/articles/${id}`); +} + +/** `GET /api/v1/admin/authors` — reference list for the article form. */ +export function adminListAuthors(): Promise { + return api.get('/admin/authors'); +} + +/** `GET /api/v1/admin/categories` — reference list for the article form. */ +export function adminListCategories(): Promise { + return api.get('/admin/categories'); } diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 144cae4..c4be899 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -195,10 +195,10 @@ export function logout(): Promise { } /** - * `GET /api/v1/articles` — list of published articles. + * `GET /api/v1/articles` — list of published articles (newest first). * - * The endpoint is provided by a later backend milestone; until then the - * UI falls back to sample data (see `src/data/sample.ts`). + * The Home page falls back to sample data (see `src/data/sample.ts`) + * when the backend is unreachable or has no published articles yet. */ export function getArticles(): Promise { return api.get('/articles').then((articles) => diff --git a/frontend/src/components/AdminLayout.tsx b/frontend/src/components/AdminLayout.tsx index 7735679..9d8c193 100644 --- a/frontend/src/components/AdminLayout.tsx +++ b/frontend/src/components/AdminLayout.tsx @@ -94,11 +94,11 @@ export function AdminLayout({ className }: AdminLayoutProps) {