Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c83f717c4 | ||
|
|
0449cc8fb9 | ||
|
|
afa399776f | ||
|
|
de96d0b152 | ||
|
|
38632bdedf | ||
|
|
e62fad4a10 | ||
|
|
b440809548 | ||
|
|
b186d0f797 | ||
|
|
ed7b30438e | ||
|
|
9144411e0f | ||
|
|
b410dcb09d | ||
|
|
253052c551 | ||
|
|
85ab297f89 |
No files matched your search
@@ -0,0 +1,34 @@
|
||||
# newzy — environment variable template.
|
||||
#
|
||||
# Copy to `.env` and adjust as needed:
|
||||
#
|
||||
# cp .env.example .env
|
||||
#
|
||||
# `docker compose` in this directory reads `.env` automatically. `.env` is
|
||||
# excluded from version control (see .gitignore) — never commit secrets.
|
||||
# The backend's own defaults are documented in `backend/.env.example`.
|
||||
|
||||
# --- Database -------------------------------------------------------------
|
||||
# SQLite database location (SQLAlchemy URL, relative to the backend's
|
||||
# working directory). Inside the Docker image this resolves to
|
||||
# /app/data/db/newzy.db, which is bind-mounted to ./data/db on the host.
|
||||
DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||
|
||||
# --- Backend ----------------------------------------------------------------
|
||||
# Enable debug mode (verbose logs; keep off in production).
|
||||
DEBUG=false
|
||||
# JWT signing key (HS256) used by the backend auth endpoints. Change this
|
||||
# before deploying publicly — the dev default is not secret.
|
||||
HN_SECRET_KEY=newzy-dev-secret-change-me
|
||||
# Comma-separated list of origins the backend allows for CORS. The Docker
|
||||
# frontend proxies /api (same-origin, no CORS needed); this mainly matters
|
||||
# when developing the frontend directly on http://localhost:5173.
|
||||
BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
|
||||
|
||||
# --- Frontend ----------------------------------------------------------------
|
||||
# Base URL the frontend uses to reach the backend API.
|
||||
# /api -> relative (recommended: the Vite dev server and the
|
||||
# Docker Nginx config both proxy /api to the backend)
|
||||
# http://host:port -> absolute (cross-origin; the origin must be listed in
|
||||
# BACKEND_CORS_ORIGINS)
|
||||
FRONTEND_API_URL=/api
|
||||
+4
-2
@@ -43,8 +43,10 @@ coverage/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Local data / uploads
|
||||
data/
|
||||
# Docker (local per-developer overrides; .dockerignore files are committed)
|
||||
docker-compose.override.yml
|
||||
|
||||
# Local data / uploads (data/ is managed by data/.gitignore)
|
||||
uploads/
|
||||
*.sqlite
|
||||
*.db
|
||||
@@ -0,0 +1,60 @@
|
||||
# newzy — development shortcuts (docker compose under the hood).
|
||||
# Run `make help` (or just `make`) for the list of targets.
|
||||
|
||||
COMPOSE ?= docker compose
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
|
||||
.PHONY: help dev stop restart build logs status backend-start frontend-start \
|
||||
test test-frontend test-backend e2e shell-backend shell-frontend clean
|
||||
|
||||
help: ## Show this help
|
||||
@grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-15s\033[0m %s\n", $$1, $$2}'
|
||||
|
||||
dev: ## Build (if needed) and start both services in the background
|
||||
$(COMPOSE) up -d --build
|
||||
|
||||
stop: ## Stop and remove containers (local data in ./data is kept)
|
||||
$(COMPOSE) down
|
||||
|
||||
restart: ## Recreate and start both services
|
||||
$(COMPOSE) down
|
||||
$(COMPOSE) up -d --build
|
||||
|
||||
build: ## Rebuild all images from scratch (no cache)
|
||||
$(COMPOSE) build --no-cache
|
||||
|
||||
logs: ## Follow the logs of both services
|
||||
$(COMPOSE) logs -f backend frontend
|
||||
|
||||
status: ## Show the status of both services
|
||||
$(COMPOSE) ps
|
||||
|
||||
backend-start: ## Build (if needed) and start the backend only
|
||||
$(COMPOSE) up -d backend
|
||||
|
||||
frontend-start: ## Build (if needed) and start the frontend only
|
||||
$(COMPOSE) up -d frontend
|
||||
|
||||
test: test-frontend test-backend ## Run all unit tests (frontend + backend)
|
||||
|
||||
test-frontend: ## Run frontend unit tests (requires Node.js 18+)
|
||||
cd frontend && npm run test
|
||||
|
||||
test-backend: ## Run backend tests (uses backend/.venv if present, else system pytest)
|
||||
cd backend && if [ -x .venv/bin/pytest ]; then .venv/bin/pytest; else pytest; fi
|
||||
|
||||
e2e: ## Run Playwright E2E tests (frontend/playwright; API calls are mocked)
|
||||
cd frontend && npm run e2e
|
||||
|
||||
shell-backend: ## Open a shell inside the running backend container
|
||||
$(COMPOSE) exec backend bash
|
||||
|
||||
shell-frontend: ## Open a shell inside the running frontend container
|
||||
$(COMPOSE) exec frontend sh
|
||||
|
||||
clean: ## Stop everything; remove containers, volumes and local data
|
||||
$(COMPOSE) down -v --remove-orphans
|
||||
rm -rf data/
|
||||
git checkout -- data/ 2>/dev/null || true
|
||||
docker image prune -f
|
||||
@@ -11,7 +11,8 @@
|
||||
| M1 | Git project setup | Done |
|
||||
| M2 | Backend setup (FastAPI) | Done |
|
||||
| M3 | Frontend setup (React + Vite) | Done |
|
||||
| M4+ | News application features | Planned |
|
||||
| M4 | Developer environment (Docker) | Done |
|
||||
| M5+ | News application features | Planned |
|
||||
|
||||
See [milestones/](milestones/) for milestone prompts and progress tracking.
|
||||
|
||||
@@ -44,17 +45,112 @@ git push -u origin feature/<short-description>
|
||||
|
||||
Full contribution guidelines, including branching, merging, and rebase workflows, are in [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
## Running the application
|
||||
## Developer environment (Docker Compose)
|
||||
|
||||
The repository root ships a complete Docker Compose setup: one command starts
|
||||
the FastAPI backend and the Nginx-served production frontend, with a
|
||||
persistent SQLite database on the host.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Docker** (Docker Desktop or the docker engine + compose plugin v2), with the daemon running
|
||||
- Optional (only for `make test` outside Docker): **Node.js 18+** and **Python 3.11+**
|
||||
|
||||
### Quick start
|
||||
|
||||
```bash
|
||||
# Full stack (backend :8000 + frontend :3000)
|
||||
docker compose up --build
|
||||
# 1. Configure the environment (defaults are fine for local development)
|
||||
cp .env.example .env
|
||||
|
||||
# 2. Build (if needed) and start both services in the background
|
||||
make dev
|
||||
|
||||
# 3. Open the application
|
||||
# Frontend: http://localhost:3000
|
||||
# Backend: http://localhost:8000 (Swagger docs: http://localhost:8000/api/v1/docs)
|
||||
|
||||
# 4. Stop everything (the database in ./data is kept)
|
||||
make stop
|
||||
```
|
||||
|
||||
Or run each half locally — see the component READMEs for details:
|
||||
### Services
|
||||
|
||||
- [frontend/README.md](frontend/README.md) — `npm run dev` (port 5173)
|
||||
- [backend/README.md](backend/README.md) — `uvicorn main:app --reload` (port 8000)
|
||||
| Service | Build context | Image base | What it does |
|
||||
| ---------- | ------------- | ----------------- | -------------------------------------------------------- |
|
||||
| `backend` | `./backend` | `python:3.11-slim`| FastAPI app (uvicorn), creates the SQLite schema on startup |
|
||||
| `frontend` | `./frontend` | `node:20-alpine` → `nginx:1.27-alpine` (multi-stage) | Builds the Vite bundle, serves it via Nginx with SPA routing and an `/api` proxy to the backend |
|
||||
|
||||
### Port mappings
|
||||
|
||||
| Host port | Container | Service |
|
||||
| --------- | --------- | -------- |
|
||||
| `3000` | `80` | frontend (Nginx) |
|
||||
| `8000` | `8000` | backend (uvicorn) |
|
||||
|
||||
### Networking and storage
|
||||
|
||||
- Both services share the bridge network `newzy-network` (subnet `172.28.0.0/16`),
|
||||
so the frontend reaches the backend by service name (`http://backend:8000`).
|
||||
- The SQLite database is stored on the host at [`data/db/newzy.db`](data/) via a
|
||||
bind mount (`./data/db` → `/app/data/db`). It is excluded from version control
|
||||
(see `data/.gitignore`) and survives `make stop`/`make restart`.
|
||||
- `frontend` only starts once `backend` reports healthy (`/health`), so
|
||||
`docker compose up` never serves a frontend with a dead API.
|
||||
|
||||
### Environment variables
|
||||
|
||||
`docker compose` reads [`.env`](.env) from the project root (template:
|
||||
[`.env.example`](.env.example)). Never commit `.env` or real secrets.
|
||||
|
||||
| Variable | Description | Default | Required |
|
||||
| --------------------- | ---------------------------------------- | --------------------------------------------------- | -------- |
|
||||
| `DATABASE_URL` | SQLite database path (SQLAlchemy URL) | `sqlite:///./data/db/newzy.db` | Yes |
|
||||
| `DEBUG` | Debug mode flag | `false` | No |
|
||||
| `BACKEND_CORS_ORIGINS`| Comma-separated allowed CORS origins | `http://localhost:3000,http://localhost:5173` | No |
|
||||
| `FRONTEND_API_URL` | Backend API base URL (relative or absolute) | `/api` | No |
|
||||
|
||||
### Makefile shortcuts
|
||||
|
||||
| Command | What it does |
|
||||
| ---------------------- | ------------------------------------------------------- |
|
||||
| `make dev` | Build (if needed) and start both services in the background |
|
||||
| `make stop` | Stop and remove containers (data kept) |
|
||||
| `make restart` | Recreate and start both services |
|
||||
| `make build` | Rebuild all images from scratch |
|
||||
| `make logs` | Follow logs of both services |
|
||||
| `make status` | Show service status |
|
||||
| `make backend-start` | Start the backend only |
|
||||
| `make frontend-start` | Start the frontend only |
|
||||
| `make test` | Run all unit tests (frontend vitest + backend pytest) |
|
||||
| `make e2e` | Run Playwright E2E tests (API calls mocked) |
|
||||
| `make shell-backend` | Open a shell in the backend container |
|
||||
| `make shell-frontend` | Open a shell in the frontend container |
|
||||
| `make clean` | Stop everything, remove containers, volumes and `data/` |
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
- **Port already in use** (`bind: address already in use`): stop the other
|
||||
process (`lsof -i :3000` / `lsof -i :8000`) or change the host port in
|
||||
`docker-compose.yml` (e.g. `"3001:80"`).
|
||||
- **Frontend starts but shows errors / 502 on API calls**: the backend is not
|
||||
healthy yet — check `make logs backend`. The frontend waits for the backend
|
||||
health check on startup; after a slow start, reload the page.
|
||||
- **`docker compose` not found**: install the Compose v2 plugin
|
||||
(`docker compose version` must print a version).
|
||||
- **Database reset**: `make clean` removes `data/` (including the SQLite file);
|
||||
tables are recreated on the next backend start.
|
||||
- **Slow builds on first run**: the first `make dev` pulls the base images and
|
||||
installs dependencies (~5 minutes). Subsequent builds use the Docker layer
|
||||
cache and finish in seconds.
|
||||
- **Ownership issues in `data/`** (e.g. after running Docker as root): restore
|
||||
with `sudo chown -R $(id -un):$(id -gn) data/`.
|
||||
- **Windows**: use WSL2 for best performance; **macOS**: allow Docker Desktop
|
||||
sufficient disk space (50 GB+ recommended).
|
||||
|
||||
### Running without Docker
|
||||
|
||||
- Frontend: [`frontend/README.md`](frontend/README.md) — `npm run dev` (port 5173, proxies `/api` to :8000)
|
||||
- Backend: [`backend/README.md`](backend/README.md) — `uvicorn main:app --reload` (port 8000)
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
@@ -5,3 +5,12 @@ DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||
|
||||
# Comma-separated list of origins allowed by CORS (frontend dev server etc.)
|
||||
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
||||
|
||||
# JWT signing key (HS256). Change this in production — tokens signed with
|
||||
# the dev default must be considered insecure.
|
||||
HN_SECRET_KEY=newzy-dev-secret-change-me
|
||||
|
||||
# Credentials for `seed_admin.py` (creates or promotes an admin account;
|
||||
# safe to re-run). Only used by the seeding script, never by the app itself.
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=change-me
|
||||
+3
-1
@@ -3,8 +3,10 @@ __pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
|
||||
# Environment files
|
||||
# Environment files (keep the committed template)
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
|
||||
+13
-3
@@ -1,15 +1,25 @@
|
||||
# newzy backend — FastAPI + SQLite.
|
||||
# Orchestration lives in the repository root: docker-compose.yml.
|
||||
|
||||
FROM python:3.11-slim
|
||||
|
||||
# Unbuffered logs, no .pyc files in the image, no pip cache.
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PIP_NO_CACHE_DIR=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies first to leverage Docker layer caching
|
||||
# Install dependencies first to leverage Docker layer caching.
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
# Copy application code (dev-only files excluded by .dockerignore).
|
||||
COPY . .
|
||||
|
||||
# SQLite database lives on a mounted volume (see docker-compose.yml)
|
||||
# The SQLite database lives on a bind-mounted volume (see docker-compose.yml);
|
||||
# ensure the directory exists even before the volume is attached.
|
||||
RUN mkdir -p /app/data/db
|
||||
VOLUME /app/data/db
|
||||
|
||||
# Expose port
|
||||
|
||||
@@ -5,11 +5,23 @@ 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 (article CRUD, admin-only) under /api/v1/admin.
|
||||
router.include_router(admin_routes.router)
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse, summary="Service health check")
|
||||
def get_health() -> HealthResponse:
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
"""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
|
||||
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 /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
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import asc, desc, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from core import auth
|
||||
from db.session import get_db
|
||||
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"])
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Rate limiting (placeholder: in-memory, per admin account)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
def __init__(self, limit: int = 1000, window_seconds: float = 60.0) -> None:
|
||||
self.limit = limit
|
||||
self.window_seconds = window_seconds
|
||||
self._hits: dict[str, list[float]] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def check(self, key: str) -> bool:
|
||||
"""Record a hit for ``key`` and return ``True`` when it is allowed."""
|
||||
now = time.monotonic()
|
||||
with self._lock:
|
||||
window = [
|
||||
stamp
|
||||
for stamp in self._hits.get(key, ())
|
||||
if now - stamp < self.window_seconds
|
||||
]
|
||||
if len(window) >= self.limit:
|
||||
self._hits[key] = window
|
||||
return False
|
||||
window.append(now)
|
||||
self._hits[key] = window
|
||||
return True
|
||||
|
||||
|
||||
_limiter = _RateLimiter()
|
||||
|
||||
|
||||
def _rate_limit(admin: User = Depends(auth.get_current_admin)) -> User:
|
||||
"""Reject the request (429) when the admin exceeds the request budget."""
|
||||
if not _limiter.check(admin.username):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Too many requests — slow down.",
|
||||
)
|
||||
return admin
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
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 ``content`` (case-insensitive substring match)."""
|
||||
if not search:
|
||||
return query
|
||||
pattern = f"%{search}%"
|
||||
return query.filter(
|
||||
or_(Article.title.ilike(pattern), Article.content.ilike(pattern))
|
||||
)
|
||||
|
||||
|
||||
def _apply_sort(query, sort_by: str, sort_order: str):
|
||||
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(
|
||||
"/articles",
|
||||
response_model=ArticleAdminList,
|
||||
summary="List articles (paginated, searchable, sortable)",
|
||||
)
|
||||
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="Articles per page (1-100)"
|
||||
),
|
||||
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),
|
||||
) -> 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()
|
||||
articles = query.offset((page - 1) * page_size).limit(page_size).all()
|
||||
total_pages = (total + page_size - 1) // page_size
|
||||
return ArticleAdminList(
|
||||
articles=[ArticleRead.model_validate(article) for article in articles],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=total_pages,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/articles",
|
||||
response_model=ArticleRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a new article",
|
||||
)
|
||||
def create_article(
|
||||
payload: ArticleCreate,
|
||||
admin: User = Depends(_rate_limit),
|
||||
db: Session = Depends(get_db),
|
||||
) -> 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,
|
||||
content=payload.content,
|
||||
author_id=payload.author_id,
|
||||
category_id=payload.category_id,
|
||||
published=payload.published,
|
||||
)
|
||||
db.add(article)
|
||||
_commit(db, action="create")
|
||||
db.refresh(article)
|
||||
return ArticleRead.model_validate(article)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/articles/{article_id}",
|
||||
response_model=ArticleRead,
|
||||
summary="Get a single article",
|
||||
)
|
||||
def get_article(
|
||||
article_id: int,
|
||||
admin: User = Depends(_rate_limit),
|
||||
db: Session = Depends(get_db),
|
||||
) -> 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(
|
||||
"/articles/{article_id}",
|
||||
response_model=ArticleRead,
|
||||
summary="Update an article",
|
||||
)
|
||||
def update_article(
|
||||
article_id: int,
|
||||
payload: ArticleUpdate,
|
||||
admin: User = Depends(_rate_limit),
|
||||
db: Session = Depends(get_db),
|
||||
) -> 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 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(article, field, value)
|
||||
_commit(db, action="update")
|
||||
db.refresh(article)
|
||||
return ArticleRead.model_validate(article)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/articles/{article_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Delete an article",
|
||||
)
|
||||
def delete_article(
|
||||
article_id: int,
|
||||
admin: User = Depends(_rate_limit),
|
||||
db: Session = Depends(get_db),
|
||||
) -> None:
|
||||
"""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"]
|
||||
@@ -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)
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Authentication endpoints: register, login, logout, me.
|
||||
|
||||
Passwords are stored only as PBKDF2-HMAC-SHA256 hashes (``core.auth``).
|
||||
Sessions are stateless: the client keeps the JWT and sends it back as a
|
||||
Bearer token, so ``logout`` is a server-side no-op (best-effort 204).
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core import auth
|
||||
from db.session import get_db
|
||||
from models import User
|
||||
from schemas import LoginIn, RegisterIn, TokenOut, UserOut
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
def _user_by_username(db: Session, username: str) -> User | None:
|
||||
return db.query(User).filter(User.username == username).first()
|
||||
|
||||
|
||||
@router.post(
|
||||
"/register",
|
||||
response_model=TokenOut,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Register a new account",
|
||||
)
|
||||
def register(payload: RegisterIn, db: Session = Depends(get_db)) -> TokenOut:
|
||||
"""Create a user (password hashed with PBKDF2) and issue a JWT."""
|
||||
if _user_by_username(db, payload.username) is not None:
|
||||
raise HTTPException(status_code=400, detail="Username already exists")
|
||||
user = User(
|
||||
username=payload.username,
|
||||
password_hash=auth.hash_password(payload.password),
|
||||
)
|
||||
db.add(user)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
# Lost the race against a concurrent registration.
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=400, detail="Username already exists") from None
|
||||
return TokenOut(
|
||||
token=auth.create_token(user.username),
|
||||
username=user.username,
|
||||
is_admin=user.is_admin,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenOut, summary="Log in with credentials")
|
||||
def login(payload: LoginIn, db: Session = Depends(get_db)) -> TokenOut:
|
||||
"""Verify the credentials and issue a JWT."""
|
||||
user = _user_by_username(db, payload.username)
|
||||
if user is None or not auth.verify_password(payload.password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Invalid username or password")
|
||||
return TokenOut(
|
||||
token=auth.create_token(user.username),
|
||||
username=user.username,
|
||||
is_admin=user.is_admin,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/logout",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Log out (stateless)",
|
||||
)
|
||||
def logout(current_user: str = Depends(auth.get_current_user)) -> None:
|
||||
"""Best-effort logout: the client simply discards its token."""
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut, summary="Current authenticated user")
|
||||
def me(current_user: User = Depends(auth.get_current_user_obj)) -> UserOut:
|
||||
"""Return the user the Bearer token belongs to (including ``is_admin``)."""
|
||||
return UserOut(username=current_user.username, is_admin=current_user.is_admin)
|
||||
@@ -21,6 +21,10 @@ DEFAULT_DATABASE_URL = "sqlite:///./data/db/newzy.db"
|
||||
# Default origins allowed by CORS (frontend dev servers).
|
||||
DEFAULT_CORS_ORIGINS = "http://localhost:3000,http://127.0.0.1:3000"
|
||||
|
||||
# Default JWT signing key (override via HN_SECRET_KEY in production —
|
||||
# never run a public deployment with the dev default).
|
||||
DEFAULT_SECRET_KEY = "newzy-dev-secret-change-me"
|
||||
|
||||
|
||||
class Settings:
|
||||
"""Runtime settings loaded from the environment."""
|
||||
@@ -32,6 +36,8 @@ class Settings:
|
||||
for origin in os.getenv("CORS_ORIGINS", DEFAULT_CORS_ORIGINS).split(",")
|
||||
if origin.strip()
|
||||
]
|
||||
# JWT signing key for auth tokens (see core.auth).
|
||||
self.secret_key: str = os.getenv("HN_SECRET_KEY", DEFAULT_SECRET_KEY)
|
||||
|
||||
@property
|
||||
def is_sqlite(self) -> bool:
|
||||
|
||||
+28
-1
@@ -17,6 +17,7 @@ from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import inspect, text
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from api.v1 import router as api_v1_router
|
||||
@@ -47,10 +48,36 @@ def _error_response(status_code: int, detail: str, code: str, errors=None) -> JS
|
||||
return JSONResponse(status_code=status_code, content=payload)
|
||||
|
||||
|
||||
def _ensure_user_columns() -> None:
|
||||
"""Lightweight schema upgrade for pre-existing databases.
|
||||
|
||||
``Base.metadata.create_all`` creates missing *tables* but never alters
|
||||
existing ones, so databases created before M6 (which added
|
||||
``users.is_admin``) are patched here. Idempotent: inspects the table
|
||||
and only issues ``ALTER TABLE`` for columns that are absent.
|
||||
"""
|
||||
inspector = inspect(engine)
|
||||
if "users" not in inspector.get_table_names():
|
||||
return
|
||||
existing = {column["name"] for column in inspector.get_columns("users")}
|
||||
if "is_admin" not in existing:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text("ALTER TABLE users ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT 0")
|
||||
)
|
||||
logger.info("Added users.is_admin column to pre-existing database")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
"""Create database tables on startup (idempotent for SQLite volumes)."""
|
||||
"""Create database tables (and patch old schemas) on startup.
|
||||
|
||||
Idempotent for SQLite volumes: new tables are created and existing
|
||||
ones only receive the missing-column upgrades (see
|
||||
``_ensure_user_columns``).
|
||||
"""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
_ensure_user_columns()
|
||||
logger.info("Database tables ensured (engine: %s)", engine.url)
|
||||
yield
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Authentication primitives.
|
||||
|
||||
- Passwords are stored only as PBKDF2-HMAC-SHA256 hashes with a random
|
||||
per-password salt (never in plaintext).
|
||||
- Sessions are stateless JWTs (HS256) signed with ``HN_SECRET_KEY``
|
||||
(see ``config.Settings``), valid for 7 days.
|
||||
- ``get_current_user`` is the FastAPI dependency that validates the
|
||||
``Authorization: Bearer <token>`` header and returns the username.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
import time
|
||||
|
||||
import jwt
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from config import get_settings
|
||||
from db.session import get_db
|
||||
from models import User
|
||||
|
||||
# HS256 JWTs signed with the application secret. The dev default keeps
|
||||
# tokens valid across container restarts; override via HN_SECRET_KEY.
|
||||
SECRET_KEY = get_settings().secret_key
|
||||
ALGORITHM = "HS256"
|
||||
TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days
|
||||
|
||||
# PBKDF2-HMAC-SHA256 parameters (120,000 iterations per OWASP guidance).
|
||||
PBKDF2_ITERATIONS = 120_000
|
||||
|
||||
# ``auto_error=False`` so missing headers produce our own 401 envelope
|
||||
# instead of FastAPI's default 403.
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hash ``password`` with a fresh random salt.
|
||||
|
||||
Returns ``"<salt>$<digest>"`` where ``salt`` is 32 hex chars
|
||||
(``secrets.token_hex(16)``) and ``digest`` is the PBKDF2 hex digest.
|
||||
"""
|
||||
salt = secrets.token_hex(16)
|
||||
digest = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
|
||||
).hex()
|
||||
return f"{salt}${digest}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
"""Verify ``password`` against a stored ``"<salt>$<digest>"`` hash.
|
||||
|
||||
The comparison is constant-time (``secrets.compare_digest``).
|
||||
Malformed stored values simply verify as ``False``.
|
||||
"""
|
||||
try:
|
||||
salt, digest = stored.split("$", 1)
|
||||
salt_bytes = bytes.fromhex(salt)
|
||||
except ValueError:
|
||||
return False
|
||||
candidate = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode(), salt_bytes, PBKDF2_ITERATIONS
|
||||
).hex()
|
||||
return secrets.compare_digest(candidate, digest)
|
||||
|
||||
|
||||
def create_token(username: str) -> str:
|
||||
"""Create a signed JWT for ``username`` (``sub``/``iat``/``exp``)."""
|
||||
now = int(time.time())
|
||||
payload = {
|
||||
"sub": username,
|
||||
"iat": now,
|
||||
"exp": now + TOKEN_TTL_SECONDS,
|
||||
}
|
||||
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def _user_for_token(
|
||||
credentials: HTTPAuthorizationCredentials | None, db: Session
|
||||
) -> User:
|
||||
"""Validate the Bearer token and return the matching :class:`User`.
|
||||
|
||||
Raises 401 when the header is missing, the token is invalid/expired
|
||||
or was issued to a user that no longer exists.
|
||||
"""
|
||||
if credentials is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
try:
|
||||
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
except jwt.PyJWTError as exc:
|
||||
raise HTTPException(status_code=401, detail="Invalid or expired token") from exc
|
||||
username = payload.get("sub")
|
||||
user = db.query(User).filter(User.username == username).first() if username else None
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Unknown user")
|
||||
return user
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> str:
|
||||
"""Validate the Bearer token and return the username.
|
||||
|
||||
Raises 401 when the header is missing, the token is invalid/expired
|
||||
or was issued to a user that no longer exists.
|
||||
"""
|
||||
return _user_for_token(credentials, db).username
|
||||
|
||||
|
||||
def get_current_user_obj(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Validate the Bearer token and return the matching :class:`User`."""
|
||||
return _user_for_token(credentials, db)
|
||||
|
||||
|
||||
def get_current_admin(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Admin-only dependency: validates the token *and* the ``is_admin`` flag.
|
||||
|
||||
A valid JWT alone is not enough — the account must additionally have
|
||||
``User.is_admin`` set. Raises 401 for missing/invalid tokens or unknown
|
||||
users and 403 ("Admin access required") for authenticated non-admins.
|
||||
"""
|
||||
user = _user_for_token(credentials, db)
|
||||
if not user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
return user
|
||||
@@ -4,5 +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.user import User
|
||||
|
||||
__all__ = ["Article", "Author", "Base", "Category", "slugify"]
|
||||
__all__ = ["Article", "Author", "Base", "Category", "User", "slugify"]
|
||||
@@ -0,0 +1,37 @@
|
||||
"""User account model (JWT-based authentication, see ``core.auth``)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from models.base import Base
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class User(Base):
|
||||
"""A registered newzy account.
|
||||
|
||||
``password_hash`` stores ``"<salt>$<pbkdf2-digest>"`` (see
|
||||
``core.auth.hash_password``) — never the plaintext password.
|
||||
"""
|
||||
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(128))
|
||||
#: Grants access to the admin area (``/api/v1/admin/*``). Never set by
|
||||
#: the registration endpoint; promote users via ``seed_admin.py``.
|
||||
is_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=_utcnow, nullable=False
|
||||
)
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return f"<User id={self.id} username={self.username!r}>"
|
||||
@@ -8,6 +8,9 @@ SQLAlchemy>=2.0.41
|
||||
# --- Schemas / validation ---------------------------------------------------
|
||||
pydantic>=2.11
|
||||
|
||||
# --- Auth (JWT; password hashing uses stdlib hashlib/secrets) --------------
|
||||
PyJWT>=2.8
|
||||
|
||||
# --- Misc runtime -----------------------------------------------------------
|
||||
python-multipart>=0.0.20
|
||||
|
||||
|
||||
@@ -1,11 +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
|
||||
|
||||
__all__ = [
|
||||
"ArticleAdminList",
|
||||
"ArticleBase",
|
||||
"ArticleCreate",
|
||||
"ArticleRead",
|
||||
@@ -20,5 +33,9 @@ __all__ = [
|
||||
"CategoryUpdate",
|
||||
"ErrorDetail",
|
||||
"HealthResponse",
|
||||
"LoginIn",
|
||||
"RegisterIn",
|
||||
"TokenOut",
|
||||
"UserOut",
|
||||
"VersionResponse",
|
||||
]
|
||||
@@ -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
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Authentication request/response schemas (see ``api.v1.auth``)."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class RegisterIn(BaseModel):
|
||||
"""Payload of ``POST /api/v1/auth/register``.
|
||||
|
||||
Usernames are restricted to 3-20 characters of letters, numbers and
|
||||
underscores; passwords must be at least 8 characters.
|
||||
"""
|
||||
|
||||
username: str = Field(
|
||||
min_length=3,
|
||||
max_length=20,
|
||||
pattern=r"^[a-zA-Z0-9_]{3,20}$",
|
||||
description="3-20 characters: letters, numbers, underscores.",
|
||||
)
|
||||
password: str = Field(min_length=8, max_length=200)
|
||||
|
||||
|
||||
class LoginIn(BaseModel):
|
||||
"""Payload of ``POST /api/v1/auth/login``."""
|
||||
|
||||
username: str = Field(min_length=1, max_length=60)
|
||||
password: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class TokenOut(BaseModel):
|
||||
"""Token response shared by the register and login endpoints."""
|
||||
|
||||
token: str
|
||||
username: str
|
||||
#: Whether the account may access the admin area (see M6).
|
||||
is_admin: bool = False
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
"""Payload of ``GET /api/v1/auth/me``."""
|
||||
|
||||
username: str
|
||||
#: Whether the account may access the admin area (see M6).
|
||||
is_admin: bool = False
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Create (or promote) an administrator account.
|
||||
|
||||
Usage (inside the backend container or with the backend venv)::
|
||||
|
||||
ADMIN_USERNAME=admin ADMIN_PASSWORD='secret' python seed_admin.py
|
||||
|
||||
Reads ``ADMIN_USERNAME`` and ``ADMIN_PASSWORD`` from the environment (see
|
||||
``.env.example``). When the user already exists the account is promoted to
|
||||
admin and its password is reset to ``ADMIN_PASSWORD``. Safe to re-run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from core import auth
|
||||
from db.session import SessionLocal
|
||||
from models import User
|
||||
|
||||
|
||||
def main() -> int:
|
||||
username = os.getenv("ADMIN_USERNAME", "").strip()
|
||||
password = os.getenv("ADMIN_PASSWORD", "")
|
||||
if not username or not password:
|
||||
print(
|
||||
"error: set ADMIN_USERNAME and ADMIN_PASSWORD "
|
||||
"(see .env.example), e.g.\n"
|
||||
" ADMIN_USERNAME=admin ADMIN_PASSWORD='secret' python seed_admin.py",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
if user is None:
|
||||
user = User(
|
||||
username=username,
|
||||
password_hash=auth.hash_password(password),
|
||||
is_admin=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
print(f"Created admin user '{username}'.")
|
||||
else:
|
||||
user.is_admin = True
|
||||
user.password_hash = auth.hash_password(password)
|
||||
db.commit()
|
||||
print(f"Promoted existing user '{username}' to admin (password reset).")
|
||||
return 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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())
|
||||
@@ -0,0 +1,671 @@
|
||||
"""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, article creation,
|
||||
partial updates, deletion and input validation.
|
||||
"""
|
||||
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import jwt as pyjwt
|
||||
import pytest
|
||||
|
||||
from api.v1 import admin as admin_api
|
||||
from core import auth
|
||||
from models import Article, Author, Category, User
|
||||
|
||||
BASE = "/api/v1/admin/articles"
|
||||
|
||||
|
||||
def _make_user(session, username: str, is_admin: bool = False) -> User:
|
||||
user = User(username=username, password_hash="salt$digest", is_admin=is_admin)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _headers(session, username: str) -> dict:
|
||||
"""A valid Bearer token for an (already persisted) user."""
|
||||
return {"Authorization": f"Bearer {auth.create_token(username)}"}
|
||||
|
||||
|
||||
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 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"<p>Body {i}</p>",
|
||||
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", ADMIN_ROUTES)
|
||||
def test_missing_token_returns_401(self, client, method, path) -> 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"
|
||||
|
||||
def test_invalid_token_returns_401(self, client) -> None:
|
||||
response = client.get(BASE, headers={"Authorization": "Bearer not.a.jwt"})
|
||||
assert response.status_code == 401
|
||||
assert response.json()["code"] == "unauthorized"
|
||||
|
||||
def test_expired_token_returns_401(self, client, session) -> None:
|
||||
_make_user(session, "admin", is_admin=True)
|
||||
now = int(time.time())
|
||||
token = pyjwt.encode(
|
||||
{"sub": "admin", "iat": now - 200, "exp": now - 100},
|
||||
auth.SECRET_KEY,
|
||||
algorithm="HS256",
|
||||
)
|
||||
response = client.get(BASE, headers={"Authorization": f"Bearer {token}"})
|
||||
assert response.status_code == 401
|
||||
|
||||
def test_token_for_deleted_user_returns_401(self, client, session) -> None:
|
||||
_make_user(session, "admin", is_admin=True)
|
||||
headers = _headers(session, "admin")
|
||||
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", 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 in ("POST", "PUT") else None
|
||||
response = client.request(
|
||||
method, path, json=payload, headers=_headers(session, "alice")
|
||||
)
|
||||
assert response.status_code == 403
|
||||
body = response.json()
|
||||
assert body["code"] == "forbidden"
|
||||
assert body["detail"] == "Admin access required"
|
||||
|
||||
|
||||
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["articles"] == []
|
||||
assert body["total"] == 0
|
||||
assert body["page"] == 1
|
||||
assert body["page_size"] == 20
|
||||
assert body["total_pages"] == 0
|
||||
|
||||
def test_pagination_math_and_contents(self, client, session) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
_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["articles"]) == 10
|
||||
assert page1["page"] == 1
|
||||
|
||||
page2 = client.get(BASE, params={"page": 2, "page_size": 10}, headers=headers).json()
|
||||
assert len(page2["articles"]) == 10
|
||||
# Pages are disjoint.
|
||||
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["articles"]) == 5
|
||||
|
||||
def test_page_size_bounds(self, client, session) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
headers = _headers(session, "root")
|
||||
assert client.get(BASE, params={"page_size": 0}, headers=headers).status_code == 422
|
||||
assert client.get(BASE, params={"page_size": 101}, headers=headers).status_code == 422
|
||||
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_content_case_insensitively(self, client, session) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
_seed_articles(session, 5)
|
||||
headers = _headers(session, "root")
|
||||
|
||||
by_title = client.get(BASE, params={"search": "STORY 02"}, headers=headers).json()
|
||||
assert [a["title"] for a in by_title["articles"]] == ["Story 02"]
|
||||
|
||||
# Bodies are "<p>Body <n></p>" — 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["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_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["articles"] == []
|
||||
assert body["total"] == 0
|
||||
|
||||
# The table is intact after the "attack".
|
||||
intact = client.get(BASE, headers=headers).json()
|
||||
assert intact["total"] == 5
|
||||
|
||||
@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_articles(session, 5)
|
||||
headers = _headers(session, "root")
|
||||
body = client.get(
|
||||
BASE, params={"sort_by": "title", "sort_order": order}, headers=headers
|
||||
).json()
|
||||
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", ["asc", "desc"])
|
||||
def test_sort_by_created_at(self, client, session, order) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
articles = _seed_articles(session, 5)
|
||||
# Distinct timestamps so the ordering is deterministic.
|
||||
base = datetime(2025, 1, 1, tzinfo=timezone.utc)
|
||||
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 = [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": "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
|
||||
)
|
||||
assert (
|
||||
client.get(BASE, params={"sort_order": "up"}, headers=headers).status_code == 422
|
||||
)
|
||||
|
||||
def test_article_payload_shape(self, client, session) -> None:
|
||||
"""List entries embed the related author and category."""
|
||||
_make_user(session, "root", is_admin=True)
|
||||
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()
|
||||
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 TestGetArticle:
|
||||
def test_returns_full_article_including_content(self, client, session) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
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}/{articles[0].id}", headers=headers)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["id"] == articles[0].id
|
||||
assert body["title"] == "Story 00"
|
||||
assert body["content"] == "<p>Body 0</p>"
|
||||
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)
|
||||
headers = _headers(session, "root")
|
||||
response = client.get(f"{BASE}/9999", headers=headers)
|
||||
assert response.status_code == 404
|
||||
assert response.json()["code"] == "not_found"
|
||||
|
||||
|
||||
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": "Fresh news",
|
||||
"content": "<p>Hello world.</p>",
|
||||
"author_id": author.id,
|
||||
"category_id": category.id,
|
||||
}
|
||||
response = client.post(BASE, json=payload, headers=headers)
|
||||
assert response.status_code == 201
|
||||
body = response.json()
|
||||
assert body["title"] == "Fresh news"
|
||||
assert body["content"] == "<p>Hello world.</p>"
|
||||
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": "<p>Live now.</p>",
|
||||
"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",
|
||||
[
|
||||
{}, # everything missing
|
||||
{"title": "t", "content": "<p>c</p>"}, # missing author/category
|
||||
{"title": "t", "author_id": 1, "category_id": 1}, # missing content
|
||||
{"title": ""}, # empty title
|
||||
{"title": "x" * 201}, # too long
|
||||
{"title": "t", "content": "<p>c</p>", "author_id": 0}, # invalid ids
|
||||
],
|
||||
)
|
||||
def test_validation_failures_return_422(self, client, session, payload) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
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": "<p>x</p>",
|
||||
"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"
|
||||
|
||||
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": "<p>x</p>",
|
||||
"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": "<p>another body</p>",
|
||||
"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)
|
||||
articles = _seed_articles(session, 1)
|
||||
headers = _headers(session, "root")
|
||||
|
||||
response = client.put(
|
||||
f"{BASE}/{articles[0].id}", json={"published": False}, headers=headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["published"] is False
|
||||
# Untouched fields keep their values.
|
||||
assert body["title"] == "Story 00"
|
||||
assert body["content"] == "<p>Body 0</p>"
|
||||
|
||||
def test_full_update(self, client, session) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
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",
|
||||
"content": "<p>Updated</p>",
|
||||
"author_id": new_author.id,
|
||||
"category_id": new_category.id,
|
||||
"published": False,
|
||||
}
|
||||
response = client.put(
|
||||
f"{BASE}/{articles[0].id}", json=payload, headers=_headers(session, "root")
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["title"] == "Retitled"
|
||||
assert body["content"] == "<p>Updated</p>"
|
||||
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)
|
||||
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)
|
||||
articles = _seed_articles(session, 1)
|
||||
response = client.put(
|
||||
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)
|
||||
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"
|
||||
|
||||
def test_title_collision_returns_409(self, client, session) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
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
|
||||
|
||||
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}/{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)
|
||||
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."""
|
||||
|
||||
def test_legacy_users_table_gains_is_admin(self) -> None:
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from core.app import _ensure_user_columns
|
||||
from db.session import engine
|
||||
from models import Base
|
||||
|
||||
with engine.begin() as connection:
|
||||
# Simulate a pre-M6 schema: users without is_admin.
|
||||
connection.execute(text("DROP TABLE IF EXISTS users"))
|
||||
connection.execute(
|
||||
text(
|
||||
"CREATE TABLE users ("
|
||||
"id INTEGER PRIMARY KEY, "
|
||||
"username VARCHAR(60) NOT NULL UNIQUE, "
|
||||
"password_hash VARCHAR(128) NOT NULL, "
|
||||
"created_at DATETIME)"
|
||||
)
|
||||
)
|
||||
|
||||
_ensure_user_columns()
|
||||
|
||||
names = {c["name"] for c in inspect(engine).get_columns("users")}
|
||||
assert "is_admin" in names
|
||||
# The standard create_all path stays idempotent on the patched table.
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
def test_is_noop_when_column_exists(self) -> None:
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from core.app import _ensure_user_columns
|
||||
from db.session import engine
|
||||
from models import Base
|
||||
|
||||
Base.metadata.create_all(bind=engine) # fresh, M6 schema
|
||||
before = [c["name"] for c in inspect(engine).get_columns("users")]
|
||||
_ensure_user_columns()
|
||||
after = [c["name"] for c in inspect(engine).get_columns("users")]
|
||||
assert before == after # unchanged, no ALTER issued
|
||||
assert "is_admin" in before
|
||||
|
||||
|
||||
class TestSeedAdminScript:
|
||||
def test_creates_admin_user(self, session, monkeypatch, capsys) -> None:
|
||||
import seed_admin
|
||||
|
||||
monkeypatch.setenv("ADMIN_USERNAME", "root")
|
||||
monkeypatch.setenv("ADMIN_PASSWORD", "super-secret-1")
|
||||
monkeypatch.setattr(seed_admin, "SessionLocal", lambda: session)
|
||||
|
||||
assert seed_admin.main() == 0
|
||||
|
||||
user = session.query(User).filter(User.username == "root").first()
|
||||
assert user is not None
|
||||
assert user.is_admin is True
|
||||
assert auth.verify_password("super-secret-1", user.password_hash)
|
||||
assert "Created admin user 'root'" in capsys.readouterr().out
|
||||
|
||||
def test_promotes_existing_user_and_resets_password(
|
||||
self, session, monkeypatch, capsys
|
||||
) -> None:
|
||||
import seed_admin
|
||||
|
||||
_make_user(session, "root", is_admin=False)
|
||||
monkeypatch.setenv("ADMIN_USERNAME", "root")
|
||||
monkeypatch.setenv("ADMIN_PASSWORD", "new-secret-2")
|
||||
monkeypatch.setattr(seed_admin, "SessionLocal", lambda: session)
|
||||
|
||||
assert seed_admin.main() == 0
|
||||
|
||||
user = session.query(User).filter(User.username == "root").first()
|
||||
assert user is not None
|
||||
assert user.is_admin is True
|
||||
assert auth.verify_password("new-secret-2", user.password_hash)
|
||||
assert "Promoted existing user 'root'" in capsys.readouterr().out
|
||||
|
||||
def test_missing_env_vars_exit_with_error(self, monkeypatch, capsys) -> None:
|
||||
import seed_admin
|
||||
|
||||
monkeypatch.delenv("ADMIN_USERNAME", raising=False)
|
||||
monkeypatch.delenv("ADMIN_PASSWORD", raising=False)
|
||||
assert seed_admin.main() == 1
|
||||
assert "ADMIN_USERNAME" in capsys.readouterr().err
|
||||
|
||||
|
||||
class TestRateLimiting:
|
||||
"""The (placeholder) limiter rejects bursts beyond the configured budget."""
|
||||
|
||||
def test_burst_over_budget_returns_429(self, client, session, monkeypatch) -> None:
|
||||
_make_user(session, "root", is_admin=True)
|
||||
headers = _headers(session, "root")
|
||||
# Start from a clean budget (earlier tests may have used "root").
|
||||
admin_api._limiter._hits.clear()
|
||||
monkeypatch.setattr(admin_api._limiter, "limit", 3)
|
||||
monkeypatch.setattr(admin_api._limiter, "window_seconds", 60.0)
|
||||
try:
|
||||
for _ in range(3):
|
||||
assert client.get(BASE, headers=headers).status_code == 200
|
||||
response = client.get(BASE, headers=headers)
|
||||
assert response.status_code == 429
|
||||
assert response.json()["code"] == "too_many_requests"
|
||||
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()
|
||||
@@ -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"<p>Body for {title}</p>",
|
||||
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"<p>Body for {article.title}</p>"
|
||||
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
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Tests for the auth primitives (core.auth) and the /api/v1/auth endpoints."""
|
||||
|
||||
import re
|
||||
import time
|
||||
|
||||
import jwt as pyjwt
|
||||
import pytest
|
||||
|
||||
from core import auth
|
||||
from models import User
|
||||
|
||||
|
||||
class TestPasswordHashing:
|
||||
def test_hash_format_and_roundtrip(self) -> None:
|
||||
hashed = auth.hash_password("s3cret!")
|
||||
salt, digest = hashed.split("$", 1)
|
||||
# salt = secrets.token_hex(16) -> 32 hex chars; sha256 digest -> 64.
|
||||
assert re.fullmatch(r"[0-9a-f]{32}", salt)
|
||||
assert re.fullmatch(r"[0-9a-f]{64}", digest)
|
||||
assert auth.verify_password("s3cret!", hashed)
|
||||
|
||||
def test_unique_salt_per_hash(self) -> None:
|
||||
assert auth.hash_password("same-password") != auth.hash_password("same-password")
|
||||
|
||||
def test_verify_wrong_password(self) -> None:
|
||||
hashed = auth.hash_password("correct-horse")
|
||||
assert not auth.verify_password("wrong-password", hashed)
|
||||
|
||||
def test_verify_rejects_malformed_stored_values(self) -> None:
|
||||
assert not auth.verify_password("x", "no-salt-separator")
|
||||
assert not auth.verify_password("x", "zz-!$deadbeef") # non-hex salt
|
||||
assert not auth.verify_password("x", "")
|
||||
assert not auth.verify_password("x", "validhex$") # empty digest
|
||||
|
||||
def test_iteration_count_is_owasp_minimum(self) -> None:
|
||||
assert auth.PBKDF2_ITERATIONS >= 120_000
|
||||
|
||||
|
||||
class TestTokenCreation:
|
||||
def test_payload_and_seven_day_expiry(self) -> None:
|
||||
token = auth.create_token("alice")
|
||||
payload = pyjwt.decode(token, auth.SECRET_KEY, algorithms=["HS256"])
|
||||
assert payload["sub"] == "alice"
|
||||
assert auth.TOKEN_TTL_SECONDS == 7 * 24 * 60 * 60
|
||||
assert payload["exp"] == payload["iat"] + auth.TOKEN_TTL_SECONDS
|
||||
assert payload["exp"] > int(time.time())
|
||||
|
||||
def test_token_signed_with_wrong_key_fails(self) -> None:
|
||||
token = auth.create_token("alice")
|
||||
with pytest.raises(pyjwt.InvalidSignatureError):
|
||||
pyjwt.decode(token, "some-other-secret", algorithms=["HS256"])
|
||||
|
||||
|
||||
def _register(client, username: str = "alice", password: str = "password123"):
|
||||
return client.post(
|
||||
"/api/v1/auth/register", json={"username": username, "password": password}
|
||||
)
|
||||
|
||||
|
||||
class TestRegisterEndpoint:
|
||||
def test_register_creates_user_and_returns_token(self, client, session) -> None:
|
||||
response = _register(client)
|
||||
assert response.status_code == 201
|
||||
body = response.json()
|
||||
assert body["username"] == "alice"
|
||||
assert body["token"]
|
||||
# Registration never grants admin rights (M6).
|
||||
assert body["is_admin"] is False
|
||||
|
||||
# The token decodes to the registered username.
|
||||
payload = pyjwt.decode(body["token"], auth.SECRET_KEY, algorithms=["HS256"])
|
||||
assert payload["sub"] == "alice"
|
||||
|
||||
# The user is persisted with a hashed (not plaintext) password.
|
||||
user = session.query(User).filter(User.username == "alice").first()
|
||||
assert user is not None
|
||||
assert user.password_hash != "password123"
|
||||
assert "$" in user.password_hash
|
||||
assert auth.verify_password("password123", user.password_hash)
|
||||
assert user.created_at is not None
|
||||
|
||||
def test_register_duplicate_username_returns_400(self, client) -> None:
|
||||
assert _register(client).status_code == 201
|
||||
response = _register(client)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["code"] == "bad_request"
|
||||
assert response.json()["detail"] == "Username already exists"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"username",
|
||||
["", "ab", "a" * 21, "bad name", "semi;colon", "with-dash", "dot.name", "ünicode"],
|
||||
)
|
||||
def test_register_rejects_invalid_usernames(self, client, username: str) -> None:
|
||||
assert _register(client, username=username).status_code == 422
|
||||
|
||||
def test_register_rejects_short_password(self, client) -> None:
|
||||
response = client.post(
|
||||
"/api/v1/auth/register", json={"username": "alice", "password": "short"}
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_register_requires_both_fields(self, client) -> None:
|
||||
response = client.post("/api/v1/auth/register", json={"username": "alice"})
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
class TestLoginEndpoint:
|
||||
def test_login_success_returns_token(self, client) -> None:
|
||||
assert _register(client).status_code == 201
|
||||
response = client.post(
|
||||
"/api/v1/auth/login", json={"username": "alice", "password": "password123"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["username"] == "alice"
|
||||
payload = pyjwt.decode(body["token"], auth.SECRET_KEY, algorithms=["HS256"])
|
||||
assert payload["sub"] == "alice"
|
||||
|
||||
def test_login_wrong_password_returns_401(self, client) -> None:
|
||||
_register(client)
|
||||
response = client.post(
|
||||
"/api/v1/auth/login", json={"username": "alice", "password": "nope-nope"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.json()["code"] == "unauthorized"
|
||||
|
||||
def test_login_unknown_user_returns_401(self, client) -> None:
|
||||
response = client.post(
|
||||
"/api/v1/auth/login", json={"username": "ghost", "password": "password123"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def _auth_headers(client, username: str = "alice") -> dict:
|
||||
token = _register(client, username=username).json()["token"]
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
class TestMeEndpoint:
|
||||
def test_me_with_valid_token(self, client) -> None:
|
||||
response = client.get("/api/v1/auth/me", headers=_auth_headers(client))
|
||||
assert response.status_code == 200
|
||||
# Registered (non-admin) accounts report is_admin=False (M6).
|
||||
assert response.json() == {"username": "alice", "is_admin": False}
|
||||
|
||||
def test_me_without_token_returns_401(self, client) -> None:
|
||||
response = client.get("/api/v1/auth/me")
|
||||
assert response.status_code == 401
|
||||
assert response.json()["code"] == "unauthorized"
|
||||
|
||||
def test_me_with_garbage_token_returns_401(self, client) -> None:
|
||||
response = client.get(
|
||||
"/api/v1/auth/me", headers={"Authorization": "Bearer not.a.jwt"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
|
||||
def test_me_with_expired_token_returns_401(self, client) -> None:
|
||||
_register(client)
|
||||
now = int(time.time())
|
||||
token = pyjwt.encode(
|
||||
{"sub": "alice", "iat": now - 10, "exp": now - 5},
|
||||
auth.SECRET_KEY,
|
||||
algorithm="HS256",
|
||||
)
|
||||
response = client.get(
|
||||
"/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
|
||||
def test_me_with_wrong_secret_returns_401(self, client) -> None:
|
||||
_register(client)
|
||||
now = int(time.time())
|
||||
token = pyjwt.encode(
|
||||
{"sub": "alice", "iat": now, "exp": now + 3600},
|
||||
"some-other-secret",
|
||||
algorithm="HS256",
|
||||
)
|
||||
response = client.get(
|
||||
"/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
|
||||
def test_me_token_for_deleted_user_returns_401(self, client, session) -> None:
|
||||
headers = _auth_headers(client)
|
||||
user = session.query(User).filter(User.username == "alice").first()
|
||||
assert user is not None
|
||||
session.delete(user)
|
||||
session.commit()
|
||||
response = client.get("/api/v1/auth/me", headers=headers)
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
class TestLogoutEndpoint:
|
||||
def test_logout_with_valid_token_returns_204(self, client) -> None:
|
||||
response = client.post("/api/v1/auth/logout", headers=_auth_headers(client))
|
||||
assert response.status_code == 204
|
||||
assert response.content == b""
|
||||
|
||||
def test_logout_without_token_returns_401(self, client) -> None:
|
||||
response = client.post("/api/v1/auth/logout")
|
||||
assert response.status_code == 401
|
||||
@@ -3,7 +3,7 @@
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from models import Article, Author, Category, slugify
|
||||
from models import Article, Author, Category, User, slugify
|
||||
|
||||
|
||||
class TestAuthor:
|
||||
@@ -41,6 +41,33 @@ class TestAuthor:
|
||||
assert author.bio is None
|
||||
|
||||
|
||||
class TestUser:
|
||||
def test_create_and_commit(self, session) -> None:
|
||||
user = User(username="alice", password_hash="abc$def")
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
assert user.id is not None
|
||||
assert user.created_at is not None
|
||||
assert user.is_admin is False # default: no admin rights (M6)
|
||||
assert session.get(User, user.id).username == "alice"
|
||||
|
||||
def test_is_admin_can_be_set(self, session) -> None:
|
||||
user = User(username="root", password_hash="abc$def", is_admin=True)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
assert user.is_admin is True
|
||||
|
||||
def test_unique_username_enforced(self, session) -> None:
|
||||
session.add(User(username="alice", password_hash="abc$def"))
|
||||
session.commit()
|
||||
session.add(User(username="alice", password_hash="other$hash"))
|
||||
with pytest.raises(IntegrityError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
|
||||
|
||||
class TestCategory:
|
||||
def test_create_and_commit(self, session) -> None:
|
||||
category = Category(name="Technology", slug="technology")
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Exclude everything under data/ from version control (SQLite database,
|
||||
# uploads, ...) except the keep file below, so the directory structure
|
||||
# (data/db/) survives a fresh clone.
|
||||
#
|
||||
# This blanket rule also covers the database files required by the M5
|
||||
# milestone: *.db, *.sqlite, data.db, newzy.db (e.g. data/db/newzy.db).
|
||||
*
|
||||
!.gitignore
|
||||
!keep_files.txt
|
||||
@@ -0,0 +1,4 @@
|
||||
# This file is tracked by git so the data/ directory structure (data/db/)
|
||||
# is preserved in fresh clones. Everything else under data/ — the SQLite
|
||||
# database (data/db/newzy.db), uploads, and other local state — is ignored
|
||||
# by data/.gitignore and recreated at runtime.
|
||||
+42
-2
@@ -1,23 +1,63 @@
|
||||
# newzy — full application stack (FastAPI backend + Nginx frontend).
|
||||
#
|
||||
# make dev # build (if needed) and start both services in the background
|
||||
# make stop # stop and remove the containers (local data is kept)
|
||||
# make clean # stop everything and remove containers, volumes and data/
|
||||
#
|
||||
# Environment variables are read from `.env` in this directory (template:
|
||||
# `.env.example`). See README.md for the complete developer documentation.
|
||||
#
|
||||
# The `version` key is intentionally omitted: it is obsolete in Compose v2
|
||||
# and only produces a deprecation warning.
|
||||
|
||||
services:
|
||||
backend:
|
||||
build: ./backend
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
# Persistent SQLite database: ./data/db on the host -> /app/data/db
|
||||
# inside the container (excluded from git, see data/.gitignore).
|
||||
- ./data/db:/app/data/db
|
||||
environment:
|
||||
- DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||
- DEBUG=false
|
||||
- BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
|
||||
# JWT signing key (override in .env; the backend falls back to a dev
|
||||
# default when unset). Never use the dev default in production.
|
||||
- HN_SECRET_KEY=${HN_SECRET_KEY:-newzy-dev-secret-change-me}
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
networks:
|
||||
- newzy-network
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
build: ./frontend
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "3000:80"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- newzy-network
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
newzy-network:
|
||||
driver: bridge
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.28.0.0/16
|
||||
|
||||
volumes:
|
||||
db-data:
|
||||
name: newzy-db-data
|
||||
@@ -0,0 +1,18 @@
|
||||
# Keep the image small: exclude dev-only files from the build context.
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
test-results/
|
||||
playwright-report/
|
||||
playwright/.cache/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.git/
|
||||
.gitignore
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
docker-compose.yml
|
||||
README.md
|
||||
*.log
|
||||
.DS_Store
|
||||
Generated
+346
-1
@@ -9,8 +9,16 @@
|
||||
"version": "0.1.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/code": "^0.25.0",
|
||||
"@lexical/html": "^0.25.0",
|
||||
"@lexical/link": "^0.25.0",
|
||||
"@lexical/list": "^0.25.0",
|
||||
"@lexical/react": "^0.25.0",
|
||||
"@lexical/rich-text": "^0.25.0",
|
||||
"@lexical/selection": "^0.25.0",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.0",
|
||||
"lexical": "^0.25.0",
|
||||
"lucide-react": "^0.263.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
@@ -356,7 +364,6 @@
|
||||
"version": "7.29.10",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
|
||||
"integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
@@ -1128,6 +1135,262 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/clipboard": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/clipboard/-/clipboard-0.25.0.tgz",
|
||||
"integrity": "sha512-z0Dx6fDSLfbfK/LsfjkFbOTO87kHXQ6FNi8eCvVHtMLnME91kHTaotIalEdlS69Hw6032AThnEqeN5rAB24BlQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/html": "0.25.0",
|
||||
"@lexical/list": "0.25.0",
|
||||
"@lexical/selection": "0.25.0",
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/code": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/code/-/code-0.25.0.tgz",
|
||||
"integrity": "sha512-jTUFIYbbsud4qdLV+zAYj1UhzC2LiKSly5uprsJgTvBwdZppexcNOiHFvH1kEODVXVSLgU6WCg0XROPB+fXh9A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0",
|
||||
"prismjs": "^1.27.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/devtools-core": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/devtools-core/-/devtools-core-0.25.0.tgz",
|
||||
"integrity": "sha512-DJl5reXPdohZulAfemZCzhkglJfSJnQbu7bAtBMhUx0U0t51YOycCqXcKeXwNge74h3T3aG4/N4fPV50Cq1izA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/html": "0.25.0",
|
||||
"@lexical/link": "0.25.0",
|
||||
"@lexical/mark": "0.25.0",
|
||||
"@lexical/table": "0.25.0",
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=17.x",
|
||||
"react-dom": ">=17.x"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/dragon": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/dragon/-/dragon-0.25.0.tgz",
|
||||
"integrity": "sha512-mMMX2clk8nQHZEgPuVlTOPYMCH0Kg4EevJ4dg6q5sGJzkHjXerooGm+PYfLEcOk7SQC0YOhvW7gkM/UQYYHHWA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/hashtag": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/hashtag/-/hashtag-0.25.0.tgz",
|
||||
"integrity": "sha512-di9pcBeCS/hx5z4EudOp7J6m4bNVqxVzm4J/15D4WDz6Jen3dh2Jha0N2pmFuHbOiuLyPAhYAV4PacFi5+ne+w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/history": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/history/-/history-0.25.0.tgz",
|
||||
"integrity": "sha512-mUkXhVZDbgUYkpjFLcMDSOorOVeX/l2eV2wxnju9hjodGenEfVK1yWv1A2siCiG0K9y8o1Eksa4F7zf3ZlXRuA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/html": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/html/-/html-0.25.0.tgz",
|
||||
"integrity": "sha512-bjO5RbMpyFw4H6kCgYcdAlxzhoF1tjtRZ1w0MxSHReLg9wqNaeg4uNwdW+uVMbxRv+cYqaO0To66qMAcND6tiQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/selection": "0.25.0",
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/link": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/link/-/link-0.25.0.tgz",
|
||||
"integrity": "sha512-epFwgLWfmYgtXgI1n7oJJ3ana48qTm+WHEAYnFK7mxXEV6V93j5hm3MJgAJL4Lut/iHkrBXhT9PVMwkg75ImRQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/list": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/list/-/list-0.25.0.tgz",
|
||||
"integrity": "sha512-hAEcNuE9WxDHJGUcwkTN+4sGn1/j5/wBqkuaYrBrhf7vCHeKUAu7er7T7Gdfj1HPfjqZm6YxdqFF4LYqejwuRg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/mark": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/mark/-/mark-0.25.0.tgz",
|
||||
"integrity": "sha512-J3T35abTjvri5rq+3P/exWdB6uHTQDmAi3gy1PkHSGLODhfKypo1gZdFY80QZmxcR9yewhMr9d9o5YwRsfZqSw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/markdown": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/markdown/-/markdown-0.25.0.tgz",
|
||||
"integrity": "sha512-KHj/AdjJIzCYtWRPyb8LjPo19gqGuLHu5Q3S2+n1OgCEwhpemPFHQPGk8AGd21jyF4h2psAe7d7ikMQj81wOrw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/code": "0.25.0",
|
||||
"@lexical/link": "0.25.0",
|
||||
"@lexical/list": "0.25.0",
|
||||
"@lexical/rich-text": "0.25.0",
|
||||
"@lexical/text": "0.25.0",
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/offset": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/offset/-/offset-0.25.0.tgz",
|
||||
"integrity": "sha512-3qcqMb07OyA174nB/ghWCj6fgGSPlqjYNzJ75xuvg1n8S3RpobDarin2iEEUb/n74wA4w5fwufJPe/Nu0NRJ/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/overflow": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/overflow/-/overflow-0.25.0.tgz",
|
||||
"integrity": "sha512-TEgn3HMx1pNI3VwlPcmFo29H+yLKvuX+zNlvdGwQh6tHHvw7DEyJ7iAuK74V4UZZT2bWcOr0ZArBYSDV/9bZtQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/plain-text": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/plain-text/-/plain-text-0.25.0.tgz",
|
||||
"integrity": "sha512-k0SG0mmsF/pKsvMMSnilysfu22NqapaNtJHtF3QPvOv8ryDuILm9HgwD8svALVvR9BI8PeCSspnoVKEELwVzCw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/clipboard": "0.25.0",
|
||||
"@lexical/selection": "0.25.0",
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/react": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/react/-/react-0.25.0.tgz",
|
||||
"integrity": "sha512-cdrwfNyknAwbFyO+3vUDjRADJ/3yckVeUKrZSQN32/71kdIas4OXYDYbPNdsUVEiIvicTkQJof8naG+cj9LtTQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/clipboard": "0.25.0",
|
||||
"@lexical/code": "0.25.0",
|
||||
"@lexical/devtools-core": "0.25.0",
|
||||
"@lexical/dragon": "0.25.0",
|
||||
"@lexical/hashtag": "0.25.0",
|
||||
"@lexical/history": "0.25.0",
|
||||
"@lexical/link": "0.25.0",
|
||||
"@lexical/list": "0.25.0",
|
||||
"@lexical/mark": "0.25.0",
|
||||
"@lexical/markdown": "0.25.0",
|
||||
"@lexical/overflow": "0.25.0",
|
||||
"@lexical/plain-text": "0.25.0",
|
||||
"@lexical/rich-text": "0.25.0",
|
||||
"@lexical/selection": "0.25.0",
|
||||
"@lexical/table": "0.25.0",
|
||||
"@lexical/text": "0.25.0",
|
||||
"@lexical/utils": "0.25.0",
|
||||
"@lexical/yjs": "0.25.0",
|
||||
"lexical": "0.25.0",
|
||||
"react-error-boundary": "^3.1.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=17.x",
|
||||
"react-dom": ">=17.x"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/rich-text": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/rich-text/-/rich-text-0.25.0.tgz",
|
||||
"integrity": "sha512-cNQeqKtJGnAp1ndRlohGoWcEE59WS17bfjMmPbbHbWUSlvFMIsa/7GopauW4KyuEjFkNNhDVEB21r1zDX97unA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/clipboard": "0.25.0",
|
||||
"@lexical/selection": "0.25.0",
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/selection": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/selection/-/selection-0.25.0.tgz",
|
||||
"integrity": "sha512-zbUflzM5bAER5JyDXNbaw4s9w5kp8Y2oYqpplkZhMXj8Ri3CUE5bQgt4vH6XbyKVl4hsJlVcZ3qmw3HJAcnWNQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/table": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/table/-/table-0.25.0.tgz",
|
||||
"integrity": "sha512-gWOvqyz1eGv504fxH7r0hZACYgxEldr5GlzS2GoII3S1OjGhEOjBkM5JNMzATFaxvfdUkL2ywbmBfhk5hI/spg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/clipboard": "0.25.0",
|
||||
"@lexical/utils": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/text": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/text/-/text-0.25.0.tgz",
|
||||
"integrity": "sha512-u5WtmkbYYMePRQGAMFKqtbq4JhEMtSFwPYvtbS/5WUoYBf55IE+0kQA3meMK9MqBsxWil6TTekWOnKYmoLXv4w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/utils": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/utils/-/utils-0.25.0.tgz",
|
||||
"integrity": "sha512-LAB/5OniVCDFMWh8zuKejqU4blAP5CEIpPXBtevbHROtbz3fqo/xqcHK3bGGP9w1UKYH0S6n+MA8Uv9hdVzf7w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/list": "0.25.0",
|
||||
"@lexical/selection": "0.25.0",
|
||||
"@lexical/table": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lexical/yjs": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/@lexical/yjs/-/yjs-0.25.0.tgz",
|
||||
"integrity": "sha512-fRXLfwt7Qp897GqRnzQ5Ew+kWaFmdixRtD3BhGoMh8/KfvccbFeL7M4d29KbQe+jOWljlpO57X1sKBZ/OWNjJw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lexical/offset": "0.25.0",
|
||||
"@lexical/selection": "0.25.0",
|
||||
"lexical": "0.25.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"yjs": ">=13.5.22"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodelib/fs.scandir": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
|
||||
@@ -4608,6 +4871,17 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/isomorphic.js": {
|
||||
"version": "0.2.5",
|
||||
"resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz",
|
||||
"integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
},
|
||||
"node_modules/istanbul-lib-coverage": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
|
||||
@@ -4847,6 +5121,34 @@
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lexical": {
|
||||
"version": "0.25.0",
|
||||
"resolved": "https://registry.npmjs.org/lexical/-/lexical-0.25.0.tgz",
|
||||
"integrity": "sha512-yZNfC+3Df/qGAbGD1Lsh+dkG0COJKGuDlT1e/t0qS9F1jaKvoz7Fm0tACQ3eRTbOYncJiaJveLiT9GADac2hrA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lib0": {
|
||||
"version": "0.2.119",
|
||||
"resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.119.tgz",
|
||||
"integrity": "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"isomorphic.js": "^0.2.4"
|
||||
},
|
||||
"bin": {
|
||||
"0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js",
|
||||
"0gentesthtml": "bin/gentesthtml.js",
|
||||
"0serve": "bin/0serve.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
},
|
||||
"node_modules/lilconfig": {
|
||||
"version": "3.1.4",
|
||||
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.4.tgz",
|
||||
@@ -5799,6 +6101,15 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/prismjs": {
|
||||
"version": "1.30.0",
|
||||
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",
|
||||
"integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/prop-types": {
|
||||
"version": "15.8.1",
|
||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||
@@ -5894,6 +6205,22 @@
|
||||
"react": "^18.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/react-error-boundary": {
|
||||
"version": "3.1.4",
|
||||
"resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-3.1.4.tgz",
|
||||
"integrity": "sha512-uM9uPzZJTF6wRQORmSrvOIgt4lJ9MC1sNgEOj2XGsDTRE4kmpWxg7ENK9EWNKJRMAOY9z0MuF4yIfl6gp4sotA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10",
|
||||
"npm": ">=6"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.13.1"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "17.0.2",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
|
||||
@@ -7579,6 +7906,24 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yjs": {
|
||||
"version": "13.6.33",
|
||||
"resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz",
|
||||
"integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"lib0": "^0.2.99"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0",
|
||||
"npm": ">=8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
},
|
||||
"node_modules/yocto-queue": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||
|
||||
@@ -20,8 +20,16 @@
|
||||
"lint": "eslint . --ext .js,.jsx,.ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"@lexical/code": "^0.25.0",
|
||||
"@lexical/html": "^0.25.0",
|
||||
"@lexical/link": "^0.25.0",
|
||||
"@lexical/list": "^0.25.0",
|
||||
"@lexical/react": "^0.25.0",
|
||||
"@lexical/rich-text": "^0.25.0",
|
||||
"@lexical/selection": "^0.25.0",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.0",
|
||||
"lexical": "^0.25.0",
|
||||
"lucide-react": "^0.263.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
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;
|
||||
content: string;
|
||||
author_id: number;
|
||||
category_id: number;
|
||||
created_at: string;
|
||||
published: boolean;
|
||||
author: WireAuthor;
|
||||
category: WireCategory;
|
||||
};
|
||||
|
||||
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' },
|
||||
];
|
||||
|
||||
function seedArticles(): WireArticle[] {
|
||||
return [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Fusion milestone: net energy gain repeated',
|
||||
content:
|
||||
'<p>Scientists again drew net energy from the reactor, marking the third repeat of the landmark result.</p>',
|
||||
author_id: 2,
|
||||
category_id: 2,
|
||||
created_at: '2024-05-03T11:30:00Z',
|
||||
published: true,
|
||||
author: AUTHORS[1],
|
||||
category: CATEGORIES[1],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'City marathon sets record turnout',
|
||||
content:
|
||||
'<p>First-timers flooded the course on Sunday as organizers beat last year\u2019s turnout.</p>',
|
||||
author_id: 3,
|
||||
category_id: 3,
|
||||
created_at: '2024-05-02T09:15:00Z',
|
||||
published: false,
|
||||
author: AUTHORS[2],
|
||||
category: CATEGORIES[2],
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Inside the new wave of open-source language models',
|
||||
content:
|
||||
'<p>Open-weight language models are reshaping who can build and deploy AI.</p>',
|
||||
author_id: 1,
|
||||
category_id: 1,
|
||||
created_at: '2024-05-01T10:00:00Z',
|
||||
published: true,
|
||||
author: AUTHORS[0],
|
||||
category: CATEGORIES[0],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
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: JSON.stringify({ detail: 'Not authenticated', code: 'unauthorized' }),
|
||||
});
|
||||
}
|
||||
if (opts.admin === false) {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ id: 2, username: 'user', is_admin: false }),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ id: 1, username: 'admin', is_admin: true }),
|
||||
});
|
||||
});
|
||||
|
||||
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';
|
||||
const sortOrder = url.searchParams.get('sort_order') ?? 'desc';
|
||||
const page = Number(url.searchParams.get('page') ?? '1');
|
||||
const pageSize = Number(url.searchParams.get('page_size') ?? '20');
|
||||
|
||||
const filtered = store.filter(
|
||||
(a) => !search || a.title.toLowerCase().includes(search) || a.content.toLowerCase().includes(search),
|
||||
);
|
||||
const direction = sortOrder === 'asc' ? 1 : -1;
|
||||
filtered.sort((a, b) => {
|
||||
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 slice = filtered.slice(start, start + pageSize);
|
||||
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
articles: slice,
|
||||
total: filtered.length,
|
||||
page,
|
||||
page_size: pageSize,
|
||||
total_pages: Math.max(1, Math.ceil(filtered.length / pageSize)),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
if (method === 'POST') {
|
||||
const body = JSON.parse(route.request().postData() ?? '{}') as {
|
||||
title: string;
|
||||
content: string;
|
||||
author_id: number;
|
||||
category_id: number;
|
||||
published: boolean;
|
||||
};
|
||||
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(article),
|
||||
});
|
||||
}
|
||||
|
||||
return route.fulfill({
|
||||
status: 405,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ detail: 'Method not allowed', code: 'method_not_allowed' }),
|
||||
});
|
||||
});
|
||||
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
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('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.getByText(/does not have access to the admin area/i),
|
||||
).toBeVisible();
|
||||
await expect(page).toHaveURL('/admin');
|
||||
});
|
||||
|
||||
test('renders the admin dashboard with all articles and the Admin header link', async ({
|
||||
page,
|
||||
}) => {
|
||||
const { token, count } = await mockAdminApi(page, { admin: true });
|
||||
await page.addInitScript(
|
||||
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||
token,
|
||||
);
|
||||
|
||||
await page.goto('/admin');
|
||||
|
||||
// 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('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 page.waitForTimeout(200);
|
||||
await expect(page.getByRole('link', { name: /^admin$/i })).toHaveCount(0);
|
||||
});
|
||||
|
||||
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('Fusion milestone: net energy gain repeated')).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('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 firstCell = () => page.locator('tbody tr').first().locator('td').first();
|
||||
const titleButton = page.getByRole('button', { name: /sort by title/i });
|
||||
|
||||
// Default ordering is newest first (created_at desc).
|
||||
await expect(firstCell()).toContainText('Fusion milestone: net energy gain repeated');
|
||||
|
||||
// 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('creates an article with the Lexical editor and navigates back', async ({
|
||||
page,
|
||||
}) => {
|
||||
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 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(/^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.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();
|
||||
|
||||
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.');
|
||||
});
|
||||
|
||||
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
|
||||
.getByRole('row', { name: /Fusion milestone: net energy gain repeated/ })
|
||||
.getByRole('link', { name: /edit/i })
|
||||
.click();
|
||||
|
||||
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 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();
|
||||
|
||||
expect(byId(1)?.title).toBe('Fusion milestone: record energy gain');
|
||||
expect(byId(1)?.published).toBe(true);
|
||||
expect(byId(1)?.author_id).toBe(2);
|
||||
});
|
||||
|
||||
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 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.getByRole('heading', { name: /are you sure you want to delete/i }),
|
||||
).toBeVisible();
|
||||
await expect(dialog).toContainText('City marathon sets record turnout');
|
||||
await expect(dialog).toContainText(/cannot be undone/i);
|
||||
|
||||
// Cancel: nothing is deleted.
|
||||
await dialog.getByRole('button', { name: /cancel/i }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
expect(count()).toBe(3);
|
||||
expect(all()).toEqual([1, 2, 3]);
|
||||
|
||||
// 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.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 controls stay disabled with a single page', 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('Showing 1–3 of 3')).toBeVisible();
|
||||
|
||||
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 = [
|
||||
'<p>Safe <strong>text</strong></p>',
|
||||
'<script>alert(1)</script>',
|
||||
'<img src="x" onerror="alert(1)"/>',
|
||||
'<svg onload="alert(1)"></svg>',
|
||||
'<a href="javascript:alert(1)">click</a>',
|
||||
].join('');
|
||||
|
||||
const dialogs: string[] = [];
|
||||
const pageErrors: string[] = [];
|
||||
page.on('dialog', (dialog) => {
|
||||
dialogs.push(dialog.message());
|
||||
void dialog.dismiss();
|
||||
});
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
|
||||
await page.addInitScript(
|
||||
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||
mock.token,
|
||||
);
|
||||
await page.goto('/admin/articles/1/edit');
|
||||
|
||||
const editable = page.getByLabel('Article content');
|
||||
await expect(editable).toContainText('Safe');
|
||||
|
||||
const html = await editable.evaluate(
|
||||
(el) => (el as HTMLElement).innerHTML,
|
||||
);
|
||||
expect(html).not.toContain('<script');
|
||||
expect(html).not.toContain('onerror');
|
||||
expect(html).not.toContain('onload');
|
||||
expect(html).not.toContain('javascript:');
|
||||
// The legitimate content survives the round trip.
|
||||
expect(html).toContain('<strong');
|
||||
// Nothing executed in the page.
|
||||
expect(dialogs).toHaveLength(0);
|
||||
expect(pageErrors).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
|
||||
const TOKEN = 'mock-jwt-token';
|
||||
|
||||
const envelope = (detail: string, code: string) => JSON.stringify({ detail, code });
|
||||
|
||||
/**
|
||||
* Mock the auth API so the flows do not depend on a running backend
|
||||
* (same approach as api.spec.ts). The "server" accepts:
|
||||
* - register: any username except `taken`, any password
|
||||
* - login: alice / password123
|
||||
* - me: the mock token -> user `alice`
|
||||
*/
|
||||
function mockAuthApi(page: Page): void {
|
||||
page.route('**/api/v1/auth/register', (route) => {
|
||||
const body = route.request().postDataJSON();
|
||||
if (body.username === 'taken') {
|
||||
return route.fulfill({
|
||||
status: 400,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Username already exists', 'bad_request'),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 201,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ token: TOKEN, username: body.username }),
|
||||
});
|
||||
});
|
||||
|
||||
page.route('**/api/v1/auth/login', (route) => {
|
||||
const body = route.request().postDataJSON();
|
||||
if (body.username !== 'alice' || body.password !== 'password123') {
|
||||
return route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Invalid username or password', 'unauthorized'),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ token: TOKEN, username: body.username }),
|
||||
});
|
||||
});
|
||||
|
||||
page.route('**/api/v1/auth/me', (route) => {
|
||||
const header = route.request().headers()['authorization'];
|
||||
if (header !== `Bearer ${TOKEN}`) {
|
||||
return route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Invalid or expired token', 'unauthorized'),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ username: 'alice' }),
|
||||
});
|
||||
});
|
||||
|
||||
page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 }));
|
||||
}
|
||||
|
||||
/** Store a session token before the app boots (session-restore tests). */
|
||||
async function seedToken(page: Page, token: string): Promise<void> {
|
||||
await page.addInitScript((value) => localStorage.setItem('AUTH_TOKEN', value), token);
|
||||
}
|
||||
|
||||
const readToken = (page: Page) => page.evaluate(() => localStorage.getItem('AUTH_TOKEN'));
|
||||
|
||||
const accountNav = (page: Page) => page.getByRole('navigation', { name: 'Account' });
|
||||
|
||||
test.describe('auth flows', () => {
|
||||
test('register: creates an account, stores the token and signs the user in', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/register');
|
||||
await page.getByLabel('Username').fill('newuser');
|
||||
await page.getByLabel('Password', { exact: true }).fill('password123');
|
||||
await page.getByLabel('Confirm password').fill('password123');
|
||||
await page.getByRole('button', { name: /register/i }).click();
|
||||
|
||||
// Registration auto-signs in and redirects to home.
|
||||
await expect(page).toHaveURL('/');
|
||||
expect(await readToken(page)).toBe(TOKEN);
|
||||
await expect(accountNav(page).getByText('newuser')).toBeVisible();
|
||||
await expect(accountNav(page).getByRole('link', { name: /sign out/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('register: rejects a duplicate username with the backend error', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/register');
|
||||
await page.getByLabel('Username').fill('taken');
|
||||
await page.getByLabel('Password', { exact: true }).fill('password123');
|
||||
await page.getByLabel('Confirm password').fill('password123');
|
||||
await page.getByRole('button', { name: /register/i }).click();
|
||||
|
||||
await expect(page.getByRole('alert')).toContainText('Username already exists');
|
||||
expect(await readToken(page)).toBeNull();
|
||||
await expect(page).toHaveURL('/register');
|
||||
});
|
||||
|
||||
test('register: validates mismatched passwords client-side', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/register');
|
||||
await page.getByLabel('Username').fill('newuser');
|
||||
await page.getByLabel('Password', { exact: true }).fill('password123');
|
||||
await page.getByLabel('Confirm password').fill('different123');
|
||||
await page.getByRole('button', { name: /register/i }).click();
|
||||
|
||||
await expect(page.getByRole('alert')).toContainText('Passwords do not match.');
|
||||
expect(await readToken(page)).toBeNull();
|
||||
});
|
||||
|
||||
test('login: stores the token and signs the user in', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Username').fill('alice');
|
||||
await page.getByLabel('Password').fill('password123');
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
|
||||
await expect(page).toHaveURL('/');
|
||||
expect(await readToken(page)).toBe(TOKEN);
|
||||
await expect(accountNav(page).getByText('alice')).toBeVisible();
|
||||
});
|
||||
|
||||
test('login: shows the backend error for invalid credentials', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Username').fill('alice');
|
||||
await page.getByLabel('Password').fill('wrong-password');
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
|
||||
await expect(page.getByRole('alert')).toContainText('Invalid username or password');
|
||||
expect(await readToken(page)).toBeNull();
|
||||
await expect(page).toHaveURL('/login');
|
||||
});
|
||||
|
||||
test('restores the session from a stored token on page load', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
await seedToken(page, TOKEN);
|
||||
|
||||
await page.goto('/');
|
||||
|
||||
await expect(accountNav(page).getByText('alice')).toBeVisible();
|
||||
expect(await readToken(page)).toBe(TOKEN);
|
||||
});
|
||||
|
||||
test('clears an invalid stored token on page load', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
await seedToken(page, 'expired-or-forged-token');
|
||||
|
||||
await page.goto('/');
|
||||
|
||||
// Restore failed -> signed-out header, token removed.
|
||||
await expect(accountNav(page).getByRole('link', { name: 'Sign in' })).toBeVisible();
|
||||
expect(await readToken(page)).toBeNull();
|
||||
});
|
||||
|
||||
test('redirects unauthenticated users from /account to /login', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
|
||||
await page.goto('/account');
|
||||
|
||||
await expect(page).toHaveURL('/login');
|
||||
});
|
||||
|
||||
test('renders the protected /account page for a signed-in user', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
await seedToken(page, TOKEN);
|
||||
|
||||
await page.goto('/account');
|
||||
|
||||
await expect(page.getByTestId('account-page')).toBeVisible();
|
||||
await expect(page.getByRole('heading', { level: 1, name: 'Account' })).toBeVisible();
|
||||
await expect(page.getByTestId('account-page').getByText('alice')).toBeVisible();
|
||||
});
|
||||
|
||||
test('sign out clears the token and returns to the login page', async ({ page }) => {
|
||||
mockAuthApi(page);
|
||||
await seedToken(page, TOKEN);
|
||||
|
||||
await page.goto('/');
|
||||
await accountNav(page).getByRole('link', { name: /sign out/i }).click();
|
||||
|
||||
await expect(page).toHaveURL('/login');
|
||||
expect(await readToken(page)).toBeNull();
|
||||
await expect(page.getByRole('status').getByText(/signed out/i)).toBeVisible();
|
||||
});
|
||||
});
|
||||
+60
-10
@@ -1,8 +1,16 @@
|
||||
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
|
||||
import { AuthProvider, RequireAdmin, RequireAuth } from './auth';
|
||||
import AdminLayout from './components/AdminLayout';
|
||||
import Layout from './components/ui/Layout';
|
||||
import Account from './pages/Account';
|
||||
import AdminDashboard from './pages/AdminDashboard';
|
||||
import ArticlePage from './pages/ArticlePage';
|
||||
import CategoriesPage from './pages/CategoriesPage';
|
||||
import EditArticlePage from './pages/EditArticlePage';
|
||||
import Home from './pages/Home';
|
||||
import Login from './pages/Login';
|
||||
import Register from './pages/Register';
|
||||
import SignOut from './pages/SignOut';
|
||||
|
||||
/** 404 fallback for unknown routes. */
|
||||
function NotFound() {
|
||||
@@ -20,10 +28,17 @@ function NotFound() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Root component: owns the React Router setup.
|
||||
* Root component: owns the React Router + auth setup.
|
||||
*
|
||||
* BrowserRouter wraps the whole app; AuthProvider restores the JWT
|
||||
* session and exposes login/register/logout (see src/auth.tsx).
|
||||
*
|
||||
* Two shells are used:
|
||||
* - the admin area (`/admin/*`, M6) renders inside its own dark sidebar
|
||||
* layout (`AdminLayout`) and is guarded by `RequireAdmin`;
|
||||
* - everything else renders inside the public site `Layout`
|
||||
* (header/footer) with `RequireAuth` guarding the account page.
|
||||
*
|
||||
* BrowserRouter wraps the whole app; Layout provides the shared shell
|
||||
* (header/footer); Routes maps URLs to page components in src/pages/.
|
||||
* In-app navigation always uses react-router-dom <Link>/<NavLink>.
|
||||
*/
|
||||
export default function App() {
|
||||
@@ -34,15 +49,50 @@ export default function App() {
|
||||
v7_relativeSplatPath: true,
|
||||
}}
|
||||
>
|
||||
<Layout>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/articles" element={<ArticlePage />} />
|
||||
<Route path="/articles/:id" element={<ArticlePage />} />
|
||||
<Route path="/categories" element={<CategoriesPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
{/* Admin area (own shell, admin-only) */}
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<RequireAdmin>
|
||||
<AdminLayout />
|
||||
</RequireAdmin>
|
||||
}
|
||||
>
|
||||
<Route index element={<AdminDashboard />} />
|
||||
<Route path="articles/new" element={<EditArticlePage />} />
|
||||
<Route path="articles/:id/edit" element={<EditArticlePage />} />
|
||||
</Route>
|
||||
|
||||
{/* Public site */}
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/articles" element={<ArticlePage />} />
|
||||
<Route path="/articles/:id" element={<ArticlePage />} />
|
||||
<Route path="/categories" element={<CategoriesPage />} />
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/sign-out" element={<SignOut />} />
|
||||
<Route
|
||||
path="/account"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<Account />
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</Layout>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 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
|
||||
* `is_admin` flag server-side; non-admins receive 403 (see the backend
|
||||
* `api/v1/admin.py`).
|
||||
*/
|
||||
import { api } from './client';
|
||||
import type { Author, Category } from '../types';
|
||||
import type {
|
||||
AdminArticle,
|
||||
AdminArticleInput,
|
||||
AdminArticlesPage,
|
||||
AdminListParams,
|
||||
} from '../types/admin';
|
||||
|
||||
/** `GET /api/v1/admin/articles` — paginated, searchable, sortable list. */
|
||||
export function adminListArticles(
|
||||
params: AdminListParams,
|
||||
): Promise<AdminArticlesPage> {
|
||||
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<AdminArticlesPage>(`/admin/articles?${query.toString()}`);
|
||||
}
|
||||
|
||||
/** `GET /api/v1/admin/articles/{id}` — a single article (with author + category). */
|
||||
export function adminGetArticle(id: number): Promise<AdminArticle> {
|
||||
return api.get<AdminArticle>(`/admin/articles/${id}`);
|
||||
}
|
||||
|
||||
/** `POST /api/v1/admin/articles` — create a new article. */
|
||||
export function adminCreateArticle(input: AdminArticleInput): Promise<AdminArticle> {
|
||||
return api.post<AdminArticle>('/admin/articles', input);
|
||||
}
|
||||
|
||||
/** `PUT /api/v1/admin/articles/{id}` — update an article. */
|
||||
export function adminUpdateArticle(
|
||||
id: number,
|
||||
input: AdminArticleInput,
|
||||
): Promise<AdminArticle> {
|
||||
return api.put<AdminArticle>(`/admin/articles/${id}`, input);
|
||||
}
|
||||
|
||||
/** `DELETE /api/v1/admin/articles/{id}` — hard-delete an article (204). */
|
||||
export function adminDeleteArticle(id: number): Promise<void> {
|
||||
return api.delete<void>(`/admin/articles/${id}`);
|
||||
}
|
||||
|
||||
/** `GET /api/v1/admin/authors` — reference list for the article form. */
|
||||
export function adminListAuthors(): Promise<Author[]> {
|
||||
return api.get<Author[]>('/admin/authors');
|
||||
}
|
||||
|
||||
/** `GET /api/v1/admin/categories` — reference list for the article form. */
|
||||
export function adminListCategories(): Promise<Category[]> {
|
||||
return api.get<Category[]>('/admin/categories');
|
||||
}
|
||||
@@ -16,10 +16,14 @@ import type {
|
||||
HealthResponse,
|
||||
VersionResponse,
|
||||
} from '../types';
|
||||
import type { MeResponse, TokenResponse } from '../types/auth';
|
||||
|
||||
export const API_BASE_URL: string =
|
||||
(import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '/api/v1';
|
||||
|
||||
/** localStorage key under which the JWT session token is persisted. */
|
||||
export const TOKEN_KEY = 'AUTH_TOKEN';
|
||||
|
||||
/** Error thrown for failed API requests (network or non-2xx responses). */
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
@@ -36,6 +40,8 @@ export class ApiError extends Error {
|
||||
interface RequestOptions extends Omit<RequestInit, 'body'> {
|
||||
/** JSON-serializable request body (stringified automatically). */
|
||||
body?: unknown;
|
||||
/** Use this Bearer token instead of the one stored under TOKEN_KEY. */
|
||||
token?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,15 +49,19 @@ interface RequestOptions extends Omit<RequestInit, 'body'> {
|
||||
* response and converts failures into `ApiError`.
|
||||
*/
|
||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { body, headers, ...rest } = options;
|
||||
const { body, headers, token, ...rest } = options;
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
// Attach the JWT (explicit override or the stored session) so the
|
||||
// backend can identify the caller on protected endpoints.
|
||||
const bearer = token ?? localStorage.getItem(TOKEN_KEY);
|
||||
response = await fetch(`${API_BASE_URL}${path}`, {
|
||||
...rest,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
||||
...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),
|
||||
...headers,
|
||||
},
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
@@ -61,6 +71,9 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
// 401: the stored session is invalid/expired — drop it so the UI can
|
||||
// redirect to login instead of retrying with a dead token.
|
||||
if (response.status === 401) localStorage.removeItem(TOKEN_KEY);
|
||||
let payload: ApiErrorPayload | null = null;
|
||||
try {
|
||||
payload = (await response.json()) as ApiErrorPayload;
|
||||
@@ -159,11 +172,33 @@ export function getVersion(): Promise<VersionResponse> {
|
||||
return api.get<VersionResponse>('/version');
|
||||
}
|
||||
|
||||
/* --- Auth endpoints (JWT sessions, see `src/auth.tsx`) ------------------- */
|
||||
|
||||
/** `POST /api/v1/auth/register` — create an account; returns the JWT. */
|
||||
export function register(username: string, password: string): Promise<TokenResponse> {
|
||||
return api.post<TokenResponse>('/auth/register', { username, password });
|
||||
}
|
||||
|
||||
/** `POST /api/v1/auth/login` — authenticate; returns the JWT. */
|
||||
export function login(username: string, password: string): Promise<TokenResponse> {
|
||||
return api.post<TokenResponse>('/auth/login', { username, password });
|
||||
}
|
||||
|
||||
/** `GET /api/v1/auth/me` — current user for the explicit (or stored) token. */
|
||||
export function me(token?: string): Promise<MeResponse> {
|
||||
return api.get<MeResponse>('/auth/me', token !== undefined ? { token } : undefined);
|
||||
}
|
||||
|
||||
/** `POST /api/v1/auth/logout` — stateless; the client discards the token. */
|
||||
export function logout(): Promise<void> {
|
||||
return api.post<void>('/auth/logout', undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* `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<Article[]> {
|
||||
return api.get<BackendArticle[]>('/articles').then((articles) =>
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
/* ==========================================================================
|
||||
newzy admin area (M6)
|
||||
Admin shell (fixed sidebar + main content) and Lexical editor content.
|
||||
Loaded after globals.css; scoped under .admin-shell / .lex-editor.
|
||||
========================================================================== */
|
||||
|
||||
/* --- Admin shell ---------------------------------------------------------- */
|
||||
|
||||
.admin-shell {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
/* Sidebar: fixed 250px column on desktop, slide-in overlay on mobile. */
|
||||
.admin-sidebar {
|
||||
width: 250px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #0f172a;
|
||||
color: #cbd5e1;
|
||||
padding: 1rem 0.75rem;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
z-index: 50;
|
||||
}
|
||||
|
||||
.admin-sidebar__brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.25rem 0.75rem 1rem;
|
||||
font-size: 1.05rem;
|
||||
font-weight: 700;
|
||||
color: #f8fafc;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.admin-sidebar__brand span {
|
||||
opacity: 0.6;
|
||||
font-weight: 500;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.admin-sidebar__nav {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.admin-sidebar__link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
padding: 0.55rem 0.75rem;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: #cbd5e1;
|
||||
transition: background-color 150ms, color 150ms;
|
||||
}
|
||||
|
||||
.admin-sidebar__link:hover {
|
||||
background: #1e293b;
|
||||
color: #f8fafc;
|
||||
}
|
||||
|
||||
.admin-sidebar__link.is-active {
|
||||
background: #1d4ed8;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.admin-sidebar__footer {
|
||||
border-top: 1px solid #1e293b;
|
||||
padding-top: 0.75rem;
|
||||
margin-top: 0.75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.admin-sidebar__user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0 0.75rem;
|
||||
font-size: 0.8rem;
|
||||
color: #94a3b8;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.admin-sidebar__user strong {
|
||||
color: #e2e8f0;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Main content: offset by the sidebar on desktop. */
|
||||
.admin-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 2rem 2rem 3rem;
|
||||
}
|
||||
|
||||
.admin-main__inner {
|
||||
max-width: 56rem;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* Mobile top bar with the sidebar toggle (< md). */
|
||||
.admin-mobilebar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.admin-sidebar {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
transform: translateX(-100%);
|
||||
transition: transform 200ms ease-out;
|
||||
box-shadow: 0 0 40px rgba(15, 23, 42, 0.4);
|
||||
}
|
||||
|
||||
.admin-sidebar.is-open {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.admin-main {
|
||||
padding: 1rem 1rem 2.5rem;
|
||||
}
|
||||
|
||||
.admin-mobilebar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
padding: 0.65rem 1rem;
|
||||
background: #0f172a;
|
||||
color: #f8fafc;
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.admin-mobilebar__toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.4rem;
|
||||
border-radius: 0.5rem;
|
||||
color: #cbd5e1;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.admin-mobilebar__toggle:hover {
|
||||
background: #1e293b;
|
||||
color: #f8fafc;
|
||||
}
|
||||
|
||||
/* Backdrop behind the slide-in sidebar. */
|
||||
.admin-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(15, 23, 42, 0.5);
|
||||
z-index: 40;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Lexical editor -------------------------------------------------------- */
|
||||
|
||||
.lex-editor {
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.5rem;
|
||||
background: #ffffff;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.lex-editor__toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
padding: 0.4rem 0.5rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.lex-toolbar-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 1.9rem;
|
||||
height: 1.9rem;
|
||||
padding: 0 0.35rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
background: transparent;
|
||||
transition: background-color 120ms, color 120ms;
|
||||
}
|
||||
|
||||
.lex-toolbar-btn:hover {
|
||||
background: #e2e8f0;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.lex-toolbar-btn.is-active {
|
||||
background: #1d4ed8;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.lex-toolbar-btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.lex-toolbar-sep {
|
||||
width: 1px;
|
||||
height: 1.4rem;
|
||||
background: #e2e8f0;
|
||||
margin: 0 0.25rem;
|
||||
}
|
||||
|
||||
.lex-toolbar-select {
|
||||
height: 1.9rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
background: #ffffff;
|
||||
padding: 0 0.3rem;
|
||||
font-size: 0.8rem;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.lex-toolbar-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.lex-toolbar-link input {
|
||||
width: 11rem;
|
||||
height: 1.9rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid #bfdbfe;
|
||||
padding: 0 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
/* Editor content (Lexical theme classes are mapped to these). */
|
||||
.lex-editor__content {
|
||||
min-height: 14rem;
|
||||
max-height: 32rem;
|
||||
overflow-y: auto;
|
||||
padding: 1rem 1.25rem;
|
||||
outline: none;
|
||||
font-size: 0.925rem;
|
||||
line-height: 1.65;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.lex-editor__content p {
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.lex-editor__content h1 {
|
||||
font-size: 1.6rem;
|
||||
font-weight: 700;
|
||||
margin: 1rem 0 0.5rem;
|
||||
}
|
||||
|
||||
.lex-editor__content h2 {
|
||||
font-size: 1.35rem;
|
||||
font-weight: 700;
|
||||
margin: 0.9rem 0 0.4rem;
|
||||
}
|
||||
|
||||
.lex-editor__content h3 {
|
||||
font-size: 1.15rem;
|
||||
font-weight: 600;
|
||||
margin: 0.8rem 0 0.35rem;
|
||||
}
|
||||
|
||||
.lex-editor__content h4,
|
||||
.lex-editor__content h5,
|
||||
.lex-editor__content h6 {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 0.7rem 0 0.3rem;
|
||||
}
|
||||
|
||||
.lex-editor__content ul {
|
||||
list-style: disc;
|
||||
padding-left: 1.4rem;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.lex-editor__content ol {
|
||||
list-style: decimal;
|
||||
padding-left: 1.4rem;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.lex-editor__content a {
|
||||
color: #1d4ed8;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.lex-editor__content pre {
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
border-radius: 0.5rem;
|
||||
padding: 0.85rem 1rem;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.85rem;
|
||||
overflow-x: auto;
|
||||
margin: 0.75rem 0;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.lex-editor__content blockquote {
|
||||
border-left: 3px solid #cbd5e1;
|
||||
padding-left: 0.9rem;
|
||||
color: #475569;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
/* Placeholder for the empty editor. */
|
||||
.lex-editor__placeholder {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
color: #94a3b8;
|
||||
}
|
||||
@@ -31,4 +31,49 @@
|
||||
.btn-secondary {
|
||||
@apply inline-flex items-center justify-center gap-2 rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50;
|
||||
}
|
||||
|
||||
/* --- Auth pages (login / register / sign out) ------------------------- */
|
||||
|
||||
/* Centered wrapper so auth cards sit in the middle of the viewport. */
|
||||
.auth-wrap {
|
||||
@apply flex min-h-[60vh] items-center justify-center px-4 py-12;
|
||||
}
|
||||
|
||||
/* Card holding an auth form. */
|
||||
.auth-card {
|
||||
@apply w-full max-w-sm rounded-xl border border-slate-200 bg-white p-6 shadow-sm;
|
||||
}
|
||||
|
||||
/* Auth card heading (icon + label). */
|
||||
.auth-title {
|
||||
@apply mb-4 flex items-center gap-2 text-lg font-semibold text-slate-900;
|
||||
}
|
||||
|
||||
/* Form field: label stacked above its input. */
|
||||
.field {
|
||||
@apply mb-4;
|
||||
}
|
||||
|
||||
.field label {
|
||||
@apply mb-1 block text-sm font-medium text-slate-700;
|
||||
}
|
||||
|
||||
/* Text input used by the auth forms. */
|
||||
.input {
|
||||
@apply w-full rounded-md border border-slate-300 px-3 py-2 text-sm text-slate-900 placeholder:text-slate-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/40;
|
||||
}
|
||||
|
||||
/* Inline error/success notices inside auth cards. */
|
||||
.auth-error {
|
||||
@apply mb-3 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700;
|
||||
}
|
||||
|
||||
.auth-success {
|
||||
@apply mb-3 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700;
|
||||
}
|
||||
|
||||
/* Cross-link line at the bottom of an auth card. */
|
||||
.auth-alt {
|
||||
@apply mt-4 text-center text-sm text-slate-600;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* Authentication state for the app.
|
||||
*
|
||||
* - `AuthProvider` restores the session on load (validates the token
|
||||
* stored under `AUTH_TOKEN` against `GET /api/v1/auth/me`, drops it
|
||||
* when invalid/expired) and exposes `login` / `register` / `logout`.
|
||||
* - The JWT is attached to every API request automatically (see
|
||||
* `api/client.ts`); this module owns username, admin flag and ready
|
||||
* state.
|
||||
* - `RequireAuth` guards signed-in routes; `RequireAdmin` (M6)
|
||||
* additionally requires the `is_admin` flag and renders a 403 page
|
||||
* for authenticated non-admins.
|
||||
*/
|
||||
import {
|
||||
ReactNode,
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { Link, Navigate, useLocation } from 'react-router-dom';
|
||||
import {
|
||||
TOKEN_KEY,
|
||||
login as apiLogin,
|
||||
logout as apiLogout,
|
||||
me as apiMe,
|
||||
register as apiRegister,
|
||||
} from './api/client';
|
||||
|
||||
export interface AuthState {
|
||||
/** Logged-in username, or `null` when signed out. */
|
||||
username: string | null;
|
||||
/** Whether the signed-in user may access the admin area (M6). */
|
||||
isAdmin: boolean;
|
||||
/** `false` until the initial session-restore attempt has finished. */
|
||||
ready: boolean;
|
||||
/** Authenticate; stores the returned JWT and signs the user in. */
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
/** Register a new account; stores the returned JWT and signs in. */
|
||||
register: (username: string, password: string) => Promise<void>;
|
||||
/** Clear the stored token (best-effort server call) and sign out. */
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
// Restore the session on first load: validate the stored token and drop
|
||||
// it when the backend rejects it (expired, invalid or unknown user).
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(TOKEN_KEY);
|
||||
if (!stored) {
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
apiMe(stored)
|
||||
.then((user) => {
|
||||
setUsername(user.username);
|
||||
setIsAdmin(user.is_admin ?? false);
|
||||
})
|
||||
.catch(() => localStorage.removeItem(TOKEN_KEY))
|
||||
.finally(() => setReady(true));
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (name: string, password: string) => {
|
||||
const res = await apiLogin(name, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
setIsAdmin(res.is_admin ?? false);
|
||||
}, []);
|
||||
|
||||
const register = useCallback(async (name: string, password: string) => {
|
||||
const res = await apiRegister(name, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
setIsAdmin(res.is_admin ?? false);
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
// Best effort: the token is discarded client-side regardless of
|
||||
// whether the (stateless) server endpoint is reachable.
|
||||
apiLogout().catch(() => undefined);
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setUsername(null);
|
||||
setIsAdmin(false);
|
||||
}, []);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ username, isAdmin, ready, login, register, logout }),
|
||||
[username, isAdmin, ready, login, register, logout],
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth(): AuthState {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within <AuthProvider>');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route guard for authenticated users: shows a brief loading state while
|
||||
* the session is being restored, redirects to `/login` (remembering the
|
||||
* intended path in router state) when signed out, and renders `children`
|
||||
* otherwise.
|
||||
*/
|
||||
export function RequireAuth({ children }: { children: ReactNode }) {
|
||||
const { username, ready } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="container-page flex justify-center py-16" role="status">
|
||||
<span className="animate-pulse text-sm text-slate-500">Checking session…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (username === null) {
|
||||
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
|
||||
}
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route guard for the admin area (M6): behaves like `RequireAuth` but
|
||||
* additionally requires the `is_admin` flag. Authenticated non-admins
|
||||
* see a 403 page (the server enforces the same rule on every admin
|
||||
* endpoint, so this is UX, not security).
|
||||
*/
|
||||
export function RequireAdmin({ children }: { children: ReactNode }) {
|
||||
const { username, isAdmin, ready } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="container-page flex justify-center py-16" role="status">
|
||||
<span className="animate-pulse text-sm text-slate-500">Checking session…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (username === null) {
|
||||
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
|
||||
}
|
||||
if (!isAdmin) {
|
||||
return (
|
||||
<div className="container-page text-center" data-testid="forbidden-page" role="alert">
|
||||
<h1 className="mb-2 text-5xl font-bold text-slate-900">403</h1>
|
||||
<p className="mb-1 text-lg font-semibold text-slate-700">Forbidden</p>
|
||||
<p className="mb-6 text-sm text-slate-600">
|
||||
Your account does not have access to the admin area. Ask a site
|
||||
administrator if you believe this is a mistake.
|
||||
</p>
|
||||
<Link to="/" className="btn">
|
||||
Back to home
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Admin area shell (M6): dark fixed sidebar (250px) with navigation,
|
||||
* "back to newzy" link and the signed-in user, plus the routed page
|
||||
* content in the main area. Responsive: the sidebar becomes a slide-in
|
||||
* overlay with a mobile top bar below the `md` breakpoint.
|
||||
*
|
||||
* Routes are guarded by `RequireAdmin` (see `App.tsx`); this component
|
||||
* is pure presentation + navigation.
|
||||
*/
|
||||
import {
|
||||
ArrowLeft,
|
||||
LayoutDashboard,
|
||||
LogOut,
|
||||
Menu,
|
||||
Plus,
|
||||
ShieldCheck,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, NavLink, Outlet, useLocation } from 'react-router-dom';
|
||||
import { useAuth } from '../auth';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
export interface AdminLayoutProps {
|
||||
/** Extra classes for the outer shell. */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const sidebarLinkClasses = ({ isActive }: { isActive: boolean }): string =>
|
||||
cn('admin-sidebar__link', isActive && 'is-active');
|
||||
|
||||
/**
|
||||
* Layout wrapper for the `/admin` routes. Renders the sidebar, the
|
||||
* mobile top bar and the current route via `<Outlet/>`.
|
||||
*/
|
||||
export function AdminLayout({ className }: AdminLayoutProps) {
|
||||
const { username } = useAuth();
|
||||
const [mobileOpen, setMobileOpen] = useState(false);
|
||||
const location = useLocation();
|
||||
|
||||
// Close the mobile sidebar on route changes.
|
||||
useEffect(() => {
|
||||
setMobileOpen(false);
|
||||
}, [location.pathname]);
|
||||
|
||||
// Close on Escape while the mobile sidebar is open.
|
||||
useEffect(() => {
|
||||
if (!mobileOpen) return;
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') setMobileOpen(false);
|
||||
};
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => document.removeEventListener('keydown', onKey);
|
||||
}, [mobileOpen]);
|
||||
|
||||
return (
|
||||
<div className={cn('admin-shell', className)} data-testid="admin-layout">
|
||||
{mobileOpen && (
|
||||
<div
|
||||
className="admin-backdrop"
|
||||
aria-hidden="true"
|
||||
onClick={() => setMobileOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Mobile top bar (sidebar collapses on small screens) */}
|
||||
<div className="admin-mobilebar">
|
||||
<span className="flex items-center gap-2">
|
||||
<ShieldCheck size={18} aria-hidden="true" />
|
||||
newzy <span aria-hidden="true" style={{ opacity: 0.6 }}>admin</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-mobilebar__toggle"
|
||||
aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
|
||||
aria-expanded={mobileOpen}
|
||||
aria-controls="admin-sidebar"
|
||||
onClick={() => setMobileOpen((open) => !open)}
|
||||
>
|
||||
{mobileOpen ? <X size={20} aria-hidden="true" /> : <Menu size={20} aria-hidden="true" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<aside
|
||||
id="admin-sidebar"
|
||||
className={cn('admin-sidebar', mobileOpen && 'is-open')}
|
||||
aria-label="Admin navigation"
|
||||
>
|
||||
<div className="admin-sidebar__brand">
|
||||
<ShieldCheck size={18} aria-hidden="true" />
|
||||
newzy <span>admin</span>
|
||||
</div>
|
||||
|
||||
<nav className="admin-sidebar__nav">
|
||||
<NavLink to="/admin" end className={sidebarLinkClasses}>
|
||||
<LayoutDashboard size={16} aria-hidden="true" />
|
||||
<span>Articles</span>
|
||||
</NavLink>
|
||||
<NavLink to="/admin/articles/new" className={sidebarLinkClasses}>
|
||||
<Plus size={16} aria-hidden="true" />
|
||||
<span>New article</span>
|
||||
</NavLink>
|
||||
<Link to="/" className="admin-sidebar__link">
|
||||
<ArrowLeft size={16} aria-hidden="true" />
|
||||
<span>Back to newzy</span>
|
||||
</Link>
|
||||
</nav>
|
||||
|
||||
<div className="admin-sidebar__footer">
|
||||
<div className="admin-sidebar__user">
|
||||
<span aria-hidden="true" style={{ opacity: 0.7 }}>
|
||||
⚙
|
||||
</span>
|
||||
<span>
|
||||
Signed in as <strong>{username}</strong>
|
||||
</span>
|
||||
</div>
|
||||
<Link to="/sign-out" className="admin-sidebar__link">
|
||||
<LogOut size={16} aria-hidden="true" />
|
||||
<span>Sign out</span>
|
||||
</Link>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="admin-main" id="admin-main">
|
||||
<div className="admin-main__inner">
|
||||
<Outlet />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AdminLayout;
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Delete confirmation dialog (M6).
|
||||
*
|
||||
* A custom modal (no extra dependencies): centered overlay, warning
|
||||
* icon, explicit "Yes, delete" action and a Cancel fallback. Closes on
|
||||
* Escape and on overlay click, and ignores dismissal while the delete
|
||||
* request is in flight.
|
||||
*/
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { AdminArticle } from '../types/admin';
|
||||
|
||||
export interface DeleteConfirmationProps {
|
||||
/** The article about to be deleted. */
|
||||
article: AdminArticle;
|
||||
/** `true` while the delete request is in flight. */
|
||||
busy?: boolean;
|
||||
/** Error from a failed delete attempt (rendered above the actions). */
|
||||
error?: string | null;
|
||||
/** Trigger the (async) delete. */
|
||||
onConfirm: () => void;
|
||||
/** Dismiss the dialog without deleting. */
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function DeleteConfirmation({
|
||||
article,
|
||||
busy = false,
|
||||
error = null,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: DeleteConfirmationProps) {
|
||||
const cancelRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
// Move focus into the dialog when it opens (accessibility).
|
||||
useEffect(() => {
|
||||
cancelRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
// Close on Escape (unless a request is in flight).
|
||||
useEffect(() => {
|
||||
if (busy) return;
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') onCancel();
|
||||
};
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => document.removeEventListener('keydown', onKey);
|
||||
}, [busy, onCancel]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4"
|
||||
role="presentation"
|
||||
onClick={busy ? undefined : onCancel}
|
||||
>
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="delete-confirm-title"
|
||||
className="w-full max-w-md rounded-xl border border-slate-200 bg-white p-6 shadow-xl"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<div className="mb-4 flex items-start gap-3">
|
||||
<span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-600">
|
||||
<AlertTriangle size={20} aria-hidden="true" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 id="delete-confirm-title" className="text-base font-semibold text-slate-900">
|
||||
Are you sure you want to delete this article?
|
||||
</h2>
|
||||
<p className="mt-1 text-sm text-slate-600">
|
||||
“<span className="font-medium text-slate-800">{article.title}</span>” will be
|
||||
permanently removed. This action cannot be undone.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
ref={cancelRef}
|
||||
className="btn-secondary"
|
||||
disabled={busy}
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="confirm-delete"
|
||||
className="inline-flex items-center justify-center gap-2 rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={busy}
|
||||
onClick={onConfirm}
|
||||
>
|
||||
{busy ? 'Deleting…' : 'Yes, delete'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default DeleteConfirmation;
|
||||
@@ -0,0 +1,399 @@
|
||||
/**
|
||||
* Rich-text editor built on Lexical (M6).
|
||||
*
|
||||
* Features: bold / italic / underline, H1–H6 headings, ordered &
|
||||
* unordered lists, links and code blocks. Content is exchanged with the
|
||||
* parent as an HTML string (`initialHtml` in, `onChange` out) so it can
|
||||
* be stored verbatim in the backend `articles.content` column.
|
||||
*
|
||||
* Lexical 0.25.x API (classic): `RichTextPlugin` + `ContentEditable`,
|
||||
* `FORMAT_TEXT_COMMAND` for inline marks, `$setBlocksType` for block
|
||||
* conversion, `$generateHtmlFromNodes` / `$generateNodesFromDOM` for
|
||||
* HTML serialization.
|
||||
*/
|
||||
import {
|
||||
FORMAT_TEXT_COMMAND,
|
||||
REDO_COMMAND,
|
||||
UNDO_COMMAND,
|
||||
$createParagraphNode,
|
||||
$getSelection,
|
||||
$getRoot,
|
||||
$isRangeSelection,
|
||||
type ElementNode,
|
||||
type LexicalEditor as LexicalEditorType,
|
||||
} from 'lexical';
|
||||
import { CodeNode, $createCodeNode, $isCodeNode } from '@lexical/code';
|
||||
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
|
||||
import { LinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link';
|
||||
import {
|
||||
ListNode,
|
||||
$insertList,
|
||||
$isListNode,
|
||||
$removeList,
|
||||
type ListType,
|
||||
} from '@lexical/list';
|
||||
import { HeadingNode, $createHeadingNode, $isHeadingNode } from '@lexical/rich-text';
|
||||
import { $setBlocksType } from '@lexical/selection';
|
||||
import { LexicalComposer } from '@lexical/react/LexicalComposer';
|
||||
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
|
||||
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
|
||||
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
|
||||
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
|
||||
import { LinkPlugin } from '@lexical/react/LexicalLinkPlugin';
|
||||
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
|
||||
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
|
||||
import {
|
||||
Bold,
|
||||
Code,
|
||||
Italic,
|
||||
Link as LinkIcon,
|
||||
List,
|
||||
ListOrdered,
|
||||
Redo2,
|
||||
Underline,
|
||||
Undo2,
|
||||
} from 'lucide-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
type HeadingTag = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
|
||||
|
||||
/** History state helpers (exposed by the history plugin at runtime). */
|
||||
function historyCanUndo(editor: LexicalEditorType): boolean {
|
||||
return (editor as unknown as { canUndo?: () => boolean }).canUndo?.() ?? false;
|
||||
}
|
||||
|
||||
function historyCanRedo(editor: LexicalEditorType): boolean {
|
||||
return (editor as unknown as { canRedo?: () => boolean }).canRedo?.() ?? false;
|
||||
}
|
||||
|
||||
interface ToolbarState {
|
||||
bold: boolean;
|
||||
italic: boolean;
|
||||
underline: boolean;
|
||||
heading: '' | HeadingTag;
|
||||
/** 'bullet' (UL) or 'number' (OL) when the block is a list. */
|
||||
list: '' | Extract<ListType, 'bullet' | 'number'>;
|
||||
code: boolean;
|
||||
canUndo: boolean;
|
||||
canRedo: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TOOLBAR: ToolbarState = {
|
||||
bold: false,
|
||||
italic: false,
|
||||
underline: false,
|
||||
heading: '',
|
||||
list: '',
|
||||
code: false,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
};
|
||||
|
||||
/** Registered node types (beyond the core Text/Paragraph nodes). */
|
||||
const EDITOR_NODES = [HeadingNode, ListNode, LinkNode, CodeNode];
|
||||
|
||||
/** Lexical theme: maps node types to the CSS classes in admin.css. */
|
||||
const EDITOR_THEME = {
|
||||
heading: {
|
||||
h1: 'lex-h1',
|
||||
h2: 'lex-h2',
|
||||
h3: 'lex-h3',
|
||||
h4: 'lex-h4',
|
||||
h5: 'lex-h5',
|
||||
h6: 'lex-h6',
|
||||
},
|
||||
link: 'lex-link',
|
||||
list: { listitem: 'lex-listitem' },
|
||||
code: 'lex-code',
|
||||
quote: 'lex-quote',
|
||||
paragraph: 'lex-paragraph',
|
||||
};
|
||||
|
||||
interface LexicalEditorProps {
|
||||
/** HTML content to load when the editor mounts. */
|
||||
initialHtml: string;
|
||||
/** Called with the editor's HTML content after every change. */
|
||||
onChange: (html: string) => void;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function LexicalEditor({ initialHtml, onChange, placeholder }: LexicalEditorProps) {
|
||||
// Keep the latest callback without re-mounting the composer.
|
||||
const onChangeRef = useRef(onChange);
|
||||
onChangeRef.current = onChange;
|
||||
|
||||
return (
|
||||
<LexicalComposer
|
||||
initialConfig={{
|
||||
namespace: 'newzy-admin-editor',
|
||||
nodes: EDITOR_NODES,
|
||||
theme: EDITOR_THEME,
|
||||
onError: (error: unknown) => {
|
||||
console.error('Lexical editor error:', error);
|
||||
},
|
||||
}}
|
||||
>
|
||||
<EditorShell initialHtml={initialHtml} onChange={onChangeRef} placeholder={placeholder} />
|
||||
</LexicalComposer>
|
||||
);
|
||||
}
|
||||
|
||||
interface EditorShellProps {
|
||||
initialHtml: string;
|
||||
onChange: React.MutableRefObject<(html: string) => void>;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
function EditorShell({ initialHtml, onChange, placeholder }: EditorShellProps) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
// Load the initial HTML once (empty string -> the default empty paragraph).
|
||||
// $generateNodesFromDOM returns the parsed nodes without attaching them,
|
||||
// so they must be appended to the root manually. Non-whitelisted markup
|
||||
// (scripts, event handlers, unknown elements) is dropped by the parser,
|
||||
// which also acts as the XSS boundary for stored content.
|
||||
useEffect(() => {
|
||||
if (!initialHtml) return;
|
||||
const doc = document.implementation.createHTMLDocument('');
|
||||
doc.body.innerHTML = initialHtml;
|
||||
editor.update(
|
||||
() => {
|
||||
const nodes = $generateNodesFromDOM(editor, doc);
|
||||
if (nodes.length === 0) return; // keep the default empty paragraph
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
root.append(...nodes);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [editor]);
|
||||
|
||||
return (
|
||||
<div className="lex-editor" data-testid="lexical-editor">
|
||||
<Toolbar />
|
||||
<RichTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className="lex-editor__content"
|
||||
aria-label="Article content"
|
||||
spellCheck
|
||||
/>
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
{placeholder && <Placeholder text={placeholder} />}
|
||||
<HistoryPlugin />
|
||||
<LinkPlugin />
|
||||
<OnChangePlugin
|
||||
onChange={(editorState) => {
|
||||
editorState.read(() => {
|
||||
onChange.current($generateHtmlFromNodes(editor));
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Placeholder({ text }: { text: string }) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const [isEmpty, setIsEmpty] = useState(true);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
editor.registerUpdateListener(({ editorState }) => {
|
||||
editorState.read(() => {
|
||||
setIsEmpty($getRoot().getTextContent().trim().length === 0);
|
||||
});
|
||||
}),
|
||||
[editor],
|
||||
);
|
||||
|
||||
if (!isEmpty) return null;
|
||||
return (
|
||||
<span className="lex-editor__placeholder" data-testid="editor-placeholder">
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/* --- Toolbar ---------------------------------------------------------------- */
|
||||
|
||||
function Toolbar() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const [state, setState] = useState<ToolbarState>(DEFAULT_TOOLBAR);
|
||||
const [linkInputOpen, setLinkInputOpen] = useState(false);
|
||||
const [linkUrl, setLinkUrl] = useState('');
|
||||
const linkInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const updateToolbar = useCallback(() => {
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) {
|
||||
return;
|
||||
}
|
||||
const block = selection.anchor.getNode().getTopLevelElement();
|
||||
const listType = $isListNode(block) ? block.getListType() : '';
|
||||
const next: ToolbarState = {
|
||||
bold: selection.hasFormat('bold'),
|
||||
italic: selection.hasFormat('italic'),
|
||||
underline: selection.hasFormat('underline'),
|
||||
heading: $isHeadingNode(block) ? block.getTag() : '',
|
||||
list: listType === 'check' ? '' : listType,
|
||||
code: $isCodeNode(block),
|
||||
canUndo: historyCanUndo(editor),
|
||||
canRedo: historyCanRedo(editor),
|
||||
};
|
||||
setState((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));
|
||||
});
|
||||
}, [editor]);
|
||||
|
||||
// Keep the toolbar in sync with selection changes inside the editor.
|
||||
useEffect(() => {
|
||||
const handleSelectionChange = () => updateToolbar();
|
||||
document.addEventListener('selectionchange', handleSelectionChange);
|
||||
const updateListener = editor.registerUpdateListener(() => updateToolbar());
|
||||
return () => {
|
||||
document.removeEventListener('selectionchange', handleSelectionChange);
|
||||
updateListener();
|
||||
};
|
||||
}, [editor, updateToolbar]);
|
||||
|
||||
const dispatchFormat = (format: 'bold' | 'italic' | 'underline') =>
|
||||
editor.dispatchCommand(FORMAT_TEXT_COMMAND, format);
|
||||
|
||||
const setHeading = (tag: '' | HeadingTag) =>
|
||||
editor.update(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) return;
|
||||
$setBlocksType(
|
||||
selection,
|
||||
(tag === ''
|
||||
? () => $createParagraphNode()
|
||||
: () => $createHeadingNode(tag)) as () => ElementNode,
|
||||
);
|
||||
});
|
||||
|
||||
const toggleList = (type: Extract<ListType, 'bullet' | 'number'>) =>
|
||||
editor.update(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) return;
|
||||
const block = selection.anchor.getNode().getTopLevelElement();
|
||||
if ($isListNode(block) && block.getListType() === type) {
|
||||
$removeList();
|
||||
} else {
|
||||
$insertList(type);
|
||||
}
|
||||
});
|
||||
|
||||
const toggleCode = () =>
|
||||
editor.update(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) return;
|
||||
const block = selection.anchor.getNode().getTopLevelElement();
|
||||
$setBlocksType(
|
||||
selection,
|
||||
($isCodeNode(block)
|
||||
? () => $createParagraphNode()
|
||||
: () => $createCodeNode()) as () => ElementNode,
|
||||
);
|
||||
});
|
||||
|
||||
const openLinkInput = () => {
|
||||
setLinkInputOpen(true);
|
||||
// Focus the input once it has rendered.
|
||||
requestAnimationFrame(() => linkInputRef.current?.focus());
|
||||
};
|
||||
|
||||
const applyLink = () => {
|
||||
const url = linkUrl.trim();
|
||||
if (url) {
|
||||
editor.dispatchCommand(TOGGLE_LINK_COMMAND, { url, rel: 'noopener noreferrer' });
|
||||
}
|
||||
setLinkInputOpen(false);
|
||||
setLinkUrl('');
|
||||
};
|
||||
|
||||
const button = (
|
||||
label: string,
|
||||
isActive: boolean,
|
||||
onClick: () => void,
|
||||
icon: React.ReactNode,
|
||||
disabled = false,
|
||||
) => (
|
||||
<button
|
||||
type="button"
|
||||
className={cn('lex-toolbar-btn', isActive && 'is-active')}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
aria-pressed={isActive}
|
||||
disabled={disabled}
|
||||
onClick={onClick}
|
||||
>
|
||||
{icon}
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="lex-editor__toolbar" role="toolbar" aria-label="Text formatting">
|
||||
{button('Undo', false, () => editor.dispatchCommand(UNDO_COMMAND, undefined), <Undo2 size={15} />, !state.canUndo)}
|
||||
{button('Redo', false, () => editor.dispatchCommand(REDO_COMMAND, undefined), <Redo2 size={15} />, !state.canRedo)}
|
||||
<span className="lex-toolbar-sep" aria-hidden="true" />
|
||||
{button('Bold', state.bold, () => dispatchFormat('bold'), <Bold size={15} />)}
|
||||
{button('Italic', state.italic, () => dispatchFormat('italic'), <Italic size={15} />)}
|
||||
{button('Underline', state.underline, () => dispatchFormat('underline'), <Underline size={15} />)}
|
||||
<span className="lex-toolbar-sep" aria-hidden="true" />
|
||||
<label className="sr-only" htmlFor="lex-heading-select">
|
||||
Heading level
|
||||
</label>
|
||||
<select
|
||||
id="lex-heading-select"
|
||||
className="lex-toolbar-select"
|
||||
value={state.heading || ''}
|
||||
onChange={(event) => setHeading(event.target.value as '' | HeadingTag)}
|
||||
>
|
||||
<option value="">Paragraph</option>
|
||||
<option value="h1">Heading 1</option>
|
||||
<option value="h2">Heading 2</option>
|
||||
<option value="h3">Heading 3</option>
|
||||
<option value="h4">Heading 4</option>
|
||||
<option value="h5">Heading 5</option>
|
||||
<option value="h6">Heading 6</option>
|
||||
</select>
|
||||
<span className="lex-toolbar-sep" aria-hidden="true" />
|
||||
{button('Bulleted list', state.list === 'bullet', () => toggleList('bullet'), <List size={15} />)}
|
||||
{button('Numbered list', state.list === 'number', () => toggleList('number'), <ListOrdered size={15} />)}
|
||||
{button('Code block', state.code, toggleCode, <Code size={15} />)}
|
||||
<span className="lex-toolbar-sep" aria-hidden="true" />
|
||||
<span className="lex-toolbar-link">
|
||||
{button('Insert link', false, openLinkInput, <LinkIcon size={15} />)}
|
||||
{linkInputOpen && (
|
||||
<input
|
||||
ref={linkInputRef}
|
||||
type="url"
|
||||
value={linkUrl}
|
||||
placeholder="https://example.com"
|
||||
aria-label="Link URL"
|
||||
onChange={(event) => setLinkUrl(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
applyLink();
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
setLinkInputOpen(false);
|
||||
setLinkUrl('');
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
setLinkInputOpen(false);
|
||||
setLinkUrl('');
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { FileText, Home, Menu, Settings, X, type LucideIcon } from 'lucide-react';
|
||||
import { FileText, Home, LogOut, Menu, Settings, ShieldCheck, User, X, type LucideIcon } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import { Link, NavLink } from 'react-router-dom';
|
||||
import { useAuth } from '../../auth';
|
||||
import logo from '../../assets/logo.svg';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
@@ -31,6 +32,7 @@ const NAV_ITEMS: NavItem[] = [
|
||||
*/
|
||||
export function Header({ className }: HeaderProps) {
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const { username, isAdmin, ready } = useAuth();
|
||||
|
||||
const closeMenu = () => setMenuOpen(false);
|
||||
|
||||
@@ -41,6 +43,35 @@ export function Header({ className }: HeaderProps) {
|
||||
isActive && 'bg-blue-50 text-blue-700 hover:bg-blue-100 hover:text-blue-800',
|
||||
);
|
||||
|
||||
const plainLinkClasses =
|
||||
'inline-flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900';
|
||||
|
||||
// Auth links: sign-in/register when logged out, account/sign-out when
|
||||
// signed in (rendered once the session restore has settled).
|
||||
const renderAuthLinks = (onClick?: () => void) =>
|
||||
ready &&
|
||||
(username ? (
|
||||
<>
|
||||
<NavLink to="/account" className={linkClasses} onClick={onClick}>
|
||||
<User className="h-5 w-5" aria-hidden="true" />
|
||||
<span>{username}</span>
|
||||
</NavLink>
|
||||
<Link to="/sign-out" className={plainLinkClasses} onClick={onClick}>
|
||||
<LogOut className="h-5 w-5" aria-hidden="true" />
|
||||
<span>Sign out</span>
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link to="/login" className={plainLinkClasses} onClick={onClick}>
|
||||
<span>Sign in</span>
|
||||
</Link>
|
||||
<Link to="/register" className="btn !px-3 !py-2" onClick={onClick}>
|
||||
<span>Register</span>
|
||||
</Link>
|
||||
</>
|
||||
));
|
||||
|
||||
const renderNav = (id: string, itemClasses?: string) => (
|
||||
<nav id={id} aria-label={`${id === 'mobile-menu' ? 'Mobile' : 'Main'} navigation`} className={itemClasses}>
|
||||
{NAV_ITEMS.map(({ to, label, icon: Icon, end }) => (
|
||||
@@ -55,6 +86,17 @@ export function Header({ className }: HeaderProps) {
|
||||
<span>{label}</span>
|
||||
</NavLink>
|
||||
))}
|
||||
{/* Admin link (M6): only visible to admin accounts. */}
|
||||
{ready && isAdmin && (
|
||||
<NavLink
|
||||
to="/admin"
|
||||
className={({ isActive }) => linkClasses({ isActive })}
|
||||
onClick={closeMenu}
|
||||
>
|
||||
<ShieldCheck className="h-5 w-5" aria-hidden="true" />
|
||||
<span>Admin</span>
|
||||
</NavLink>
|
||||
)}
|
||||
</nav>
|
||||
);
|
||||
|
||||
@@ -73,6 +115,11 @@ export function Header({ className }: HeaderProps) {
|
||||
{/* Desktop navigation */}
|
||||
{renderNav('main-nav', 'hidden items-center gap-1 md:flex')}
|
||||
|
||||
{/* Account (auth) links */}
|
||||
<nav aria-label="Account" className="hidden items-center gap-1 md:flex">
|
||||
{renderAuthLinks()}
|
||||
</nav>
|
||||
|
||||
{/* Mobile menu toggle */}
|
||||
<button
|
||||
type="button"
|
||||
@@ -91,7 +138,14 @@ export function Header({ className }: HeaderProps) {
|
||||
</div>
|
||||
|
||||
{/* Mobile navigation (rendered only while open) */}
|
||||
{menuOpen && renderNav('mobile-menu', 'flex flex-col gap-1 border-t border-slate-200 px-4 pb-4 pt-2 md:hidden')}
|
||||
{menuOpen && (
|
||||
<div className="flex flex-col border-t border-slate-200 px-4 pb-4 pt-2 md:hidden">
|
||||
{renderNav('mobile-menu', 'flex flex-col gap-1')}
|
||||
<div className="mt-1 flex flex-col gap-1 border-t border-slate-200 pt-2">
|
||||
{renderAuthLinks(closeMenu)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Sample data used until the backend article endpoints are available
|
||||
* (planned for a later milestone). The home page falls back to this
|
||||
* dataset whenever `GET /api/v1/articles` is unavailable.
|
||||
*/
|
||||
import type { Article, Author, Category } from '../types';
|
||||
|
||||
export const sampleAuthors: Author[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Ada Lovelace',
|
||||
email: 'ada@example.com',
|
||||
bio: 'Writes about technology and computation.',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: 'Grace Hopper',
|
||||
email: 'grace@example.com',
|
||||
bio: 'Covers science and engineering.',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: 'Alan Turing',
|
||||
email: 'alan@example.com',
|
||||
bio: 'Follows sports and culture.',
|
||||
},
|
||||
];
|
||||
|
||||
export const sampleCategories: Category[] = [
|
||||
{ id: 1, name: 'Technology', slug: 'technology' },
|
||||
{ id: 2, name: 'Science', slug: 'science' },
|
||||
{ id: 3, name: 'Sports', slug: 'sports' },
|
||||
{ id: 4, name: 'Culture', slug: 'culture' },
|
||||
];
|
||||
|
||||
const authorOf = (id: number): Author => sampleAuthors.find((a) => a.id === id) as Author;
|
||||
const categoryOf = (id: number): Category =>
|
||||
sampleCategories.find((c) => c.id === id) as Category;
|
||||
|
||||
export const sampleArticles: Article[] = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Inside the new wave of open-source language models',
|
||||
content:
|
||||
'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.',
|
||||
authorId: 1,
|
||||
author: authorOf(1),
|
||||
categoryId: 1,
|
||||
category: categoryOf(1),
|
||||
createdAt: '2025-06-02T09:30:00Z',
|
||||
published: true,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Fusion milestone: net energy gain repeated for the third time',
|
||||
content:
|
||||
'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.',
|
||||
authorId: 2,
|
||||
author: authorOf(2),
|
||||
categoryId: 2,
|
||||
category: categoryOf(2),
|
||||
createdAt: '2025-05-28T14:10:00Z',
|
||||
published: true,
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'City marathon sets record turnout as first-timers flood the course',
|
||||
content:
|
||||
'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.',
|
||||
authorId: 3,
|
||||
author: authorOf(3),
|
||||
categoryId: 3,
|
||||
category: categoryOf(3),
|
||||
createdAt: '2025-05-25T08:00:00Z',
|
||||
published: true,
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: 'The quiet return of the neighborhood library',
|
||||
content:
|
||||
'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.',
|
||||
authorId: 1,
|
||||
author: authorOf(1),
|
||||
categoryId: 4,
|
||||
category: categoryOf(4),
|
||||
createdAt: '2025-05-20T17:45:00Z',
|
||||
published: true,
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
title: 'Rust keeps climbing the systems programming charts',
|
||||
content:
|
||||
'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.',
|
||||
authorId: 2,
|
||||
author: authorOf(2),
|
||||
categoryId: 1,
|
||||
category: categoryOf(1),
|
||||
createdAt: '2025-05-15T11:20:00Z',
|
||||
published: true,
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
title: 'Ocean robots map the deepest trenches in record time',
|
||||
content:
|
||||
'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.',
|
||||
authorId: 3,
|
||||
author: authorOf(3),
|
||||
categoryId: 2,
|
||||
category: categoryOf(2),
|
||||
createdAt: '2025-05-10T19:05:00Z',
|
||||
published: true,
|
||||
},
|
||||
];
|
||||
@@ -2,6 +2,7 @@ import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
import './assets/styles/globals.css';
|
||||
import './assets/styles/admin.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/**
|
||||
* Placeholder account page (protected by `RequireAuth`): proves the
|
||||
* auth-guarded routing works end-to-end. Real profile features arrive
|
||||
* in a later milestone.
|
||||
*/
|
||||
export default function Account() {
|
||||
const { username } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="container-page" data-testid="account-page">
|
||||
<h1 className="mb-2 text-3xl font-bold text-slate-900">Account</h1>
|
||||
<p className="text-sm text-slate-600">
|
||||
You are signed in as{' '}
|
||||
<strong className="font-semibold text-slate-900">{username}</strong>. Profile
|
||||
settings will live here.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
/**
|
||||
* Admin dashboard (M6): paginated list of all articles with debounced
|
||||
* search (300ms), sortable columns (title / created date), page-size
|
||||
* selector, row actions (edit / delete) and a success notice after
|
||||
* saves coming back from the edit page.
|
||||
*/
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpDown,
|
||||
Pencil,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Trash2,
|
||||
} from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { adminDeleteArticle, adminListArticles } from '../api/admin';
|
||||
import { ApiError } from '../api/client';
|
||||
import { DeleteConfirmation } from '../components/DeleteConfirmation';
|
||||
import { cn } from '../lib/utils';
|
||||
import type {
|
||||
AdminArticle,
|
||||
AdminArticlesPage,
|
||||
AdminSortBy,
|
||||
AdminSortOrder,
|
||||
} from '../types/admin';
|
||||
|
||||
const PAGE_SIZES = [10, 20, 50];
|
||||
const SEARCH_DEBOUNCE_MS = 300;
|
||||
|
||||
interface AdminDashboardState {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
search: string;
|
||||
sortBy: AdminSortBy;
|
||||
sortOrder: AdminSortOrder;
|
||||
}
|
||||
|
||||
const INITIAL_STATE: AdminDashboardState = {
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
search: '',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'desc',
|
||||
};
|
||||
|
||||
/** "2024-05-01T12:30:00Z" -> "01 May 2024, 12:30" (empty on bad input). */
|
||||
function formatDateTime(value: string): string {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return date.toLocaleString('en-GB', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
/** Compact page-number window with ellipses, e.g. [1, '…', 4, 5, 6, '…', 12]. */
|
||||
function pageWindow(current: number, total: number): (number | '…')[] {
|
||||
if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
|
||||
const pages = new Set<number>([1, 2, total - 1, total, current - 1, current, current + 1]);
|
||||
const sorted = [...pages].filter((p) => p >= 1 && p <= total).sort((a, b) => a - b);
|
||||
const out: (number | '…')[] = [];
|
||||
let previous = 0;
|
||||
for (const p of sorted) {
|
||||
if (p - previous > 1) out.push('…');
|
||||
out.push(p);
|
||||
previous = p;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function AdminDashboard() {
|
||||
const [state, setState] = useState<AdminDashboardState>(INITIAL_STATE);
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [data, setData] = useState<AdminArticlesPage | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pendingDelete, setPendingDelete] = useState<AdminArticle | null>(null);
|
||||
const [deleteBusy, setDeleteBusy] = useState(false);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
|
||||
const location = useLocation();
|
||||
// Success notice passed by the edit page after a save.
|
||||
useEffect(() => {
|
||||
const passed = (location.state as { notice?: string } | null)?.notice;
|
||||
if (passed) {
|
||||
setNotice(passed);
|
||||
// Clear it from router state so a refresh does not re-show it.
|
||||
window.history.replaceState({}, '');
|
||||
}
|
||||
}, [location.state]);
|
||||
|
||||
// Debounce the search input (300ms) before it reaches the API.
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedSearch(state.search), SEARCH_DEBOUNCE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [state.search]);
|
||||
|
||||
const searchActive = debouncedSearch.trim();
|
||||
|
||||
const load = useCallback(
|
||||
async (signal?: { cancelled: boolean }) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await adminListArticles({
|
||||
page: state.page,
|
||||
pageSize: state.pageSize,
|
||||
search: searchActive,
|
||||
sortBy: state.sortBy,
|
||||
sortOrder: state.sortOrder,
|
||||
});
|
||||
if (signal?.cancelled) return;
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
if (signal?.cancelled) return;
|
||||
setError(
|
||||
err instanceof ApiError
|
||||
? err.message
|
||||
: 'Something went wrong while loading articles.',
|
||||
);
|
||||
} finally {
|
||||
if (!signal?.cancelled) setLoading(false);
|
||||
}
|
||||
},
|
||||
[state, searchActive],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const signal = { cancelled: false };
|
||||
void load(signal);
|
||||
return () => {
|
||||
signal.cancelled = true;
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const update = (patch: Partial<AdminDashboardState>) =>
|
||||
setState((current) => ({ ...current, ...patch }));
|
||||
|
||||
// Search resets to page 1 (the debounced value drives the fetch).
|
||||
const onSearchChange = (value: string) => update({ search: value, page: 1 });
|
||||
|
||||
const onSort = (field: AdminSortBy) =>
|
||||
setState((current) =>
|
||||
current.sortBy === field
|
||||
? {
|
||||
...current,
|
||||
sortOrder: current.sortOrder === 'asc' ? 'desc' : 'asc',
|
||||
page: 1,
|
||||
}
|
||||
: { ...current, sortBy: field, sortOrder: 'asc', page: 1 },
|
||||
);
|
||||
|
||||
const onPageSizeChange = (size: number) => update({ pageSize: size, page: 1 });
|
||||
const onPageChange = (page: number) => update({ page });
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!pendingDelete) return;
|
||||
setDeleteBusy(true);
|
||||
setDeleteError(null);
|
||||
try {
|
||||
await adminDeleteArticle(pendingDelete.id);
|
||||
setPendingDelete(null);
|
||||
setNotice(`“${pendingDelete.title}” was deleted.`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
setDeleteError(
|
||||
err instanceof ApiError ? err.message : 'Deleting the article failed.',
|
||||
);
|
||||
} finally {
|
||||
setDeleteBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const cancelDelete = () => {
|
||||
setPendingDelete(null);
|
||||
setDeleteError(null);
|
||||
};
|
||||
|
||||
const range = useMemo(() => {
|
||||
if (!data || data.total === 0) return null;
|
||||
const start = (data.page - 1) * data.page_size + 1;
|
||||
const end = Math.min(data.page * data.page_size, data.total);
|
||||
return { start, end, total: data.total };
|
||||
}, [data]);
|
||||
|
||||
const totalPages = data?.total_pages ?? 0;
|
||||
|
||||
const sortIndicator = (field: AdminSortBy) =>
|
||||
state.sortBy !== field ? (
|
||||
<ArrowUpDown size={13} className="text-slate-400" aria-hidden="true" />
|
||||
) : state.sortOrder === 'asc' ? (
|
||||
<ArrowUp size={13} className="text-blue-600" aria-hidden="true" />
|
||||
) : (
|
||||
<ArrowDown size={13} className="text-blue-600" aria-hidden="true" />
|
||||
);
|
||||
|
||||
const thClasses =
|
||||
'px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500';
|
||||
const sortButtonClasses =
|
||||
'inline-flex items-center gap-1.5 uppercase tracking-wide hover:text-slate-800';
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Heading + primary action */}
|
||||
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">Articles</h1>
|
||||
<p className="text-sm text-slate-500">
|
||||
Create, edit and delete the articles shown on the site.
|
||||
</p>
|
||||
</div>
|
||||
<Link to="/admin/articles/new" className="btn">
|
||||
<Plus size={15} aria-hidden="true" />
|
||||
New article
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{notice && (
|
||||
<div
|
||||
className="mb-4 flex items-center justify-between gap-3 rounded-md border border-green-200 bg-green-50 px-4 py-2.5 text-sm text-green-800"
|
||||
role="status"
|
||||
>
|
||||
<span>{notice}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Dismiss notice"
|
||||
className="text-green-700 hover:text-green-900"
|
||||
onClick={() => setNotice(null)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search + filters */}
|
||||
<form
|
||||
role="search"
|
||||
className="mb-4 flex items-center gap-3"
|
||||
onSubmit={(event) => event.preventDefault()}
|
||||
>
|
||||
<label htmlFor="admin-article-search" className="sr-only">
|
||||
Search articles
|
||||
</label>
|
||||
<div className="relative w-full max-w-sm">
|
||||
<Search
|
||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 text-slate-400"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<input
|
||||
id="admin-article-search"
|
||||
type="search"
|
||||
placeholder="Search by title or content…"
|
||||
value={state.search}
|
||||
onChange={(event) => onSearchChange(event.target.value)}
|
||||
className="w-full rounded-md border border-slate-300 bg-white py-2 pl-9 pr-3 text-sm text-slate-900 placeholder:text-slate-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/40"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
className="mb-4 flex items-center justify-between gap-3 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
|
||||
role="alert"
|
||||
>
|
||||
<span>{error}</span>
|
||||
<button type="button" className="btn-secondary !py-1.5" onClick={() => void load()}>
|
||||
<RefreshCw size={14} aria-hidden="true" />
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Article table */}
|
||||
<div className="overflow-x-auto rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||
<table className="min-w-full divide-y divide-slate-200 text-sm">
|
||||
<thead className="bg-slate-50">
|
||||
<tr>
|
||||
<th scope="col" className={thClasses}>
|
||||
<button
|
||||
type="button"
|
||||
className={sortButtonClasses}
|
||||
onClick={() => onSort('title')}
|
||||
aria-label="Sort by title"
|
||||
>
|
||||
Title {sortIndicator('title')}
|
||||
</button>
|
||||
</th>
|
||||
<th scope="col" className={thClasses}>
|
||||
Author
|
||||
</th>
|
||||
<th scope="col" className={thClasses}>
|
||||
Category
|
||||
</th>
|
||||
<th scope="col" className={thClasses}>
|
||||
Published
|
||||
</th>
|
||||
<th scope="col" className={thClasses}>
|
||||
<button
|
||||
type="button"
|
||||
className={sortButtonClasses}
|
||||
onClick={() => onSort('created_at')}
|
||||
aria-label="Sort by creation date"
|
||||
>
|
||||
Created {sortIndicator('created_at')}
|
||||
</button>
|
||||
</th>
|
||||
<th scope="col" className={cn(thClasses, 'text-right')}>
|
||||
<span className="sr-only">Actions</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{loading && data === null ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-12 text-center text-sm text-slate-500">
|
||||
<span className="animate-pulse">Loading articles…</span>
|
||||
</td>
|
||||
</tr>
|
||||
) : data && data.articles.length > 0 ? (
|
||||
data.articles.map((article) => (
|
||||
<tr key={article.id} className="transition-colors hover:bg-slate-50">
|
||||
<td className="max-w-xs px-4 py-3">
|
||||
<span
|
||||
className="block truncate font-medium text-slate-900"
|
||||
title={article.title}
|
||||
>
|
||||
{article.title}
|
||||
</span>
|
||||
</td>
|
||||
<td className="max-w-[12rem] px-4 py-3">
|
||||
<span className="block truncate text-slate-600" title={article.author.name}>
|
||||
{article.author.name}
|
||||
</span>
|
||||
</td>
|
||||
<td className="max-w-[12rem] px-4 py-3">
|
||||
<span
|
||||
className="block truncate rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-medium text-slate-600"
|
||||
title={article.category.name}
|
||||
>
|
||||
{article.category.name}
|
||||
</span>
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3">
|
||||
{article.published ? (
|
||||
<span className="rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-700">
|
||||
Published
|
||||
</span>
|
||||
) : (
|
||||
<span className="rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-medium text-amber-700">
|
||||
Draft
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-slate-500">
|
||||
{formatDateTime(article.created_at)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-right">
|
||||
<div className="inline-flex items-center gap-1">
|
||||
<Link
|
||||
to={`/admin/articles/${article.id}/edit`}
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-slate-300 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 transition-colors hover:bg-slate-100"
|
||||
>
|
||||
<Pencil size={13} aria-hidden="true" />
|
||||
Edit
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-red-200 bg-white px-2.5 py-1.5 text-xs font-medium text-red-700 transition-colors hover:bg-red-50"
|
||||
onClick={() => setPendingDelete(article)}
|
||||
>
|
||||
<Trash2 size={13} aria-hidden="true" />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-12 text-center text-sm text-slate-500">
|
||||
{searchActive
|
||||
? `No articles match “${searchActive}”.`
|
||||
: 'No articles yet — create the first one.'}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
<nav
|
||||
aria-label="Pagination"
|
||||
className="mt-4 flex flex-wrap items-center justify-between gap-3"
|
||||
>
|
||||
<div className="flex items-center gap-3 text-sm text-slate-600">
|
||||
<label htmlFor="admin-page-size" className="inline-flex items-center gap-2">
|
||||
Rows per page
|
||||
<select
|
||||
id="admin-page-size"
|
||||
className="rounded-md border border-slate-300 bg-white py-1.5 pl-2 pr-7 text-sm"
|
||||
value={state.pageSize}
|
||||
onChange={(event) => onPageSizeChange(Number(event.target.value))}
|
||||
>
|
||||
{PAGE_SIZES.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{range && (
|
||||
<span aria-live="polite">
|
||||
Showing {range.start}–{range.end} of {range.total}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
className="btn-secondary !px-3 !py-1.5"
|
||||
disabled={state.page <= 1 || loading}
|
||||
onClick={() => onPageChange(state.page - 1)}
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
{pageWindow(state.page, totalPages).map((page, index) =>
|
||||
page === '…' ? (
|
||||
<span key={`gap-${index}`} className="px-1.5 text-sm text-slate-400">
|
||||
…
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
key={page}
|
||||
type="button"
|
||||
aria-current={page === state.page ? 'page' : undefined}
|
||||
className={cn(
|
||||
'min-w-[2.1rem] rounded-md px-2 py-1.5 text-sm font-medium',
|
||||
page === state.page
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'border border-slate-300 bg-white text-slate-700 hover:bg-slate-100',
|
||||
)}
|
||||
disabled={loading}
|
||||
onClick={() => onPageChange(page)}
|
||||
>
|
||||
{page}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn-secondary !px-3 !py-1.5"
|
||||
disabled={state.page >= totalPages || loading}
|
||||
onClick={() => onPageChange(state.page + 1)}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Delete confirmation dialog */}
|
||||
{pendingDelete && (
|
||||
<DeleteConfirmation
|
||||
article={pendingDelete}
|
||||
busy={deleteBusy}
|
||||
error={deleteError}
|
||||
onConfirm={() => void confirmDelete()}
|
||||
onCancel={cancelDelete}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AdminDashboard;
|
||||
@@ -0,0 +1,516 @@
|
||||
/**
|
||||
* Create/edit article page (M6).
|
||||
*
|
||||
* Full form for an article: title, author (select), category (select),
|
||||
* published flag and a Lexical WYSIWYG editor for the HTML body.
|
||||
* Validates required fields client-side (mirroring the backend 422
|
||||
* rules), shows a loading state while saving and surfaces success/error
|
||||
* notifications. An optional debounced auto-save can be enabled.
|
||||
*
|
||||
* Routes:
|
||||
* - `/admin/articles/new` -> create mode (no `:id` param)
|
||||
* - `/admin/articles/:id/edit` -> edit mode (loads the article on mount)
|
||||
*/
|
||||
import { ArrowLeft, Loader2, Save } from 'lucide-react';
|
||||
import {
|
||||
FormEvent,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import {
|
||||
adminCreateArticle,
|
||||
adminGetArticle,
|
||||
adminListAuthors,
|
||||
adminListCategories,
|
||||
adminUpdateArticle,
|
||||
} from '../api/admin';
|
||||
import { ApiError } from '../api/client';
|
||||
import { LexicalEditor } from '../components/LexicalEditor';
|
||||
import type { Author, Category } from '../types';
|
||||
import type { AdminArticleInput } from '../types/admin';
|
||||
|
||||
const AUTO_SAVE_DELAY_MS = 2000;
|
||||
|
||||
interface FormValues {
|
||||
title: string;
|
||||
/** 0 = not selected yet (no author). */
|
||||
authorId: number;
|
||||
/** 0 = not selected yet (no category). */
|
||||
categoryId: number;
|
||||
/** Whether the article is visible on the public site. */
|
||||
published: boolean;
|
||||
}
|
||||
|
||||
interface FieldErrors {
|
||||
title?: string;
|
||||
authorId?: string;
|
||||
categoryId?: string;
|
||||
content?: string;
|
||||
}
|
||||
|
||||
/** Plain text of an HTML fragment (client-side "not empty" check). */
|
||||
function textOf(html: string): string {
|
||||
return html
|
||||
.replace(/<[^>]*>/g, ' ')
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Client-side validation mirroring the backend rules (422 on the server). */
|
||||
function validate(values: FormValues, content: string): FieldErrors {
|
||||
const errors: FieldErrors = {};
|
||||
const title = values.title.trim();
|
||||
if (!title) {
|
||||
errors.title = 'Title is required.';
|
||||
} else if (title.length > 200) {
|
||||
errors.title = 'Title must be at most 200 characters.';
|
||||
}
|
||||
if (!values.authorId) errors.authorId = 'Select an author.';
|
||||
if (!values.categoryId) errors.categoryId = 'Select a category.';
|
||||
if (!textOf(content)) errors.content = 'Content is required.';
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function EditArticlePage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const editingId = id ? Number(id) : null;
|
||||
const isCreate = editingId === null;
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [values, setValues] = useState<FormValues>({
|
||||
title: '',
|
||||
authorId: 0,
|
||||
categoryId: 0,
|
||||
published: false,
|
||||
});
|
||||
const [contentHtml, setContentHtml] = useState('');
|
||||
const [authors, setAuthors] = useState<Author[]>([]);
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [refsLoaded, setRefsLoaded] = useState(false);
|
||||
const [refsError, setRefsError] = useState<string | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(isCreate ? false : true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [autoSave, setAutoSave] = useState(false);
|
||||
const [autoSaveStatus, setAutoSaveStatus] = useState<
|
||||
'idle' | 'saving' | 'saved' | 'paused'
|
||||
>('idle');
|
||||
|
||||
// After an auto-save in create mode, switch to updating the new article.
|
||||
const [createdId, setCreatedId] = useState<number | null>(null);
|
||||
const targetId = editingId ?? createdId;
|
||||
|
||||
const [initialValues, setInitialValues] = useState<FormValues | null>(null);
|
||||
const lastSavedSignature = useRef<string | null>(null);
|
||||
|
||||
const applyBaseline = (next: FormValues, content: string) => {
|
||||
setInitialValues(next);
|
||||
lastSavedSignature.current = signature(next, content);
|
||||
};
|
||||
|
||||
// Load the author/category reference lists (shared by both modes).
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
Promise.all([adminListAuthors(), adminListCategories()])
|
||||
.then(([authorList, categoryList]) => {
|
||||
if (!active) return;
|
||||
setAuthors(authorList);
|
||||
setCategories(categoryList);
|
||||
setRefsLoaded(true);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!active) return;
|
||||
setRefsError(
|
||||
err instanceof ApiError
|
||||
? err.message
|
||||
: 'Could not load the author and category lists.',
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Default the selects to the first entries so the form is usable right
|
||||
// away (create mode; edit mode overwrites with the loaded values).
|
||||
useEffect(() => {
|
||||
if (!refsLoaded) return;
|
||||
setValues((current) => ({
|
||||
...current,
|
||||
authorId: current.authorId || (authors[0]?.id ?? 0),
|
||||
categoryId: current.categoryId || (categories[0]?.id ?? 0),
|
||||
}));
|
||||
}, [refsLoaded, authors, categories]);
|
||||
|
||||
// Create mode: snapshot the baseline once the defaults have been applied.
|
||||
useEffect(() => {
|
||||
if (editingId !== null || !refsLoaded || initialValues !== null) return;
|
||||
applyBaseline(values, contentHtml);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [editingId, refsLoaded, values, initialValues]);
|
||||
|
||||
// Load the article in edit mode.
|
||||
useEffect(() => {
|
||||
if (editingId === null) return;
|
||||
let active = true;
|
||||
adminGetArticle(editingId)
|
||||
.then((article) => {
|
||||
if (!active) return;
|
||||
const loaded: FormValues = {
|
||||
title: article.title,
|
||||
authorId: article.author_id,
|
||||
categoryId: article.category_id,
|
||||
published: article.published,
|
||||
};
|
||||
setValues(loaded);
|
||||
setContentHtml(article.content);
|
||||
applyBaseline(loaded, article.content);
|
||||
setLoadError(null);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!active) return;
|
||||
setLoadError(
|
||||
err instanceof ApiError ? err.message : 'Could not load the article.',
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [editingId]);
|
||||
|
||||
const dirty = useMemo(
|
||||
() =>
|
||||
initialValues !== null &&
|
||||
signature(values, contentHtml) !== lastSavedSignature.current,
|
||||
[values, contentHtml, initialValues],
|
||||
);
|
||||
|
||||
const save = useCallback(
|
||||
async (mode: 'manual' | 'auto' = 'manual') => {
|
||||
const errors = validate(values, contentHtml);
|
||||
setFieldErrors(errors);
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (mode === 'auto') {
|
||||
setAutoSaveStatus('paused');
|
||||
return false;
|
||||
}
|
||||
setFormError('Please fix the highlighted fields and try again.');
|
||||
return false;
|
||||
}
|
||||
setFormError(null);
|
||||
setSaving(true);
|
||||
if (mode === 'auto') setAutoSaveStatus('saving');
|
||||
try {
|
||||
const payload: AdminArticleInput = {
|
||||
title: values.title.trim(),
|
||||
content: contentHtml,
|
||||
author_id: values.authorId,
|
||||
category_id: values.categoryId,
|
||||
published: values.published,
|
||||
};
|
||||
const saved =
|
||||
targetId !== null
|
||||
? await adminUpdateArticle(targetId, payload)
|
||||
: await adminCreateArticle(payload);
|
||||
// Trim the title in the form too so the baseline signature matches.
|
||||
setValues((current) => ({ ...current, title: current.title.trim() }));
|
||||
lastSavedSignature.current = signature(
|
||||
{ ...values, title: values.title.trim() },
|
||||
contentHtml,
|
||||
);
|
||||
if (createdId === null && editingId === null) {
|
||||
setCreatedId(saved.id);
|
||||
}
|
||||
setAutoSaveStatus('saved');
|
||||
return true;
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof ApiError ? err.message : 'Saving the article failed.';
|
||||
if (mode === 'auto') {
|
||||
setAutoSaveStatus('paused');
|
||||
} else {
|
||||
setFormError(message);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
},
|
||||
[values, contentHtml, targetId, createdId, editingId],
|
||||
);
|
||||
|
||||
// Debounced auto-save: fire 2s after the last change when enabled.
|
||||
useEffect(() => {
|
||||
if (!autoSave || loading || saving || !dirty) return;
|
||||
const timer = setTimeout(() => {
|
||||
void save('auto');
|
||||
}, AUTO_SAVE_DELAY_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [autoSave, loading, saving, dirty, save]);
|
||||
|
||||
const onSubmit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const ok = await save('manual');
|
||||
if (ok) {
|
||||
navigate('/admin', {
|
||||
state: { notice: `“${values.title.trim()}” was saved.` },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center py-16" role="status">
|
||||
<span className="animate-pulse text-sm text-slate-500">
|
||||
Loading article…
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<div className="text-center">
|
||||
<h1 className="mb-2 text-2xl font-bold text-slate-900">
|
||||
Article not found
|
||||
</h1>
|
||||
<p className="mb-6 text-sm text-slate-600">{loadError}</p>
|
||||
<Link to="/admin" className="btn">
|
||||
<ArrowLeft size={15} aria-hidden="true" />
|
||||
Back to articles
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const autoSaveHint =
|
||||
autoSaveStatus === 'saving'
|
||||
? 'Saving…'
|
||||
: autoSaveStatus === 'saved'
|
||||
? 'All changes saved'
|
||||
: autoSaveStatus === 'paused'
|
||||
? 'Auto-save paused (fix validation errors)'
|
||||
: 'Off';
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<Link
|
||||
to="/admin"
|
||||
className="mb-2 inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800"
|
||||
>
|
||||
<ArrowLeft size={14} aria-hidden="true" />
|
||||
Back to articles
|
||||
</Link>
|
||||
<h1 className="text-2xl font-bold text-slate-900">
|
||||
{isCreate && createdId === null
|
||||
? 'New article'
|
||||
: `Edit article #${targetId}`}
|
||||
</h1>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm text-slate-600">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
|
||||
checked={autoSave}
|
||||
disabled={saving}
|
||||
onChange={(event) => {
|
||||
setAutoSave(event.target.checked);
|
||||
if (!event.target.checked) setAutoSaveStatus('idle');
|
||||
}}
|
||||
/>
|
||||
Auto-save <span className="text-xs text-slate-400">({autoSaveHint})</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{refsError && (
|
||||
<div
|
||||
className="mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
|
||||
role="alert"
|
||||
>
|
||||
{refsError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{formError && (
|
||||
<div
|
||||
className="mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
|
||||
role="alert"
|
||||
>
|
||||
{formError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form
|
||||
onSubmit={(event) => void onSubmit(event)}
|
||||
className="space-y-5 rounded-xl border border-slate-200 bg-white p-6 shadow-sm"
|
||||
noValidate
|
||||
>
|
||||
<div>
|
||||
<label htmlFor="article-title" className="mb-1 block text-sm font-medium text-slate-700">
|
||||
Title <span className="text-red-600" aria-hidden="true">*</span>
|
||||
</label>
|
||||
<input
|
||||
id="article-title"
|
||||
className="input"
|
||||
value={values.title}
|
||||
maxLength={200}
|
||||
placeholder="Headline of the story"
|
||||
onChange={(event) =>
|
||||
setValues((current) => ({ ...current, title: event.target.value }))
|
||||
}
|
||||
/>
|
||||
{fieldErrors.title && (
|
||||
<p className="mt-1 text-sm text-red-600" role="alert">
|
||||
{fieldErrors.title}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="article-author" className="mb-1 block text-sm font-medium text-slate-700">
|
||||
Author <span className="text-red-600" aria-hidden="true">*</span>
|
||||
</label>
|
||||
<select
|
||||
id="article-author"
|
||||
className="input"
|
||||
value={values.authorId}
|
||||
onChange={(event) =>
|
||||
setValues((current) => ({
|
||||
...current,
|
||||
authorId: Number(event.target.value),
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value={0} disabled>
|
||||
Select an author…
|
||||
</option>
|
||||
{authors.map((author) => (
|
||||
<option key={author.id} value={author.id}>
|
||||
{author.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldErrors.authorId && (
|
||||
<p className="mt-1 text-sm text-red-600" role="alert">
|
||||
{fieldErrors.authorId}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="article-category" className="mb-1 block text-sm font-medium text-slate-700">
|
||||
Category <span className="text-red-600" aria-hidden="true">*</span>
|
||||
</label>
|
||||
<select
|
||||
id="article-category"
|
||||
className="input"
|
||||
value={values.categoryId}
|
||||
onChange={(event) =>
|
||||
setValues((current) => ({
|
||||
...current,
|
||||
categoryId: Number(event.target.value),
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value={0} disabled>
|
||||
Select a category…
|
||||
</option>
|
||||
{categories.map((category) => (
|
||||
<option key={category.id} value={category.id}>
|
||||
{category.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldErrors.categoryId && (
|
||||
<p className="mt-1 text-sm text-red-600" role="alert">
|
||||
{fieldErrors.categoryId}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="article-published"
|
||||
className="mb-1 block text-sm font-medium text-slate-700"
|
||||
>
|
||||
Published{' '}
|
||||
<span className="text-xs font-normal text-slate-400">
|
||||
(visible on the public site)
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="article-published"
|
||||
type="checkbox"
|
||||
className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
|
||||
checked={values.published}
|
||||
onChange={(event) =>
|
||||
setValues((current) => ({
|
||||
...current,
|
||||
published: event.target.checked,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="mb-1 block text-sm font-medium text-slate-700">
|
||||
Content <span className="text-red-600" aria-hidden="true">*</span>
|
||||
</span>
|
||||
<LexicalEditor
|
||||
initialHtml={contentHtml}
|
||||
onChange={setContentHtml}
|
||||
placeholder="Write the story body…"
|
||||
/>
|
||||
{fieldErrors.content && (
|
||||
<p className="mt-1 text-sm text-red-600" role="alert">
|
||||
{fieldErrors.content}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-1 text-xs text-slate-400">
|
||||
Rich text: bold, italic, underline, headings, lists, links and code blocks.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 border-t border-slate-100 pt-5">
|
||||
<button type="submit" className="btn" disabled={saving}>
|
||||
{saving ? (
|
||||
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<Save size={15} aria-hidden="true" />
|
||||
)}
|
||||
{saving
|
||||
? 'Saving…'
|
||||
: isCreate && createdId === null
|
||||
? 'Create article'
|
||||
: 'Save changes'}
|
||||
</button>
|
||||
<Link to="/admin" className="btn-secondary">
|
||||
Cancel
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function signature(values: FormValues, content: string): string {
|
||||
return JSON.stringify({ ...values, content });
|
||||
}
|
||||
|
||||
export default EditArticlePage;
|
||||
@@ -14,8 +14,9 @@ type FeedSource = 'api' | 'sample';
|
||||
* Homepage: featured (hero) article, search bar, article grid built from
|
||||
* ArticleCard components, and a pagination placeholder.
|
||||
*
|
||||
* Articles are loaded from `GET /api/v1/articles`; until that backend
|
||||
* endpoint exists the page falls back to sample data (clearly labelled).
|
||||
* Articles are loaded from `GET /api/v1/articles`; when the backend is
|
||||
* unreachable or has no published articles yet the page falls back to
|
||||
* sample data (clearly labelled).
|
||||
*/
|
||||
export function Home() {
|
||||
const [articles, setArticles] = useState<Article[]>([]);
|
||||
@@ -38,8 +39,8 @@ export function Home() {
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!active) return;
|
||||
// 404 (endpoint not implemented yet) or network failure: fall back to
|
||||
// sample data so the UI stays useful without a running backend.
|
||||
// Network failure (or non-2xx): fall back to sample data so the
|
||||
// UI stays useful without a running backend.
|
||||
if (!(error instanceof ApiError)) {
|
||||
console.error('Unexpected error while loading articles:', error);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { FormEvent, useState } from 'react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Loader2, LogIn } from 'lucide-react';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
interface LoginLocationState {
|
||||
/** Route the user was trying to reach (set by `RequireAuth`). */
|
||||
from?: string;
|
||||
/** `true` when arriving here right after a sign-out. */
|
||||
signedOut?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Login page: authenticates against `POST /api/v1/auth/login` via
|
||||
* `useAuth` (which stores the JWT) and redirects back to the intended
|
||||
* page, or to home.
|
||||
*/
|
||||
export default function Login() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const state = (location.state ?? null) as LoginLocationState | null;
|
||||
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!username.trim() || !password) {
|
||||
setError('Please enter both username and password.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await login(username.trim(), password);
|
||||
const from = state?.from;
|
||||
navigate(from && from !== '/login' ? from : '/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Sign in failed');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<div className="auth-card" data-testid="login-card">
|
||||
<h1 className="auth-title">
|
||||
<LogIn size={18} aria-hidden="true" />
|
||||
Sign in
|
||||
</h1>
|
||||
|
||||
{state?.signedOut && (
|
||||
<p className="auth-success" role="status">
|
||||
You have been signed out.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p className="auth-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={submit}>
|
||||
<div className="field">
|
||||
<label htmlFor="login-username">Username</label>
|
||||
<input
|
||||
id="login-username"
|
||||
className="input"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
placeholder="your username"
|
||||
maxLength={60}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="login-password">Password</label>
|
||||
<input
|
||||
id="login-password"
|
||||
type="password"
|
||||
className="input"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
placeholder="your password"
|
||||
maxLength={200}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button className="btn" type="submit" disabled={busy}>
|
||||
{busy ? (
|
||||
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<LogIn size={15} aria-hidden="true" />
|
||||
)}
|
||||
{busy ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="auth-alt">
|
||||
No account yet?{' '}
|
||||
<Link to="/register" className="font-medium text-blue-700 hover:underline">
|
||||
Register
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { FormEvent, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { Loader2, UserPlus } from 'lucide-react';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/** Must match the backend `RegisterIn.username` pattern. */
|
||||
const USERNAME_PATTERN = /^[a-zA-Z0-9_]{3,20}$/;
|
||||
|
||||
/**
|
||||
* Registration page: validates the inputs client-side, then calls
|
||||
* `POST /api/v1/auth/register` via `useAuth` (which stores the JWT and
|
||||
* signs the user in). Backend rejections (e.g. duplicate username) are
|
||||
* shown verbatim.
|
||||
*/
|
||||
export default function Register() {
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const name = username.trim();
|
||||
if (!USERNAME_PATTERN.test(name)) {
|
||||
setError('Username must be 3–20 characters: letters, numbers or underscores.');
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters.');
|
||||
return;
|
||||
}
|
||||
if (password !== confirm) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await register(name, password);
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Registration failed');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<div className="auth-card" data-testid="register-card">
|
||||
<h1 className="auth-title">
|
||||
<UserPlus size={18} aria-hidden="true" />
|
||||
Create an account
|
||||
</h1>
|
||||
|
||||
{error && (
|
||||
<p className="auth-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={submit}>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-username">Username</label>
|
||||
<input
|
||||
id="reg-username"
|
||||
className="input"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
placeholder="3–20 letters, numbers or underscores"
|
||||
maxLength={20}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-password">Password</label>
|
||||
<input
|
||||
id="reg-password"
|
||||
type="password"
|
||||
className="input"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
placeholder="at least 8 characters"
|
||||
maxLength={200}
|
||||
minLength={8}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-confirm">Confirm password</label>
|
||||
<input
|
||||
id="reg-confirm"
|
||||
type="password"
|
||||
className="input"
|
||||
value={confirm}
|
||||
onChange={(event) => setConfirm(event.target.value)}
|
||||
placeholder="repeat the password"
|
||||
maxLength={200}
|
||||
minLength={8}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button className="btn" type="submit" disabled={busy}>
|
||||
{busy ? (
|
||||
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<UserPlus size={15} aria-hidden="true" />
|
||||
)}
|
||||
{busy ? 'Creating account…' : 'Register'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="auth-alt">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="font-medium text-blue-700 hover:underline">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { LogOut } from 'lucide-react';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/**
|
||||
* Sign-out page: clears the stored JWT (best-effort call to the
|
||||
* stateless `POST /api/v1/auth/logout`) and redirects to the login page
|
||||
* with a "signed out" notice.
|
||||
*/
|
||||
export default function SignOut() {
|
||||
const { logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
logout();
|
||||
navigate('/login', { replace: true, state: { signedOut: true } });
|
||||
}, [logout, navigate]);
|
||||
|
||||
return (
|
||||
<div className="auth-wrap" role="status">
|
||||
<div className="flex items-center gap-2 text-slate-600">
|
||||
<LogOut size={20} aria-hidden="true" />
|
||||
<span className="text-sm">Signing out…</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,33 @@
|
||||
import { fireEvent, screen, within } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { me } from '../api/client';
|
||||
import Header from '../components/ui/Header';
|
||||
import { renderWithRouter } from './utils';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Header', () => {
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the brand with the logo', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
const brand = screen.getByRole('link', { name: 'newzy' });
|
||||
expect(brand).toHaveAttribute('href', '/');
|
||||
expect(brand.querySelector('img')).toHaveAttribute('src', expect.stringContaining('logo'));
|
||||
});
|
||||
|
||||
it('renders the primary navigation with router links and lucide icons', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||
expect(within(nav).getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
|
||||
@@ -24,7 +39,7 @@ describe('Header', () => {
|
||||
});
|
||||
|
||||
it('marks the active route in the navigation', () => {
|
||||
renderWithRouter(<Header />, { route: '/categories' });
|
||||
renderWithAuth(<Header />, { route: '/categories' });
|
||||
|
||||
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveClass('bg-blue-50');
|
||||
@@ -32,7 +47,7 @@ describe('Header', () => {
|
||||
});
|
||||
|
||||
it('toggles the mobile menu', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
// Mobile menu is closed by default.
|
||||
expect(screen.queryByRole('navigation', { name: 'Mobile navigation' })).not.toBeInTheDocument();
|
||||
@@ -50,6 +65,35 @@ describe('Header', () => {
|
||||
screen.queryByRole('navigation', { name: 'Mobile navigation' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows sign-in and register links when signed out', async () => {
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const accountNav = screen.getByRole('navigation', { name: 'Account' });
|
||||
expect(await within(accountNav).findByRole('link', { name: 'Sign in' })).toHaveAttribute(
|
||||
'href',
|
||||
'/login',
|
||||
);
|
||||
expect(within(accountNav).getByRole('link', { name: /register/i })).toHaveAttribute(
|
||||
'href',
|
||||
'/register',
|
||||
);
|
||||
expect(within(accountNav).queryByRole('link', { name: /sign out/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the username and sign-out link when signed in', async () => {
|
||||
(me as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem('AUTH_TOKEN', 'stored-token');
|
||||
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const accountNav = screen.getByRole('navigation', { name: 'Account' });
|
||||
expect(await within(accountNav).findByText('alice')).toBeInTheDocument();
|
||||
expect(within(accountNav).getByRole('link', { name: 'Sign out' })).toHaveAttribute(
|
||||
'href',
|
||||
'/sign-out',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const NAV_ITEM_COUNT = 3;
|
||||
@@ -3,10 +3,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { getHealth } from '../api/client';
|
||||
import Layout from '../components/ui/Layout';
|
||||
import { renderWithRouter } from './utils';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
getHealth: vi.fn(),
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Layout', () => {
|
||||
@@ -17,7 +22,7 @@ describe('Layout', () => {
|
||||
it('renders the header, main content area and footer', () => {
|
||||
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>Page content</p>
|
||||
</Layout>,
|
||||
@@ -33,7 +38,7 @@ describe('Layout', () => {
|
||||
it('shows the API as online when the health check succeeds', async () => {
|
||||
(getHealth as Mock).mockResolvedValue({ status: 'ok', version: '0.1.0' });
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>content</p>
|
||||
</Layout>,
|
||||
@@ -46,7 +51,7 @@ describe('Layout', () => {
|
||||
it('shows the API as offline when the health check fails', async () => {
|
||||
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>content</p>
|
||||
</Layout>,
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Unit tests for the admin API client (URL/parameter building, methods,
|
||||
* response parsing, error propagation).
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
adminCreateArticle,
|
||||
adminDeleteArticle,
|
||||
adminGetArticle,
|
||||
adminListArticles,
|
||||
adminListAuthors,
|
||||
adminListCategories,
|
||||
adminUpdateArticle,
|
||||
} from '../../api/admin';
|
||||
import { ApiError, TOKEN_KEY } from '../../api/client';
|
||||
import type { AdminArticlesPage } from '../../types/admin';
|
||||
|
||||
const SAMPLE_PAGE: AdminArticlesPage = {
|
||||
articles: [
|
||||
{
|
||||
id: 1,
|
||||
title: 'First story',
|
||||
content: '<p>Hello</p>',
|
||||
author_id: 7,
|
||||
category_id: 1,
|
||||
author: { id: 7, name: 'Ada Lovelace', email: 'ada@example.com' },
|
||||
category: { id: 1, name: 'Technology', slug: 'technology' },
|
||||
published: true,
|
||||
created_at: '2024-05-01T12:00:00Z',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
total_pages: 1,
|
||||
};
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
statusText: 'OK',
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body),
|
||||
} as Response;
|
||||
}
|
||||
|
||||
describe('admin API client', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
});
|
||||
|
||||
it('listArticles builds the query string from all parameters', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'admin-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
|
||||
|
||||
const res = await adminListArticles({
|
||||
page: 2,
|
||||
pageSize: 50,
|
||||
search: ' breaking news ',
|
||||
sortBy: 'title',
|
||||
sortOrder: 'asc',
|
||||
});
|
||||
|
||||
expect(res).toEqual(SAMPLE_PAGE);
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
// URLSearchParams encodes spaces as `+`.
|
||||
expect(url).toBe(
|
||||
'/api/v1/admin/articles?page=2&page_size=50&search=breaking+news&sort_by=title&sort_order=asc',
|
||||
);
|
||||
expect(init.method).toBeUndefined();
|
||||
// The JWT is attached as a Bearer token.
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer admin-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('listArticles omits the search parameter when empty', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
|
||||
|
||||
await adminListArticles({
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
search: ' ',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'desc',
|
||||
});
|
||||
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe(
|
||||
'/api/v1/admin/articles?page=1&page_size=20&sort_by=created_at&sort_order=desc',
|
||||
);
|
||||
});
|
||||
|
||||
it('getArticle requests the article by id', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.articles[0]));
|
||||
|
||||
await adminGetArticle(7);
|
||||
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/articles/7');
|
||||
});
|
||||
|
||||
it('createArticle POSTs the payload', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.articles[0]));
|
||||
|
||||
await adminCreateArticle({
|
||||
title: 'New story',
|
||||
content: '<p>Body</p>',
|
||||
author_id: 7,
|
||||
category_id: 2,
|
||||
published: false,
|
||||
});
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/articles');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
title: 'New story',
|
||||
content: '<p>Body</p>',
|
||||
author_id: 7,
|
||||
category_id: 2,
|
||||
published: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('updateArticle PUTs the payload to the article route', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.articles[0]));
|
||||
|
||||
await adminUpdateArticle(7, {
|
||||
title: 'Updated',
|
||||
content: '<p>Body</p>',
|
||||
author_id: 8,
|
||||
category_id: 1,
|
||||
published: true,
|
||||
});
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/articles/7');
|
||||
expect(init.method).toBe('PUT');
|
||||
});
|
||||
|
||||
it('deleteArticle sends DELETE and resolves to undefined on 204', async () => {
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 204,
|
||||
statusText: 'No Content',
|
||||
} as Response);
|
||||
|
||||
await expect(adminDeleteArticle(7)).resolves.toBeUndefined();
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/articles/7');
|
||||
expect(init.method).toBe('DELETE');
|
||||
});
|
||||
|
||||
it('listAuthors requests the author reference list', async () => {
|
||||
const authors = [{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com', bio: null }];
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, authors));
|
||||
|
||||
const res = await adminListAuthors();
|
||||
|
||||
expect(res).toEqual(authors);
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/authors');
|
||||
});
|
||||
|
||||
it('listCategories requests the category reference list', async () => {
|
||||
const categories = [{ id: 1, name: 'Technology', slug: 'technology' }];
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, categories));
|
||||
|
||||
const res = await adminListCategories();
|
||||
|
||||
expect(res).toEqual(categories);
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/categories');
|
||||
});
|
||||
|
||||
it('surfaces the backend error for non-admin access (403)', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'non-admin-token');
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(403, { detail: 'Admin access required', code: 'forbidden' }),
|
||||
);
|
||||
|
||||
const err = await adminListArticles({
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
search: '',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'desc',
|
||||
}).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(ApiError);
|
||||
expect((err as ApiError).status).toBe(403);
|
||||
expect((err as ApiError).code).toBe('forbidden');
|
||||
expect((err as ApiError).message).toBe('Admin access required');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
/**
|
||||
* Tests for the AdminDashboard list view (M6): rendering, debounced
|
||||
* search, sorting, pagination and the delete confirmation flow.
|
||||
*/
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
adminDeleteArticle,
|
||||
adminListArticles,
|
||||
} from '../../api/admin';
|
||||
import { AdminDashboard } from '../../pages/AdminDashboard';
|
||||
import type { AdminArticlesPage } from '../../types/admin';
|
||||
|
||||
vi.mock('../../api/admin', () => ({
|
||||
adminListArticles: vi.fn(),
|
||||
adminGetArticle: vi.fn(),
|
||||
adminCreateArticle: vi.fn(),
|
||||
adminUpdateArticle: vi.fn(),
|
||||
adminDeleteArticle: vi.fn(),
|
||||
adminListAuthors: vi.fn(),
|
||||
adminListCategories: vi.fn(),
|
||||
}));
|
||||
|
||||
const AUTHORS = [
|
||||
{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
|
||||
{ id: 2, name: 'Grace Hopper', email: 'grace@example.com' },
|
||||
];
|
||||
const CATEGORIES = [
|
||||
{ id: 1, name: 'Technology', slug: 'technology' },
|
||||
{ id: 2, name: 'Science', slug: 'science' },
|
||||
];
|
||||
|
||||
const article = (id: number, overrides: Record<string, unknown> = {}) => ({
|
||||
id,
|
||||
title: `Story ${id}`,
|
||||
content: `<p>Body ${id}</p>`,
|
||||
author_id: AUTHORS[(id - 1) % AUTHORS.length].id,
|
||||
category_id: CATEGORIES[(id - 1) % CATEGORIES.length].id,
|
||||
author: AUTHORS[(id - 1) % AUTHORS.length],
|
||||
category: CATEGORIES[(id - 1) % CATEGORIES.length],
|
||||
published: true,
|
||||
created_at: `2024-05-0${(id % 9) + 1}T12:00:00Z`,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const articles = (count: number, offset = 0) =>
|
||||
Array.from({ length: count }, (_, i) => article(i + 1 + offset));
|
||||
|
||||
const page = (overrides: Partial<AdminArticlesPage> = {}): AdminArticlesPage => ({
|
||||
articles: articles(3),
|
||||
total: 3,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
total_pages: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function lastCallParams(): {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
search: string;
|
||||
sortBy: string;
|
||||
sortOrder: string;
|
||||
} {
|
||||
const calls = vi.mocked(adminListArticles).mock.calls;
|
||||
const last = calls[calls.length - 1][0];
|
||||
return {
|
||||
page: last.page,
|
||||
pageSize: last.pageSize,
|
||||
search: last.search,
|
||||
sortBy: last.sortBy,
|
||||
sortOrder: last.sortOrder,
|
||||
};
|
||||
}
|
||||
|
||||
function renderDashboard() {
|
||||
return render(
|
||||
<MemoryRouter
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AdminDashboard />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('AdminDashboard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(adminListArticles).mockResolvedValue(page());
|
||||
vi.mocked(adminDeleteArticle).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('renders the fetched articles with their details', async () => {
|
||||
renderDashboard();
|
||||
|
||||
expect(await screen.findByText('Story 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Story 2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Story 3')).toBeInTheDocument();
|
||||
// Each row shows its author and category.
|
||||
expect(screen.getAllByText('Ada Lovelace').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('Grace Hopper').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('Technology').length).toBeGreaterThan(0);
|
||||
expect(screen.getByText('Showing 1–3 of 3')).toBeInTheDocument();
|
||||
// Published badges: one per row (the "Published" column header is a
|
||||
// columnheader role, not a cell).
|
||||
expect(screen.getAllByRole('cell', { name: 'Published' })).toHaveLength(3);
|
||||
// Edit links point at the edit route.
|
||||
const editLinks = screen.getAllByRole('link', { name: /edit/i });
|
||||
expect(editLinks[0].getAttribute('href')).toBe('/admin/articles/1/edit');
|
||||
});
|
||||
|
||||
it('requests the initial page with the default parameters', async () => {
|
||||
renderDashboard();
|
||||
await screen.findByText('Story 1');
|
||||
expect(lastCallParams()).toEqual({
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
search: '',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'desc',
|
||||
});
|
||||
});
|
||||
|
||||
it('debounces the search and filters by it', async () => {
|
||||
renderDashboard();
|
||||
await screen.findByText('Story 1');
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Search articles'), {
|
||||
target: { value: 'breaking' },
|
||||
});
|
||||
|
||||
// Immediately after typing: still the original request (debounce).
|
||||
expect(lastCallParams().search).toBe('');
|
||||
|
||||
// After the 300ms debounce the API is called with the search term.
|
||||
await waitFor(() => expect(lastCallParams().search).toBe('breaking'), {
|
||||
timeout: 1500,
|
||||
});
|
||||
// Searching resets to page 1.
|
||||
expect(lastCallParams().page).toBe(1);
|
||||
});
|
||||
|
||||
it('toggles sort direction when clicking the same column twice', async () => {
|
||||
renderDashboard();
|
||||
await screen.findByText('Story 1');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /sort by title/i }));
|
||||
expect(lastCallParams().sortBy).toBe('title');
|
||||
expect(lastCallParams().sortOrder).toBe('asc');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /sort by title/i }));
|
||||
expect(lastCallParams().sortBy).toBe('title');
|
||||
expect(lastCallParams().sortOrder).toBe('desc');
|
||||
|
||||
// Switching columns starts on ascending again.
|
||||
fireEvent.click(screen.getByRole('button', { name: /sort by creation date/i }));
|
||||
expect(lastCallParams().sortBy).toBe('created_at');
|
||||
expect(lastCallParams().sortOrder).toBe('asc');
|
||||
});
|
||||
|
||||
it('navigates pages and changes the page size', async () => {
|
||||
vi.mocked(adminListArticles).mockResolvedValue(
|
||||
page({ total: 45, page: 2, total_pages: 3 }),
|
||||
);
|
||||
renderDashboard();
|
||||
await screen.findByText('Story 1');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /next/i }));
|
||||
await waitFor(() => expect(lastCallParams().page).toBe(2));
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /previous/i }));
|
||||
await waitFor(() => expect(lastCallParams().page).toBe(1));
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Rows per page'), {
|
||||
target: { value: '50' },
|
||||
});
|
||||
await waitFor(() => expect(lastCallParams().pageSize).toBe(50));
|
||||
expect(lastCallParams().page).toBe(1);
|
||||
});
|
||||
|
||||
it('shows an empty state when nothing matches the search', async () => {
|
||||
vi.mocked(adminListArticles).mockResolvedValue(page({ articles: [], total: 0 }));
|
||||
renderDashboard();
|
||||
await screen.findByText(/no articles yet/i);
|
||||
});
|
||||
|
||||
it('shows the error state with a retry action', async () => {
|
||||
vi.mocked(adminListArticles).mockRejectedValue(new Error('boom'));
|
||||
renderDashboard();
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/boom|went wrong/i);
|
||||
screen.getByRole('button', { name: /retry/i }).click();
|
||||
await waitFor(() =>
|
||||
expect(vi.mocked(adminListArticles).mock.calls.length).toBeGreaterThanOrEqual(2),
|
||||
);
|
||||
});
|
||||
|
||||
it('deletes an article only after explicit confirmation', async () => {
|
||||
renderDashboard();
|
||||
await screen.findByText('Story 1');
|
||||
|
||||
// Open the dialog.
|
||||
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(dialog).toHaveTextContent('Story 1');
|
||||
expect(vi.mocked(adminDeleteArticle)).not.toHaveBeenCalled();
|
||||
|
||||
// Cancel: no API call.
|
||||
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
|
||||
expect(await screen.findByText('Story 1')).toBeInTheDocument();
|
||||
expect(vi.mocked(adminDeleteArticle)).not.toHaveBeenCalled();
|
||||
|
||||
// Confirm: the API is called and the list refreshes.
|
||||
const listCallsBefore = vi.mocked(adminListArticles).mock.calls.length;
|
||||
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
||||
await screen.findByRole('dialog');
|
||||
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(vi.mocked(adminDeleteArticle)).toHaveBeenCalledWith(1),
|
||||
);
|
||||
expect(
|
||||
vi.mocked(adminListArticles).mock.calls.length,
|
||||
).toBeGreaterThanOrEqual(listCallsBefore + 1);
|
||||
});
|
||||
|
||||
it('keeps the dialog open and shows the error when the delete fails', async () => {
|
||||
vi.mocked(adminDeleteArticle).mockRejectedValue(
|
||||
new Error('Deleting the article failed.') as Error & { status?: number },
|
||||
);
|
||||
renderDashboard();
|
||||
await screen.findByText('Story 1');
|
||||
|
||||
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
||||
await screen.findByRole('dialog');
|
||||
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
|
||||
|
||||
const alert = await screen.findByRole('alert');
|
||||
expect(alert).toHaveTextContent(/deleting the article failed/i);
|
||||
// Dialog still open.
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Tests for the DeleteConfirmation modal (M6): warning layout, explicit
|
||||
* "Yes, delete" confirmation, cancel/Escape/overlay dismissal and the
|
||||
* busy state while the request is in flight.
|
||||
*/
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { DeleteConfirmation } from '../../components/DeleteConfirmation';
|
||||
import type { AdminArticle } from '../../types/admin';
|
||||
|
||||
const ARTICLE: AdminArticle = {
|
||||
id: 42,
|
||||
title: 'Breaking: the sky is falling',
|
||||
content: '<p>…</p>',
|
||||
author_id: 1,
|
||||
category_id: 1,
|
||||
author: { id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
|
||||
category: { id: 1, name: 'Technology', slug: 'technology' },
|
||||
published: true,
|
||||
created_at: '2024-05-01T12:00:00Z',
|
||||
};
|
||||
|
||||
function renderModal(props: Partial<Parameters<typeof DeleteConfirmation>[0]> = {}) {
|
||||
const onConfirm = vi.fn();
|
||||
const onCancel = vi.fn();
|
||||
const utils = render(
|
||||
<DeleteConfirmation
|
||||
article={ARTICLE}
|
||||
onConfirm={onConfirm}
|
||||
onCancel={onCancel}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
return { onConfirm, onCancel, ...utils };
|
||||
}
|
||||
|
||||
describe('DeleteConfirmation', () => {
|
||||
it('shows the warning layout with the article title', () => {
|
||||
renderModal();
|
||||
|
||||
const dialog = screen.getByRole('dialog');
|
||||
expect(
|
||||
screen.getByRole('heading', { name: /are you sure you want to delete/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(dialog).toHaveTextContent('Breaking: the sky is falling');
|
||||
expect(dialog).toHaveTextContent(/cannot be undone/i);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /yes, delete/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onConfirm when "Yes, delete" is clicked', () => {
|
||||
const { onConfirm } = renderModal();
|
||||
|
||||
fireEvent.click(screen.getByTestId('confirm-delete'));
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls onCancel when Cancel is clicked', () => {
|
||||
const { onCancel } = renderModal();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes on overlay click but not on dialog click', () => {
|
||||
const { onCancel } = renderModal();
|
||||
const dialog = screen.getByRole('dialog');
|
||||
const overlay = dialog.parentElement as HTMLElement;
|
||||
|
||||
fireEvent.click(overlay);
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.click(dialog);
|
||||
expect(onCancel).toHaveBeenCalledTimes(1); // unchanged — stopPropagation
|
||||
});
|
||||
|
||||
it('closes on the Escape key', () => {
|
||||
const { onCancel } = renderModal();
|
||||
|
||||
act(() => {
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
});
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('disables both actions and ignores Escape while busy', () => {
|
||||
const { onCancel } = renderModal({ busy: true });
|
||||
|
||||
const confirm = screen.getByRole('button', { name: /deleting…/i });
|
||||
const cancel = screen.getByRole('button', { name: /cancel/i });
|
||||
expect(confirm).toBeDisabled();
|
||||
expect(cancel).toBeDisabled();
|
||||
expect(confirm).toHaveTextContent(/deleting…/i);
|
||||
|
||||
act(() => {
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
});
|
||||
fireEvent.click(cancel);
|
||||
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders an error message when provided', () => {
|
||||
renderModal({ error: 'Deleting the article failed.' });
|
||||
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Deleting the article failed.');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,289 @@
|
||||
/**
|
||||
* Tests for the EditArticlePage (M6): create/edit form validation,
|
||||
* reference-list prefill in create mode, prefill in edit mode, save
|
||||
* flows (success navigation + error display) and the load-failure view.
|
||||
* The Lexical editor is stubbed; its HTML contract is exercised through
|
||||
* the `editor-body` textarea.
|
||||
*/
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
adminCreateArticle,
|
||||
adminGetArticle,
|
||||
adminListAuthors,
|
||||
adminListCategories,
|
||||
adminUpdateArticle,
|
||||
} from '../../api/admin';
|
||||
import { ApiError } from '../../api/client';
|
||||
import { EditArticlePage as EditPage } from '../../pages/EditArticlePage';
|
||||
import type { AdminArticle } from '../../types/admin';
|
||||
|
||||
vi.mock('../../api/admin', () => ({
|
||||
adminListArticles: vi.fn(),
|
||||
adminGetArticle: vi.fn(),
|
||||
adminCreateArticle: vi.fn(),
|
||||
adminUpdateArticle: vi.fn(),
|
||||
adminDeleteArticle: vi.fn(),
|
||||
adminListAuthors: vi.fn(),
|
||||
adminListCategories: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../components/LexicalEditor', () => ({
|
||||
LexicalEditor: ({
|
||||
initialHtml,
|
||||
onChange,
|
||||
}: {
|
||||
initialHtml: string;
|
||||
onChange: (html: string) => void;
|
||||
placeholder?: string;
|
||||
}) => (
|
||||
<div data-testid="lexical-stub">
|
||||
<textarea
|
||||
data-testid="editor-body"
|
||||
defaultValue={initialHtml}
|
||||
aria-label="Article content"
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const AUTHORS = [
|
||||
{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
|
||||
{ id: 2, name: 'Grace Hopper', email: 'grace@example.com' },
|
||||
];
|
||||
const CATEGORIES = [
|
||||
{ id: 1, name: 'Technology', slug: 'technology' },
|
||||
{ id: 2, name: 'Science', slug: 'science' },
|
||||
];
|
||||
|
||||
const ARTICLE: AdminArticle = {
|
||||
id: 5,
|
||||
title: 'Original headline',
|
||||
content: '<p>Original body</p>',
|
||||
author_id: 2,
|
||||
category_id: 1,
|
||||
author: AUTHORS[1],
|
||||
category: CATEGORIES[0],
|
||||
published: true,
|
||||
created_at: '2024-05-01T12:00:00Z',
|
||||
};
|
||||
|
||||
function DashboardStub() {
|
||||
const location = useLocation();
|
||||
const notice = (location.state as { notice?: string } | null)?.notice ?? '';
|
||||
return (
|
||||
<div data-testid="dashboard-stub">
|
||||
{notice && <p data-testid="dashboard-notice">{notice}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderAt(path: string) {
|
||||
return render(
|
||||
<MemoryRouter
|
||||
initialEntries={[path]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<Routes>
|
||||
<Route path="/admin" element={<DashboardStub />} />
|
||||
<Route path="/admin/articles/new" element={<EditPage />} />
|
||||
<Route path="/admin/articles/:id/edit" element={<EditPage />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('EditArticlePage (create)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(adminListAuthors).mockResolvedValue(AUTHORS);
|
||||
vi.mocked(adminListCategories).mockResolvedValue(CATEGORIES);
|
||||
vi.mocked(adminCreateArticle).mockResolvedValue({ ...ARTICLE, id: 99 });
|
||||
vi.mocked(adminUpdateArticle).mockResolvedValue(ARTICLE);
|
||||
});
|
||||
|
||||
it('pre-fills the first author and category from the reference lists', async () => {
|
||||
renderAt('/admin/articles/new');
|
||||
|
||||
await screen.findByTestId('lexical-stub');
|
||||
await waitFor(() =>
|
||||
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||
);
|
||||
expect(screen.getByLabelText(/^Category/)).toHaveValue('1');
|
||||
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('New article');
|
||||
});
|
||||
|
||||
it('blocks submission with an empty title and does not call the API', async () => {
|
||||
renderAt('/admin/articles/new');
|
||||
await screen.findByTestId('lexical-stub');
|
||||
await waitFor(() =>
|
||||
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||
);
|
||||
|
||||
screen.getByRole('button', { name: /create article/i }).click();
|
||||
|
||||
// The field error and the form-level error are both alerts.
|
||||
const alerts = await screen.findAllByRole('alert');
|
||||
expect(
|
||||
alerts.some((el) => /title is required/i.test(el.textContent ?? '')),
|
||||
).toBe(true);
|
||||
expect(vi.mocked(adminCreateArticle)).not.toHaveBeenCalled();
|
||||
expect(screen.queryByTestId('dashboard-stub')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('blocks submission with an empty body', async () => {
|
||||
renderAt('/admin/articles/new');
|
||||
await screen.findByTestId('lexical-stub');
|
||||
await waitFor(() =>
|
||||
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Only a title' } });
|
||||
screen.getByRole('button', { name: /create article/i }).click();
|
||||
|
||||
const alerts = await screen.findAllByRole('alert');
|
||||
expect(
|
||||
alerts.some((el) => /content is required/i.test(el.textContent ?? '')),
|
||||
).toBe(true);
|
||||
expect(vi.mocked(adminCreateArticle)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates the article with trimmed values and navigates back with a notice', async () => {
|
||||
renderAt('/admin/articles/new');
|
||||
await screen.findByTestId('lexical-stub');
|
||||
await waitFor(() =>
|
||||
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/^Title/), {
|
||||
target: { value: ' Fresh story ' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/^Author/), { target: { value: '2' } });
|
||||
fireEvent.change(screen.getByLabelText(/^Category/), { target: { value: '2' } });
|
||||
fireEvent.click(screen.getByLabelText(/^Published/));
|
||||
fireEvent.change(screen.getByTestId('editor-body'), {
|
||||
target: { value: '<p>Body <strong>here</strong></p>' },
|
||||
});
|
||||
|
||||
screen.getByRole('button', { name: /create article/i }).click();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(vi.mocked(adminCreateArticle)).toHaveBeenCalledWith({
|
||||
title: 'Fresh story',
|
||||
content: '<p>Body <strong>here</strong></p>',
|
||||
author_id: 2,
|
||||
category_id: 2,
|
||||
published: true,
|
||||
}),
|
||||
);
|
||||
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('dashboard-notice')).toHaveTextContent(
|
||||
'“Fresh story” was saved.',
|
||||
);
|
||||
});
|
||||
|
||||
it('disables the create button while the request is in flight', async () => {
|
||||
let resolveCreate!: (value: AdminArticle) => void;
|
||||
vi.mocked(adminCreateArticle).mockReturnValueOnce(
|
||||
new Promise<AdminArticle>((resolve) => {
|
||||
resolveCreate = resolve;
|
||||
}),
|
||||
);
|
||||
renderAt('/admin/articles/new');
|
||||
await screen.findByTestId('lexical-stub');
|
||||
await waitFor(() =>
|
||||
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Pending' } });
|
||||
fireEvent.change(screen.getByTestId('editor-body'), {
|
||||
target: { value: '<p>Body</p>' },
|
||||
});
|
||||
screen.getByRole('button', { name: /create article/i }).click();
|
||||
|
||||
const button = screen.getByRole('button', { name: /create article/i });
|
||||
await waitFor(() => expect(button).toBeDisabled());
|
||||
|
||||
resolveCreate({ ...ARTICLE, id: 99, title: 'Pending' });
|
||||
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the backend error when the create request fails', async () => {
|
||||
vi.mocked(adminCreateArticle).mockRejectedValue(
|
||||
new ApiError(422, 'Validation failed', 'validation_error'),
|
||||
);
|
||||
renderAt('/admin/articles/new');
|
||||
await screen.findByTestId('lexical-stub');
|
||||
await waitFor(() =>
|
||||
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'x' } });
|
||||
fireEvent.change(screen.getByTestId('editor-body'), {
|
||||
target: { value: '<p>Body</p>' },
|
||||
});
|
||||
screen.getByRole('button', { name: /create article/i }).click();
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Validation failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditArticlePage (edit)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(adminListAuthors).mockResolvedValue(AUTHORS);
|
||||
vi.mocked(adminListCategories).mockResolvedValue(CATEGORIES);
|
||||
vi.mocked(adminGetArticle).mockResolvedValue(ARTICLE);
|
||||
vi.mocked(adminUpdateArticle).mockResolvedValue(ARTICLE);
|
||||
});
|
||||
|
||||
it('loads and pre-fills the article, then updates it on save', async () => {
|
||||
renderAt('/admin/articles/5/edit');
|
||||
|
||||
// Loading state first.
|
||||
expect(screen.getByRole('status')).toHaveTextContent(/loading article/i);
|
||||
|
||||
await screen.findByTestId('lexical-stub');
|
||||
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(
|
||||
'Edit article #5',
|
||||
);
|
||||
expect(screen.getByLabelText(/^Title/)).toHaveValue('Original headline');
|
||||
expect(screen.getByLabelText(/^Author/)).toHaveValue('2');
|
||||
expect(screen.getByLabelText(/^Category/)).toHaveValue('1');
|
||||
expect(screen.getByLabelText(/^Published/)).toBeChecked();
|
||||
expect(screen.getByTestId('editor-body')).toHaveValue('<p>Original body</p>');
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/^Title/), {
|
||||
target: { value: 'Retitled' },
|
||||
});
|
||||
screen.getByRole('button', { name: /save changes/i }).click();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(vi.mocked(adminUpdateArticle)).toHaveBeenCalledWith(5, {
|
||||
title: 'Retitled',
|
||||
content: '<p>Original body</p>',
|
||||
author_id: 2,
|
||||
category_id: 1,
|
||||
published: true,
|
||||
}),
|
||||
);
|
||||
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the not-found view when the article cannot be loaded', async () => {
|
||||
vi.mocked(adminGetArticle).mockRejectedValue(
|
||||
new ApiError(404, 'Article not found', 'not_found'),
|
||||
);
|
||||
renderAt('/admin/articles/999/edit');
|
||||
|
||||
expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(
|
||||
/article not found/i,
|
||||
);
|
||||
expect(screen.getByRole('link', { name: /back to articles/i })).toHaveAttribute(
|
||||
'href',
|
||||
'/admin',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Tests for the RequireAdmin route guard (M6): signed-out users are
|
||||
* redirected to /login, authenticated non-admins see the 403 page, and
|
||||
* admins get the protected content.
|
||||
*/
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, me as clientMe } from '../../api/client';
|
||||
import { AuthProvider, RequireAdmin } from '../../auth';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
const routes = (
|
||||
<Routes>
|
||||
<Route path="/login" element={<div>Login page</div>} />
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<RequireAdmin>
|
||||
<div data-testid="admin-content">Admin dashboard</div>
|
||||
</RequireAdmin>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
function renderAt(path: string) {
|
||||
return render(
|
||||
<MemoryRouter
|
||||
initialEntries={[path]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>{routes}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('RequireAdmin', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('redirects signed-out users to /login', async () => {
|
||||
renderAt('/admin');
|
||||
expect(await screen.findByText('Login page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the 403 page for an authenticated non-admin', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice', is_admin: false });
|
||||
localStorage.setItem(TOKEN_KEY, 'token');
|
||||
|
||||
renderAt('/admin');
|
||||
|
||||
expect(await screen.findByTestId('forbidden-page')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { level: 1, name: '403' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('alert')).toHaveTextContent(/admin area/i);
|
||||
expect(screen.queryByTestId('admin-content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('treats a missing is_admin flag as non-admin (defensive)', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'token');
|
||||
|
||||
renderAt('/admin');
|
||||
|
||||
expect(await screen.findByTestId('forbidden-page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the protected content for an admin', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
|
||||
localStorage.setItem(TOKEN_KEY, 'token');
|
||||
|
||||
renderAt('/admin');
|
||||
|
||||
expect(await screen.findByTestId('admin-content')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('forbidden-page')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import {
|
||||
TOKEN_KEY,
|
||||
login as clientLogin,
|
||||
logout as clientLogout,
|
||||
me as clientMe,
|
||||
register as clientRegister,
|
||||
} from '../api/client';
|
||||
import { AuthProvider, RequireAuth, useAuth } from '../auth';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
/** Renders the current auth state plus one trigger button per action. */
|
||||
function StateProbe() {
|
||||
const { username, ready, login, register, logout } = useAuth();
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="ready">{String(ready)}</span>
|
||||
<span data-testid="username">{username ?? 'null'}</span>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="do-login"
|
||||
onClick={() => {
|
||||
void login('login-user', 'password123');
|
||||
}}
|
||||
>
|
||||
login
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="do-register"
|
||||
onClick={() => {
|
||||
void register('register-user', 'password123');
|
||||
}}
|
||||
>
|
||||
register
|
||||
</button>
|
||||
<button type="button" data-testid="do-logout" onClick={logout}>
|
||||
logout
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe('AuthProvider', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('starts signed out without a stored token (no me() call)', async () => {
|
||||
renderWithAuth(<StateProbe />);
|
||||
expect(await screen.findByTestId('ready')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('null');
|
||||
expect(clientMe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restores the session from a valid stored token', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
|
||||
expect(await screen.findByTestId('username')).toHaveTextContent('alice');
|
||||
expect(clientMe).toHaveBeenCalledWith('valid-token');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('valid-token');
|
||||
});
|
||||
|
||||
it('clears an invalid stored token on restore failure', async () => {
|
||||
(clientMe as Mock).mockRejectedValue(new Error('401'));
|
||||
localStorage.setItem(TOKEN_KEY, 'expired-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
|
||||
expect(await screen.findByTestId('ready')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('null');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('login stores the returned token and sets the username', async () => {
|
||||
(clientLogin as Mock).mockResolvedValue({ token: 'new-token', username: 'login-user' });
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await screen.findByTestId('ready');
|
||||
screen.getByTestId('do-login').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('login-user'));
|
||||
expect(clientLogin).toHaveBeenCalledWith('login-user', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('new-token');
|
||||
});
|
||||
|
||||
it('register stores the returned token and sets the username', async () => {
|
||||
(clientRegister as Mock).mockResolvedValue({
|
||||
token: 'new-token',
|
||||
username: 'register-user',
|
||||
});
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await screen.findByTestId('ready');
|
||||
screen.getByTestId('do-register').click();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('register-user'),
|
||||
);
|
||||
expect(clientRegister).toHaveBeenCalledWith('register-user', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('new-token');
|
||||
});
|
||||
|
||||
it('logout calls the API best-effort and clears the session', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
(clientLogout as Mock).mockResolvedValue(undefined);
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('alice'));
|
||||
screen.getByTestId('do-logout').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('null'));
|
||||
expect(clientLogout).toHaveBeenCalledTimes(1);
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('logout still clears the session when the API call fails', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
(clientLogout as Mock).mockRejectedValue(new Error('network down'));
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('alice'));
|
||||
screen.getByTestId('do-logout').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('null'));
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RequireAuth', () => {
|
||||
const routes = (
|
||||
<Routes>
|
||||
<Route path="/login" element={<div>Login page</div>} />
|
||||
<Route
|
||||
path="/account"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<div>Account page</div>
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
const renderProtected = (initialPath: string) =>
|
||||
render(
|
||||
<MemoryRouter
|
||||
initialEntries={[initialPath]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>{routes}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users to /login', async () => {
|
||||
renderProtected('/account');
|
||||
expect(await screen.findByText('Login page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders protected content for a signed-in user', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderProtected('/account');
|
||||
expect(await screen.findByText('Account page')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Unit tests for the auth methods of the API client (token attachment,
|
||||
* 401 handling, request/response shapes).
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ApiError, login, logout, me, register, TOKEN_KEY } from '../api/client';
|
||||
|
||||
/** Minimal fetch Response look-alike for the client. */
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
statusText: 'OK',
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body),
|
||||
} as Response;
|
||||
}
|
||||
|
||||
describe('auth API client', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
});
|
||||
|
||||
it('login posts credentials to /auth/login and returns the token payload', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { token: 'tok', username: 'alice' }));
|
||||
|
||||
const res = await login('alice', 'password123');
|
||||
|
||||
expect(res).toEqual({ token: 'tok', username: 'alice' });
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/login');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
username: 'alice',
|
||||
password: 'password123',
|
||||
});
|
||||
});
|
||||
|
||||
it('register posts to /auth/register', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(201, { token: 'tok', username: 'bob' }));
|
||||
|
||||
await register('bob', 'password123');
|
||||
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/register');
|
||||
});
|
||||
|
||||
it('attaches the stored token as a Bearer Authorization header', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'stored-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me();
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer stored-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('sends no Authorization header without a stored token', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me();
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBeUndefined();
|
||||
});
|
||||
|
||||
it('me() prefers an explicit token over the stored one', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'stored-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me('explicit-token');
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer explicit-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the stored token on a 401 response', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'dead-token');
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(401, { detail: 'Invalid or expired token', code: 'unauthorized' }),
|
||||
);
|
||||
|
||||
await expect(me('dead-token')).rejects.toBeInstanceOf(ApiError);
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces the backend error detail for failed registrations', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(400, { detail: 'Username already exists', code: 'bad_request' }),
|
||||
);
|
||||
|
||||
const err = await register('alice', 'password123').catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(ApiError);
|
||||
expect((err as ApiError).status).toBe(400);
|
||||
expect((err as ApiError).code).toBe('bad_request');
|
||||
expect((err as ApiError).message).toBe('Username already exists');
|
||||
});
|
||||
|
||||
it('logout posts to /auth/logout and resolves to undefined', async () => {
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 204,
|
||||
statusText: 'No Content',
|
||||
} as Response);
|
||||
|
||||
await expect(logout()).resolves.toBeUndefined();
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/logout');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(init.body).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, login as clientLogin } from '../../api/client';
|
||||
import { AuthProvider } from '../../auth';
|
||||
import Login from '../../pages/Login';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderLogin() {
|
||||
return (
|
||||
<MemoryRouter
|
||||
initialEntries={['/login']}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={<div>Home page</div>} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
async function fillLoginForm(username: string, password: string) {
|
||||
fireEvent.change(screen.getByLabelText('Username'), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
|
||||
const form = screen.getByRole('button', { name: /sign in/i }).closest('form');
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
}
|
||||
|
||||
describe('Login page', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the form fields and a link to registration', () => {
|
||||
render(renderLogin());
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();
|
||||
expect(screen.getByRole('link', { name: /register/i })).toHaveAttribute('href', '/register');
|
||||
});
|
||||
|
||||
it('blocks submission with empty fields', async () => {
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
const form = screen.getByRole('button', { name: /sign in/i }).closest('form');
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'Please enter both username and password.',
|
||||
);
|
||||
expect(clientLogin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('signs in, stores the token and navigates to home', async () => {
|
||||
(clientLogin as Mock).mockResolvedValue({ token: 'tok-123', username: 'alice' });
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'password123');
|
||||
|
||||
expect(await screen.findByText('Home page')).toBeInTheDocument();
|
||||
expect(clientLogin).toHaveBeenCalledWith('alice', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('tok-123');
|
||||
});
|
||||
|
||||
it('shows the backend error on failed login and stores no token', async () => {
|
||||
(clientLogin as Mock).mockRejectedValue(
|
||||
new Error('Invalid username or password'),
|
||||
);
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'wrong-password');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Invalid username or password');
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a loading state while the login request is pending', async () => {
|
||||
(clientLogin as Mock).mockReturnValue(new Promise(() => undefined));
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'password123');
|
||||
|
||||
expect(await screen.findByText('Signing in…')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /signing in/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, register as clientRegister } from '../../api/client';
|
||||
import { AuthProvider } from '../../auth';
|
||||
import Register from '../../pages/Register';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderRegister() {
|
||||
return (
|
||||
<MemoryRouter
|
||||
initialEntries={['/register']}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<div>Home page</div>} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
async function fillRegisterForm(
|
||||
username: string,
|
||||
password: string,
|
||||
confirm: string,
|
||||
): Promise<void> {
|
||||
fireEvent.change(screen.getByLabelText('Username'), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
|
||||
fireEvent.change(screen.getByLabelText('Confirm password'), {
|
||||
target: { value: confirm },
|
||||
});
|
||||
const form = screen.getByRole('button', { name: /register/i }).closest('form');
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
}
|
||||
|
||||
describe('Register page', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the form fields and a link to login', () => {
|
||||
render(renderRegister());
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Confirm password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /sign in/i })).toHaveAttribute('href', '/login');
|
||||
});
|
||||
|
||||
it('rejects mismatched passwords without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'different123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Passwords do not match.');
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects invalid usernames without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('ab', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/3–20 characters/);
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects short passwords without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'short', 'short');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/at least 8 characters/);
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('registers, stores the token and navigates to home', async () => {
|
||||
(clientRegister as Mock).mockResolvedValue({ token: 'tok-456', username: 'newuser' });
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByText('Home page')).toBeInTheDocument();
|
||||
expect(clientRegister).toHaveBeenCalledWith('newuser', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('tok-456');
|
||||
});
|
||||
|
||||
it('shows the backend error for an existing username', async () => {
|
||||
(clientRegister as Mock).mockRejectedValue(
|
||||
new Error('Username already exists'),
|
||||
);
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Username already exists');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,52 @@
|
||||
/**
|
||||
* Vitest setup: registers jest-dom matchers and cleans up the DOM after
|
||||
* every test (React Testing Library auto-cleanup needs this when globals
|
||||
* are disabled).
|
||||
* Vitest setup: registers jest-dom matchers, provides a working
|
||||
* `localStorage` and cleans up the DOM after every test (React Testing
|
||||
* Library auto-cleanup needs this when globals are disabled).
|
||||
*/
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
import { afterEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* In-memory Storage. Node >= 22 exposes an experimental `localStorage`
|
||||
* global that is `undefined` without `--localstorage-file`, and the jsdom
|
||||
* environment does not override it — so the auth tests (which persist the
|
||||
* JWT under AUTH_TOKEN) get a real storage implementation here.
|
||||
*/
|
||||
class MemoryStorage implements Storage {
|
||||
private store = new Map<string, string>();
|
||||
|
||||
get length(): number {
|
||||
return this.store.size;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
getItem(key: string): string | null {
|
||||
return this.store.has(key) ? this.store.get(key)! : null;
|
||||
}
|
||||
|
||||
key(index: number): string | null {
|
||||
return Array.from(this.store.keys())[index] ?? null;
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
setItem(key: string, value: string): void {
|
||||
this.store.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: new MemoryStorage(),
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
@@ -1,12 +1,23 @@
|
||||
import { render, type RenderOptions } from '@testing-library/react';
|
||||
import type { ReactElement } from 'react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
export interface RenderWithRouterOptions extends Omit<RenderOptions, 'wrapper'> {
|
||||
/** Initial route (path only, e.g. "/articles/1"). */
|
||||
route?: string;
|
||||
}
|
||||
|
||||
interface RouterFutureFlags {
|
||||
v7_startTransition: boolean;
|
||||
v7_relativeSplatPath: boolean;
|
||||
}
|
||||
|
||||
const ROUTER_FUTURE: RouterFutureFlags = {
|
||||
v7_startTransition: true,
|
||||
v7_relativeSplatPath: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Render helper that wraps the UI in a MemoryRouter so components using
|
||||
* react-router-dom (Link, NavLink, useParams) can be tested in isolation.
|
||||
@@ -15,12 +26,26 @@ export function renderWithRouter(ui: ReactElement, options: RenderWithRouterOpti
|
||||
const { route = '/', ...renderOptions } = options;
|
||||
|
||||
return render(
|
||||
<MemoryRouter
|
||||
initialEntries={[route]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<MemoryRouter initialEntries={[route]} future={ROUTER_FUTURE}>
|
||||
{ui}
|
||||
</MemoryRouter>,
|
||||
renderOptions,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render helper for auth-aware components: additionally wraps the UI in
|
||||
* the app's `AuthProvider`. Tests that care about the auth API should
|
||||
* mock `../api/client`; with an empty localStorage no network calls are
|
||||
* made during session restore.
|
||||
*/
|
||||
export function renderWithAuth(ui: ReactElement, options: RenderWithRouterOptions = {}) {
|
||||
const { route = '/', ...renderOptions } = options;
|
||||
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[route]} future={ROUTER_FUTURE}>
|
||||
<AuthProvider>{ui}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
renderOptions,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Admin area types (mirror the backend `schemas.article` payloads).
|
||||
*
|
||||
* The backend returns snake_case JSON; these interfaces keep the wire
|
||||
* shape 1:1 (no remapping) because they are only consumed by the admin
|
||||
* pages. The related `author` and `category` are always embedded by the
|
||||
* backend (`ArticleRead`), so they are required here.
|
||||
*/
|
||||
import type { Author, Category } from './index';
|
||||
|
||||
/** One article as managed in the admin area. */
|
||||
export interface AdminArticle {
|
||||
id: number;
|
||||
title: string;
|
||||
/** HTML body produced by the Lexical editor. */
|
||||
content: string;
|
||||
author_id: number;
|
||||
category_id: number;
|
||||
/** Embedded author (always present on the wire). */
|
||||
author: Author;
|
||||
/** Embedded category (always present on the wire). */
|
||||
category: Category;
|
||||
/** Whether the article is visible on the public site. */
|
||||
published: boolean;
|
||||
/** ISO-8601 timestamp. */
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** Payload of `GET /api/v1/admin/articles` (paginated list). */
|
||||
export interface AdminArticlesPage {
|
||||
articles: AdminArticle[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
/** Sortable columns of the article list. */
|
||||
export type AdminSortBy = 'title' | 'created_at';
|
||||
|
||||
export type AdminSortOrder = 'asc' | 'desc';
|
||||
|
||||
/** Query parameters of the article list endpoint. */
|
||||
export interface AdminListParams {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
/** Case-insensitive match on title OR content. */
|
||||
search: string;
|
||||
sortBy: AdminSortBy;
|
||||
sortOrder: AdminSortOrder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload of `POST /api/v1/admin/articles` and
|
||||
* `PUT /api/v1/admin/articles/{id}`.
|
||||
*/
|
||||
export interface AdminArticleInput {
|
||||
title: string;
|
||||
content: string;
|
||||
author_id: number;
|
||||
category_id: number;
|
||||
published: boolean;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Auth API types (mirror the backend `schemas.auth` payloads).
|
||||
*/
|
||||
|
||||
/** Payload of `POST /api/v1/auth/register` and `POST /api/v1/auth/login`. */
|
||||
export interface TokenResponse {
|
||||
/** Signed JWT (7-day expiry) — store and send back as `Bearer` token. */
|
||||
token: string;
|
||||
username: string;
|
||||
/** Whether the account may access the admin area (M6). */
|
||||
is_admin?: boolean;
|
||||
}
|
||||
|
||||
/** Payload of `GET /api/v1/auth/me`. */
|
||||
export interface MeResponse {
|
||||
username: string;
|
||||
/** Whether the account may access the admin area (M6). */
|
||||
is_admin?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
# M4: Setup Developer Environment
|
||||
|
||||
## Prompt
|
||||
|
||||
Set up a complete developer environment for **newzy** news web application with Docker Compose orchestration. Follow these steps:
|
||||
|
||||
1. Create `docker-compose.yml` at project root (`newzy/docker-compose.yml`) with all services:
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
backend:
|
||||
build: ./backend
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./data/db:/app/data/db
|
||||
environment:
|
||||
- DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||
- DEBUG=false
|
||||
|
||||
frontend:
|
||||
build: ./frontend
|
||||
ports:
|
||||
- "3000:80"
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
networks:
|
||||
newzy-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
db-data:
|
||||
```
|
||||
|
||||
2. Create `.env.example` file documenting all required environment variables:
|
||||
- DATABASE_URL (SQLite path)
|
||||
- DEBUG (boolean, optional)
|
||||
- BACKEND_CORS_ORIGINS (comma-separated, default: http://localhost:3000)
|
||||
- FRONTEND_API_URL (relative /api or absolute)
|
||||
|
||||
3. Create `.env` file with default development values:
|
||||
```bash
|
||||
DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||
DEBUG=false
|
||||
BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
|
||||
FRONTEND_API_URL=/api
|
||||
```
|
||||
|
||||
4. Update `backend/.gitignore` to exclude `.env` and production data:
|
||||
```python
|
||||
.env
|
||||
.env.*
|
||||
data/
|
||||
```
|
||||
|
||||
5. Create development scripts in project root using Makefile or shell script:
|
||||
- `dev` - Start both services in background
|
||||
- `stop` - Stop all services
|
||||
- `restart` - Restart all services
|
||||
- `backend-start` - Start backend only
|
||||
- `frontend-start` - Start frontend only
|
||||
- `test` - Run all tests (unit + E2E)
|
||||
- `clean` - Remove containers and volumes
|
||||
|
||||
6. Add `Makefile` for command shortcuts:
|
||||
```makefile
|
||||
.PHONY: dev stop restart backend-start frontend-start test clean
|
||||
|
||||
dev:
|
||||
docker compose up -d --build
|
||||
|
||||
stop:
|
||||
docker compose down
|
||||
|
||||
restart:
|
||||
docker compose down
|
||||
docker compose up -d --build
|
||||
|
||||
backend-start:
|
||||
docker compose up -d backend
|
||||
|
||||
frontend-start:
|
||||
docker compose up -d frontend
|
||||
|
||||
test:
|
||||
npm run test # frontend
|
||||
cd backend && pytest # backend
|
||||
|
||||
clean:
|
||||
docker compose down -v
|
||||
rm -rf data/
|
||||
docker image prune -f
|
||||
```
|
||||
|
||||
7. Create `backend/Dockerfile` with development optimizations:
|
||||
- Copy only required files
|
||||
- Install dependencies efficiently
|
||||
- Use slim Python base image
|
||||
- Expose port 8000
|
||||
|
||||
8. Update `frontend/Dockerfile` to use production Nginx:
|
||||
- Multi-stage build (build stage + nginx serve stage)
|
||||
- Nginx configuration for SPA routing
|
||||
- Production-optimized static file serving
|
||||
|
||||
9. Create `.gitignore` at project root excluding:
|
||||
```
|
||||
# Dependencies
|
||||
node_modules/
|
||||
*.egg-info/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# IDE settings
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Docker artifacts (optional)
|
||||
.dockerignore
|
||||
docker-compose.override.yml
|
||||
```
|
||||
|
||||
10. Create `data/.gitignore` to exclude SQLite database from version control:
|
||||
```
|
||||
*
|
||||
!keep_files.txt
|
||||
```
|
||||
|
||||
11. Document setup process in `README.md`:
|
||||
- Prerequisites (Docker, Node.js 18+)
|
||||
- Quick start commands
|
||||
- Service descriptions
|
||||
- Port mappings
|
||||
- Network configuration
|
||||
- Troubleshooting guide
|
||||
|
||||
12. Create `.dockerignore` files for both backend and frontend to exclude unnecessary files during builds:
|
||||
```
|
||||
.git/
|
||||
.env
|
||||
__pycache__/
|
||||
*.pyc
|
||||
node_modules/
|
||||
dist/
|
||||
.pytest_cache/
|
||||
```
|
||||
|
||||
Remember: Focus ONLY on developer environment setup. No application code changes required.
|
||||
|
||||
## Description
|
||||
|
||||
This milestone sets up a complete Docker Compose development environment for the newzy news web application. The scope includes orchestrating both backend and frontend services, environment variable management, and streamlined development commands—no application logic changes or business feature implementation.
|
||||
|
||||
**Purpose**: Provide developers with a consistent, reproducible local development environment using Docker that matches the production setup as closely as possible.
|
||||
|
||||
**Target Audience**: Developers joining the project who need quick access to running services without manual installation of Python, Node.js, databases, or Nginx.
|
||||
|
||||
**Expected Outcomes**: A working docker-compose.yml at project root that can start all services with a single command, proper environment configuration, and development workflow automation via Makefile.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] `docker-compose.yml` at project root configures both backend and frontend services
|
||||
- [ ] Backend service builds from `./backend` directory
|
||||
- [ ] Frontend service builds from `./frontend` directory
|
||||
- [ ] Port mappings configured: 3000 for frontend, 8000 for backend
|
||||
- [ ] Docker network defined for inter-service communication
|
||||
- [ ] Volume mounted for persistent SQLite database at `/data/db`
|
||||
- [ ] `.env.example` file documents all environment variables
|
||||
- [ ] `.env` file provides default development configuration
|
||||
- [ ] `backend/Dockerfile` optimized for production use
|
||||
- [ ] `frontend/Dockerfile` uses multi-stage build with Nginx
|
||||
- [ ] Makefile or shell scripts provide dev, stop, restart commands
|
||||
- [ ] `data/.gitignore` excludes database from version control
|
||||
- [ ] `.dockerignore` files exist for both frontend and backend
|
||||
- [ ] Project root `.gitignore` excludes env files and build artifacts
|
||||
- [ ] README.md documents docker setup with quick start guide
|
||||
|
||||
## Technical Details
|
||||
|
||||
### docker-compose.yml (Project Root)
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./data/db:/app/data/db
|
||||
environment:
|
||||
- DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||
- DEBUG=false
|
||||
- BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
|
||||
depends_on:
|
||||
backend-db:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- newzy-network
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "3000:80"
|
||||
depends_on:
|
||||
- backend
|
||||
networks:
|
||||
- newzy-network
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
newzy-network:
|
||||
driver: bridge
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.28.0.0/16
|
||||
|
||||
volumes:
|
||||
db-data:
|
||||
name: newzy-db-data
|
||||
```
|
||||
|
||||
### Environment Variables (.env.example)
|
||||
|
||||
| Variable | Description | Default | Required |
|
||||
|----------|-------------|---------|----------|
|
||||
| DATABASE_URL | SQLite database path | sqlite:///./data/db/newzy.db | Yes |
|
||||
| DEBUG | Debug mode flag | false | No |
|
||||
| BACKEND_CORS_ORIGINS | Allowed frontend origins | http://localhost:3000 | No |
|
||||
| FRONTEND_API_URL | Backend API base URL | /api | No |
|
||||
|
||||
### Development Commands (Makefile)
|
||||
|
||||
```makefile
|
||||
.PHONY: dev stop restart test clean build
|
||||
|
||||
dev:
|
||||
docker compose up -d --build backend frontend
|
||||
|
||||
stop:
|
||||
docker compose down
|
||||
|
||||
restart:
|
||||
docker compose down
|
||||
docker compose up -d --build backend frontend
|
||||
|
||||
test:
|
||||
@echo "Running frontend tests..."
|
||||
npm run test
|
||||
@echo "Running backend tests..."
|
||||
docker exec frontend npm run test || \
|
||||
docker exec backend pytest
|
||||
|
||||
clean:
|
||||
docker compose down -v
|
||||
rm -rf data/
|
||||
docker images | grep -E "(newzy|python|node)" | awk '{print $$3}' | xargs docker rmi
|
||||
|
||||
build:
|
||||
docker compose build --no-cache
|
||||
|
||||
logs:
|
||||
docker compose logs -f backend frontend
|
||||
|
||||
shell-backend:
|
||||
docker exec -it backend bash
|
||||
|
||||
shell-frontend:
|
||||
docker exec -it frontend sh
|
||||
```
|
||||
|
||||
### Directory Structure with Docker Setup
|
||||
|
||||
```
|
||||
newzy/
|
||||
├── data/ # Local SQLite data directory
|
||||
│ └── db/
|
||||
│ └── newzy.db # Persisted database (excluded from git)
|
||||
├── backend/
|
||||
│ ├── Dockerfile
|
||||
│ ├── requirements.txt
|
||||
│ ├── .gitignore
|
||||
│ └── pytest.ini
|
||||
├── frontend/
|
||||
│ ├── Dockerfile
|
||||
│ ├── docker-compose.yml # Frontend-specific override (optional)
|
||||
│ └── package.json
|
||||
├── docker-compose.yml # Main orchestration file
|
||||
├── .env # Development environment variables
|
||||
├── .env.example # Template for .env
|
||||
├── Makefile # Development shortcuts
|
||||
├── .dockerignore # Exclude files from build context
|
||||
└── data/.gitignore # Exclude database from git
|
||||
```
|
||||
|
||||
### Multi-stage Build Strategy
|
||||
|
||||
**Backend Dockerfile:**
|
||||
- Base: `python:3.11-slim`
|
||||
- Install dependencies with `pip install --no-cache-dir`
|
||||
- Copy only production code and requirements
|
||||
- Expose port 8000
|
||||
|
||||
**Frontend Dockerfile:**
|
||||
- Stage 1: `node:20-alpine` → Build frontend with Vite
|
||||
- Stage 2: `nginx:alpine` → Serve built static files
|
||||
- Nginx config routes all requests to index.html for SPA
|
||||
|
||||
### Service Communication Flow
|
||||
|
||||
```
|
||||
Browser (localhost:3000)
|
||||
↓ HTTP Request
|
||||
Frontend Container (newzy-network:80)
|
||||
↓ Forwarded to /api
|
||||
Backend Container (newzy-network:8000)
|
||||
↓ Connects to SQLite
|
||||
Volume: data/db/newzy.db
|
||||
```
|
||||
|
||||
## QA Notes
|
||||
|
||||
### Testing Checklist
|
||||
- [ ] `docker compose up` starts both services without errors
|
||||
- [ ] Frontend accessible at http://localhost:3000
|
||||
- [ ] Backend accessible at http://localhost:8000
|
||||
- [ ] Health endpoints respond correctly
|
||||
- [ ] Database persists across service restarts
|
||||
- [ ] `.env.example` contains all documented variables
|
||||
- [ ] Makefile commands work (dev, stop, restart, clean)
|
||||
- [ ] `data/` directory excluded from git commits
|
||||
- [ ] `.gitignore` excludes environment files
|
||||
|
||||
### Security Considerations
|
||||
- Never commit `.env` file to version control
|
||||
- Use `.env.example` as template for new developers
|
||||
- SQLite database stored locally, not in container (volume mounted)
|
||||
- CORS configured with specific origins
|
||||
- No production secrets exposed by default
|
||||
|
||||
### Performance Notes
|
||||
- `--build` flag only when needed (avoid rebuilds on dev)
|
||||
- Docker cache leveraged for incremental builds
|
||||
- SQLite file storage faster than network databases for development
|
||||
- Nginx serves static files efficiently in production
|
||||
|
||||
### Known Limitations
|
||||
- Requires Docker Desktop or equivalent installed locally
|
||||
- Mac users need sufficient disk space (~50GB recommended)
|
||||
- Windows WSL2 required for best performance
|
||||
- No GPU acceleration (CPU-based only)
|
||||
- Production databases should use PostgreSQL, not SQLite
|
||||
|
||||
### Success Metrics
|
||||
- `docker compose up` completes in under 5 minutes on first run
|
||||
- Services restart within 10 seconds subsequent runs
|
||||
- Development environment identical to staging/production setup
|
||||
- Zero manual configuration required for new developers
|
||||
- Makefile shortcuts reduce repetitive Docker commands
|
||||
@@ -0,0 +1,489 @@
|
||||
# M5: Setup Authentication
|
||||
|
||||
## Prompt
|
||||
|
||||
Implement complete authentication for **newzy** news web application. Follow the reference implementation pattern from `/home/daniel/Gitea/daniel/news`.
|
||||
|
||||
### Backend Requirements (FastAPI)
|
||||
|
||||
1. Create `backend/app/auth.py` with:
|
||||
- Password hashing using PBKDF2 with salt
|
||||
- JWT token creation and verification
|
||||
- Current user dependency that validates Bearer tokens
|
||||
- Environment variable `HN_SECRET_KEY` for JWT signing (default dev key)
|
||||
|
||||
2. Update `backend/app/models.py` to add User model:
|
||||
- `id`: Integer primary key
|
||||
- `username`: String(60), unique, index
|
||||
- `password_hash`: String(128)
|
||||
- `created_at`: DateTime with default
|
||||
|
||||
3. Create/update authentication endpoints in `backend/app/main.py`:
|
||||
- `POST /api/auth/register` - Register new user, return JWT token
|
||||
- `POST /api/auth/login` - Login, return JWT token
|
||||
- `POST /api/auth/logout` - Logout (clear token, optional)
|
||||
- `GET /api/auth/me` - Return current user info
|
||||
- Password hashing with PBKDF2 (120,000 iterations minimum)
|
||||
|
||||
4. Create/update `backend/requirements.txt`:
|
||||
- Add `python-jose[cryptography]` for JWT
|
||||
- Add `passlib[bcrypt]` or hashlib for password hashing
|
||||
- Ensure all auth dependencies are listed
|
||||
|
||||
5. Update `backend/app/database.py` if needed:
|
||||
- Configure SQLite database properly for user persistence
|
||||
- Ensure models can be created/queried
|
||||
|
||||
6. Create `data/.gitignore` with patterns to exclude:
|
||||
```python
|
||||
*.db
|
||||
*.sqlite
|
||||
data.db
|
||||
newzy.db
|
||||
```
|
||||
|
||||
7. Update project root `docker-compose.yml` if needed:
|
||||
- Add environment variable override for `HN_SECRET_KEY` (optional, default in code)
|
||||
- Ensure database volume is properly mounted
|
||||
|
||||
### Frontend Requirements (React + TypeScript)
|
||||
|
||||
1. Create `frontend/src/types/auth.ts`:
|
||||
```typescript
|
||||
export interface TokenResponse {
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
username: string;
|
||||
}
|
||||
```
|
||||
|
||||
2. Update `frontend/src/api/client.ts`:
|
||||
- Add methods for auth endpoints: `login(username, password)`, `register(username, password)`, `logout()`, `me()`
|
||||
- Implement JWT token attachment to requests (Authorization: Bearer <token>)
|
||||
- Handle token storage in localStorage
|
||||
|
||||
3. Create `frontend/src/auth.tsx`:
|
||||
- Create AuthContext with username and ready state
|
||||
- Provide login, register, logout functions
|
||||
- On app load, check localStorage for token and call `/api/auth/me` to restore session
|
||||
- If token invalid/expired, clear storage
|
||||
- Export `AuthProvider` component
|
||||
|
||||
4. Create page components:
|
||||
- `frontend/src/pages/Login.tsx`: Login form with username/password validation
|
||||
- `frontend/src/pages/Register.tsx`: Registration form with username/password validation
|
||||
- `frontend/src/pages/SignOut.tsx`: Sign out button that clears token and redirects to login
|
||||
|
||||
5. Update `frontend/src/App.tsx`:
|
||||
- Wrap app with `<AuthProvider>`
|
||||
- Set up protected routes for logged-in users (optional placeholder)
|
||||
|
||||
6. Create CSS styling:
|
||||
- `frontend/src/assets/styles/auth.css` or include in existing styles
|
||||
- Auth pages should be clean, accessible forms
|
||||
- Proper loading states during API calls
|
||||
|
||||
### Shared Requirements
|
||||
|
||||
1. Token Management:
|
||||
- JWT token stored in `localStorage` with key `AUTH_TOKEN`
|
||||
- Tokens have 7-day expiry (7 * 24 * 60 * 60 seconds)
|
||||
- Token format: `sub=USERNAME, iat=TIMESTAMP, exp=TIMESTAMP+7days`
|
||||
|
||||
2. Security:
|
||||
- Passwords hashed with PBKDF2-HMAC-SHA256 (120,000 iterations minimum)
|
||||
- Salt generated using `secrets.token_hex(16)` for uniqueness
|
||||
- JWT signed with HS256 algorithm
|
||||
- Bearer token in Authorization header: `Authorization: Bearer <token>`
|
||||
|
||||
3. Error Handling:
|
||||
- 401 on invalid/expired token
|
||||
- Clear error messages for user actions
|
||||
- Best effort logout on client side
|
||||
|
||||
### Testing Requirements (M3 already covers this)
|
||||
- Unit tests for auth functions
|
||||
- E2E tests for login/register/logout flows
|
||||
|
||||
Remember: Focus ONLY on authentication setup. No complex UI features or business logic required beyond auth endpoints and pages. Use the reference implementation in `/home/daniel/Gitea/daniel/news` as a guide for patterns and structure.
|
||||
|
||||
## Description
|
||||
|
||||
This milestone implements complete JWT-based authentication for newzy news application using FastAPI backend with PBKDF2 password hashing and React frontend with localStorage token management. The scope includes user registration, login, logout, and session restoration—no complex UI features beyond authentication pages.
|
||||
|
||||
**Purpose**: Enable secure user accounts with JWT tokens for protecting content creation and interaction operations in subsequent milestones.
|
||||
|
||||
**Target Audience**: Developers who need to understand the auth flow and extend it with features like profile management or social login.
|
||||
|
||||
**Expected Outcomes**: A fully functional authentication system where users can register, log in, receive JWT tokens, and maintain session state across page reloads. Backend validates tokens against user records. Frontend manages token storage and applies to API requests automatically.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] User model created with username, password_hash, created_at fields
|
||||
- [ ] Password hashing implemented with PBKDF2 (120,000+ iterations)
|
||||
- [ ] JWT token generation using HS256 algorithm with 7-day expiry
|
||||
- [ ] POST /api/auth/register accepts username/password, returns token
|
||||
- [ ] POST /api/auth/login accepts credentials, returns token
|
||||
- [ ] POST /api/auth/logout clears state (client-side best effort)
|
||||
- [ ] GET /api/auth/me validates Bearer token, returns current user
|
||||
- [ ] Frontend auth.tsx with AuthContext for state management
|
||||
- [ ] Auth pages: Login.tsx, Register.tsx, SignOut.tsx created
|
||||
- [ ] API client includes auth methods with token attachment
|
||||
- [ ] localStorage persistence for AUTH_TOKEN key
|
||||
- [ ] Session restoration on page load (check token validity)
|
||||
- [ ] Token stored in localStorage expires automatically after 7 days
|
||||
- [ ] 401 responses for invalid/missing/expired tokens
|
||||
- [ ] .gitignore excludes database files and sensitive configs
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Backend User Model
|
||||
|
||||
```python
|
||||
# backend/app/models.py
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(128))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
```
|
||||
|
||||
### Password Hashing (PBKDF2)
|
||||
|
||||
```python
|
||||
# backend/app/auth.py
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
PBKDF2_ITERATIONS = 120_000
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Generate password hash with random salt."""
|
||||
salt = secrets.token_hex(16)
|
||||
digest = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
|
||||
).hex()
|
||||
return f"{salt}${digest}"
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
"""Verify password against stored hash."""
|
||||
try:
|
||||
salt, digest = stored.split("$", 1)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
candidate = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
|
||||
).hex()
|
||||
|
||||
return secrets.compare_digest(candidate, digest)
|
||||
```
|
||||
|
||||
### JWT Token Creation & Verification
|
||||
|
||||
```python
|
||||
# backend/app/auth.py
|
||||
|
||||
import jwt
|
||||
import os
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
SECRET_KEY = os.environ.get("HN_SECRET_KEY", "hn-clone-dev-secret-change-me")
|
||||
ALGORITHM = "HS256"
|
||||
TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
def create_token(username: str) -> str:
|
||||
"""Create JWT token for user."""
|
||||
now = int(time.time())
|
||||
payload = {
|
||||
"sub": username,
|
||||
"iat": now,
|
||||
"exp": now + TOKEN_TTL_SECONDS
|
||||
}
|
||||
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
def get_current_user(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""Validate Bearer token and return user data."""
|
||||
if credentials is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM]
|
||||
)
|
||||
except jwt.PyJWTError as e:
|
||||
raise HTTPException(status_code=401, detail="Invalid or expired token")
|
||||
|
||||
username = payload.get("sub")
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Unknown user")
|
||||
|
||||
return user
|
||||
```
|
||||
|
||||
### Authentication Endpoints (FastAPI)
|
||||
|
||||
```python
|
||||
# backend/app/main.py
|
||||
|
||||
@app.post("/api/auth/register", response_model=dict)
|
||||
async def register(username: str, password: str):
|
||||
"""Register new user."""
|
||||
# Validate username (alphanumeric, 3-20 chars)
|
||||
if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
|
||||
raise HTTPException(status_code=400, detail="Invalid username")
|
||||
|
||||
# Check user doesn't exist
|
||||
existing = db.query(User).filter(User.username == username).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Username already exists")
|
||||
|
||||
# Create user with hashed password
|
||||
new_user = User(
|
||||
username=username,
|
||||
password_hash=hash_password(password)
|
||||
)
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
|
||||
# Return JWT token
|
||||
return {
|
||||
"token": create_token(username),
|
||||
"username": username
|
||||
}
|
||||
|
||||
@app.post("/api/auth/login", response_model=dict)
|
||||
async def login(username: str, password: str):
|
||||
"""Authenticate and return JWT token."""
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
if not user or not verify_password(password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
|
||||
return {
|
||||
"token": create_token(username),
|
||||
"username": username
|
||||
}
|
||||
|
||||
@app.get("/api/auth/me", response_model=dict)
|
||||
async def get_current_user_info(user: dict = Depends(get_current_user)):
|
||||
"""Return current user data."""
|
||||
return {"username": user.username}
|
||||
|
||||
@app.post("/api/auth/logout", status_code=204)
|
||||
async def logout():
|
||||
"""Logout (stateless - token discarded on client side)."""
|
||||
pass # Optional: server-side invalidation if needed
|
||||
```
|
||||
|
||||
### Frontend Auth Context
|
||||
|
||||
```typescript
|
||||
// frontend/src/auth.tsx
|
||||
|
||||
interface TokenResponse {
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
const TOKEN_KEY = "AUTH_TOKEN";
|
||||
|
||||
export interface AuthState {
|
||||
username: string | null;
|
||||
ready: boolean;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
register: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
// Restore session on load
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(TOKEN_KEY);
|
||||
if (!stored) {
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
api.me(stored)
|
||||
.then((user) => setUsername(user.username))
|
||||
.catch(() => localStorage.removeItem(TOKEN_KEY))
|
||||
.finally(() => setReady(true));
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (username: string, password: string) => {
|
||||
const res = await api.login(username, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
}, [api]);
|
||||
|
||||
const register = useCallback(async (username: string, password: string) => {
|
||||
const res = await api.register(username, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
}, [api]);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
// Best effort logout
|
||||
api.logout().catch(() => {});
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setUsername(null);
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ username, ready, login, register, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### API Client with Auth Methods
|
||||
|
||||
```typescript
|
||||
// frontend/src/api/client.ts
|
||||
|
||||
export const api = {
|
||||
async login(username: string, password: string): Promise<TokenResponse> {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('Login failed');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
async register(username: string, password: string): Promise<TokenResponse> {
|
||||
const res = await fetch('/api/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('Registration failed');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
async me(token: string): Promise<{ username: string }> {
|
||||
const res = await fetch('/api/auth/me', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('Invalid token');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
} catch (e) {
|
||||
// Best effort - discard token anyway
|
||||
}
|
||||
},
|
||||
|
||||
// Other API methods with token attachment...
|
||||
};
|
||||
```
|
||||
|
||||
### Login/Register Pages Structure
|
||||
|
||||
**Login.tsx:**
|
||||
- Form with username and password fields
|
||||
- Submit button with loading state
|
||||
- Validation for empty/invalid inputs
|
||||
- Redirect to dashboard after successful login
|
||||
|
||||
**Register.tsx:**
|
||||
- Form with username, password, confirm password fields
|
||||
- Validation: unique username, matching passwords, minimum lengths
|
||||
- Error messages for existing usernames or weak passwords
|
||||
- Redirect to login after successful registration
|
||||
|
||||
### Security Configuration
|
||||
|
||||
```python
|
||||
# .env.example (project root)
|
||||
|
||||
HN_SECRET_KEY=your-secret-key-change-in-production
|
||||
```
|
||||
|
||||
**Important**: Change `HN_SECRET_KEY` in production! Default dev key should never be used.
|
||||
|
||||
## QA Notes
|
||||
|
||||
### Testing Checklist - Backend
|
||||
- [ ] User registration creates account with hashed password
|
||||
- [ ] Duplicate username rejection with 400 status
|
||||
- [ ] Login validates credentials and returns token
|
||||
- [ ] Invalid credentials return 401
|
||||
- [ ] JWT token has correct expiry (7 days)
|
||||
- [ ] Token verification checks against database
|
||||
- [ ] Unknown user on /api/auth/me returns 401
|
||||
- [ ] Missing/expired Bearer token returns 401
|
||||
|
||||
### Testing Checklist - Frontend
|
||||
- [ ] AuthContext provides login, register, logout functions
|
||||
- [ ] localStorage persists AUTH_TOKEN correctly
|
||||
- [ ] Session restores on page load (validates token)
|
||||
- [ ] Invalid token cleared from storage on error
|
||||
- [ ] Login form validates inputs before submission
|
||||
- [ ] Register form checks username uniqueness
|
||||
- [ ] Protected routes redirect unauthenticated users to login
|
||||
- [ ] Logout clears token and navigates to login
|
||||
|
||||
### Security Review Checklist
|
||||
- [x] Passwords never stored as plaintext
|
||||
- [x] JWT signed with strong secret (not hardcoded)
|
||||
- [x] PBKDF2 iterations >= 120,000
|
||||
- [x] Salt generated per-password using secrets module
|
||||
- [x] Username validation prevents injection attacks
|
||||
- [x] Token expiry set to prevent session hijacking
|
||||
- [ ] CSRF protection not needed (stateless auth)
|
||||
|
||||
### Performance Considerations
|
||||
- JWT creation should be fast (<1ms)
|
||||
- Password hashing takes ~100-200ms (PBKDF2) - acceptable for login
|
||||
- Database queries cached where possible
|
||||
- Frontend token storage doesn't impact performance
|
||||
|
||||
### Known Issues / Limitations
|
||||
- PBKDF2 is slower than bcrypt - may need async handling
|
||||
- JWT tokens don't expire until 7 days (no refresh tokens)
|
||||
- No rate limiting on auth endpoints yet
|
||||
- Password reset not implemented
|
||||
- Email verification not implemented
|
||||
- Account locking after failed attempts not implemented
|
||||
|
||||
### Success Metrics
|
||||
- Registration complete in <2 seconds with validation feedback
|
||||
- Login completes in <500ms (excluding network)
|
||||
- JWT token format valid and decodable
|
||||
- Session persists across browser restarts within 7 days
|
||||
- Security headers present (CORS configured appropriately)
|
||||
- No plaintext passwords in database or logs
|
||||
@@ -0,0 +1,611 @@
|
||||
# M6: Setup Admin Area
|
||||
|
||||
## Prompt
|
||||
|
||||
Implement a complete admin area for **newzy** news web application. Follow the reference implementation patterns from `/home/daniel/Gitea/daniel/news`.
|
||||
|
||||
### Requirements
|
||||
|
||||
Create an admin dashboard that allows administrators to manage content items (articles/stories). The admin area must include:
|
||||
|
||||
1. **Admin Authentication & Access Control**
|
||||
- Protected route accessible only when user has `is_admin=true` role/flag
|
||||
- Admin status stored in database (new field on User model or separate table)
|
||||
- Middleware to check admin flag before accessing admin routes
|
||||
|
||||
2. **List View with CRUD Operations**
|
||||
- Display paginated list of all content items
|
||||
- Search functionality (search by title, URL)
|
||||
- Sortable columns (at minimum: title, date created, points)
|
||||
- Pagination controls (page size selector, page number navigation)
|
||||
- Edit action button on each row (opens edit view modal or route)
|
||||
- Delete action button on each row (requires confirmation)
|
||||
|
||||
3. **Edit View**
|
||||
- Create/Edit page with full form for item details:
|
||||
- Title (text input, required)
|
||||
- URL (text input, optional)
|
||||
- Content/Body (Lexical WYSIWYG editor)
|
||||
- Points (number input, default 0)
|
||||
- Author (user selection or auto-filled from session user)
|
||||
- Lexical WYSIWYG editor with basic formatting:
|
||||
- Bold, italic, underline
|
||||
- Headings (H1-H6)
|
||||
- Lists (ordered and unordered)
|
||||
- Link insertion
|
||||
- Paragraph editing
|
||||
- Code blocks (optional but recommended)
|
||||
|
||||
4. **Delete Confirmation**
|
||||
- Delete action triggers a confirmation dialog (SweetAlert2 or custom modal)
|
||||
- Warning message explaining consequences
|
||||
- Require explicit "Yes, delete" to confirm
|
||||
- Prevent accidental deletion of important content
|
||||
|
||||
5. **Backend Admin Endpoints**
|
||||
- `GET /api/admin/items` - List all items with pagination, search, sort parameters
|
||||
- `GET /api/admin/items/{id}` - Get single item details (admin required)
|
||||
- `POST /api/admin/items` - Create new item (admin only)
|
||||
- `PUT /api/admin/items/{id}` - Update item (admin only)
|
||||
- `DELETE /api/admin/items/{id}` - Delete item (admin only)
|
||||
|
||||
### Backend Implementation (FastAPI)
|
||||
|
||||
1. **Update User Model** (`backend/app/models.py`):
|
||||
```python
|
||||
class User(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(128))
|
||||
is_admin: Mapped[bool] = mapped_column(Boolean, default=False) # ← NEW FIELD
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
```
|
||||
|
||||
2. **Admin Dependency** (`backend/app/main.py`):
|
||||
```python
|
||||
def current_active_user(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
# Existing user validation...
|
||||
|
||||
user = db.query(User).filter(User.username == payload["sub"]).first()
|
||||
if not user or not user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
return user
|
||||
```
|
||||
|
||||
3. **Admin API Endpoints**:
|
||||
- Implement CRUD endpoints with proper admin-only access control
|
||||
- Pagination parameters: `page`, `page_size` (default 10-50 range)
|
||||
- Search parameter: `search` (matches title OR url, case-insensitive)
|
||||
- Sort parameters: `sort_by` (title or created_at), `sort_order` (asc/desc)
|
||||
- Include total count in response for pagination metadata
|
||||
|
||||
4. **Update Database Migration**:
|
||||
- Add `is_admin` column to users table
|
||||
- Provide seed data command to create admin user (or CLI flag)
|
||||
|
||||
### Frontend Implementation (React + TypeScript)
|
||||
|
||||
1. **Create Admin Layout Component** (`frontend/src/components/AdminLayout.tsx`):
|
||||
- Sidebar navigation for admin pages
|
||||
- Breadcrumb/Back button to return to regular app
|
||||
- Protected by auth provider check for `is_admin` flag
|
||||
- Error boundary for graceful degradation if not admin
|
||||
|
||||
2. **Create Admin Pages**:
|
||||
- `frontend/src/pages/AdminDashboard.tsx` - List view component
|
||||
- `frontend/src/pages/EditItemPage.tsx` - Create/Edit form with Lexical
|
||||
- `frontend/src/components/AdminModal.tsx` - For inline editing (optional)
|
||||
- `frontend/src/components/DeleteConfirmation.tsx` - Confirm deletion dialog
|
||||
|
||||
3. **Implement AdminList Component**:
|
||||
```typescript
|
||||
interface AdminItem {
|
||||
id: number;
|
||||
title: string;
|
||||
url: string;
|
||||
points: number;
|
||||
user: { username: string };
|
||||
created_at: Date | string;
|
||||
}
|
||||
|
||||
interface AdminListProps {
|
||||
items: AdminItem[];
|
||||
total: number;
|
||||
currentPage: number;
|
||||
pageSize: number;
|
||||
onPageChange: (page: number) => void;
|
||||
onPageSizeChange: (size: number) => void;
|
||||
searchQuery: string;
|
||||
setSearchQuery: (query: string) => void;
|
||||
sortBy: 'title' | 'created_at';
|
||||
sortOrder: 'asc' | 'desc';
|
||||
onSort: (field: 'title' | 'created_at') => void;
|
||||
}
|
||||
```
|
||||
|
||||
4. **Implement AdminEdit Component**:
|
||||
- Lexical editor with rich formatting toolbar
|
||||
- Form validation for required fields
|
||||
- Loading state during save
|
||||
- Success/error notifications
|
||||
- Auto-save option (debounced)
|
||||
|
||||
5. **Admin API Client** (`frontend/src/adminApi.ts`):
|
||||
- `listItems(page, pageSize, search, sort)` with Bearer token
|
||||
- `getItem(id)` for fetching single item details
|
||||
- `createItem(data)` for new items
|
||||
- `updateItem(id, data)` for updates
|
||||
- `deleteItem(id)` for deletion
|
||||
|
||||
6. **Lexical Editor Integration**:
|
||||
```typescript
|
||||
import { createEditor } from "lexical";
|
||||
// Or use lexical-react:
|
||||
import { LexicalComposer } from "@lexical/react";
|
||||
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
|
||||
```
|
||||
|
||||
### Styling Requirements
|
||||
|
||||
1. **Admin Layout Styles**:
|
||||
- Sidebar: Fixed left navigation (250px width)
|
||||
- Main content area: Padding-left for sidebar offset
|
||||
- Darker theme distinction from regular app (optional but clear)
|
||||
- Responsive design collapses sidebar on mobile
|
||||
|
||||
2. **Table/List View Styles**:
|
||||
- Card-based layout or table format
|
||||
- Hover effects on rows
|
||||
- Clear edit/delete action buttons with hover states
|
||||
- Pagination controls at bottom with page number indicators
|
||||
- Search bar with debounce (300ms)
|
||||
|
||||
3. **Delete Confirmation Modal**:
|
||||
- Centered modal overlay
|
||||
- Warning icon (exclamation triangle)
|
||||
- Red "Yes, Delete" button vs normal confirmation
|
||||
- Cancel button (secondary style)
|
||||
- Title: "Are you sure you want to delete this item?"
|
||||
- Message explaining consequences
|
||||
|
||||
4. **Edit Form with Lexical**:
|
||||
- Clean, spacious editor interface
|
||||
- Formatting toolbar at top (bold, italic, etc.)
|
||||
- Full-width content area
|
||||
- Save/Cancel buttons side-by-side
|
||||
- Preview option (optional)
|
||||
|
||||
### Files to Create
|
||||
|
||||
1. **Backend**:
|
||||
- `backend/app/models.py` - Add `is_admin` field to User model
|
||||
- `backend/app/main.py` - Admin dependency and CRUD endpoints
|
||||
- `backend/app/schemas.py` - AdminItem, ItemCreateAdmin, ItemUpdateAdmin schemas
|
||||
- `backend/seed_data.py` - Script to create admin user (optional)
|
||||
|
||||
2. **Frontend**:
|
||||
- `frontend/src/types/admin.ts` - Type definitions for admin API responses
|
||||
- `frontend/src/adminApi.ts` - Admin-specific fetch functions
|
||||
- `frontend/src/components/AdminLayout.tsx` - Layout wrapper
|
||||
- `frontend/src/pages/AdminDashboard.tsx` - List view with pagination/search/sort
|
||||
- `frontend/src/pages/EditItemPage.tsx` - Create/edit form
|
||||
- `frontend/src/components/DeleteConfirmation.tsx` - Confirmation modal
|
||||
- `frontend/src/assets/styles/admin.css` - Admin-specific styles
|
||||
|
||||
### Files to Update
|
||||
|
||||
1. **Backend**:
|
||||
- `backend/app/models.py` - Add is_admin field
|
||||
- `backend/app/main.py` - Add admin endpoints and dependencies
|
||||
- `backend/requirements.txt` - No new deps needed (use existing SQLAlchemy, FastAPI)
|
||||
|
||||
2. **Frontend**:
|
||||
- `frontend/src/App.tsx` - Add admin routes protected by auth check
|
||||
- `frontend/src/api/client.ts` - Add admin method wrappers
|
||||
- `frontend/src/AuthContext.tsx` - Return is_admin flag in username data
|
||||
- `frontend/src/index.css` - Add admin-specific CSS classes
|
||||
|
||||
### Security Considerations
|
||||
|
||||
1. **Admin Access**:
|
||||
- Server-side validation of `is_admin` flag on ALL admin endpoints
|
||||
- Never trust client-side auth checks
|
||||
- JWT token must be valid AND user must have admin role
|
||||
|
||||
2. **Rate Limiting** (Recommended):
|
||||
- Add rate limiting to admin CRUD endpoints (prevent abuse)
|
||||
- Especially important for delete operations
|
||||
|
||||
3. **Audit Logging** (Future Milestone):
|
||||
- Log admin actions (created, updated, deleted items)
|
||||
- Track timestamp and user performing action
|
||||
|
||||
4. **Input Validation**:
|
||||
- Title: max 300 characters
|
||||
- URL: must be valid URL format if provided
|
||||
- Content: validate lexical editor output on save
|
||||
- Points: must be integer >= 0
|
||||
|
||||
### Testing Requirements (M3/M4 covers general testing)
|
||||
|
||||
- Unit tests for admin API endpoints (create, update, delete, list with pagination)
|
||||
- Integration tests for admin-only routes (verify unauthorized users get 403)
|
||||
- E2E tests for full admin workflow (list → edit → save → delete)
|
||||
|
||||
### Docker Configuration
|
||||
|
||||
No new Docker changes required - existing setup works. However:
|
||||
|
||||
1. Add `.env` entry if creating admin user via script:
|
||||
```bash
|
||||
ADMIN_USERNAME=admin_user
|
||||
HN_SECRET_KEY=your-secret-key-change-in-production
|
||||
```
|
||||
|
||||
2. Database migration should run automatically on startup (SQLAlchemy auto-creates tables)
|
||||
|
||||
### Success Metrics
|
||||
|
||||
- Admin can view list of items with pagination working correctly
|
||||
- Search returns relevant results within 200ms
|
||||
- Sort by date/title works in both ascending/descending order
|
||||
- Edit form saves successfully and updates database immediately
|
||||
- Delete confirmation prevents accidental deletions
|
||||
- Lexical editor formats content properly before save
|
||||
- Non-admin users receive 403 Forbidden on admin routes
|
||||
- All API responses include proper HTTP status codes
|
||||
|
||||
## Description
|
||||
|
||||
This milestone implements a complete admin area for newzy allowing administrators to manage content through a web interface. The scope includes creating protected admin routes, implementing CRUD operations with pagination and search, adding Lexical WYSIWYG editor for rich content editing, and ensuring secure admin-only access control—no business logic or additional features beyond the admin interface.
|
||||
|
||||
**Purpose**: Enable site administrators to create, edit, and delete news items through a user-friendly interface without directly editing code or database files.
|
||||
|
||||
**Target Audience**: Non-technical content editors who need to manage the website content, plus developers extending the admin area in future milestones.
|
||||
|
||||
**Expected Outcomes**: A fully functional admin dashboard where logged-in admin users can view paginated item lists with search/sort capabilities, edit articles using a rich text editor, and safely delete items after confirmation. The system protects unauthorized users from accessing admin functionality.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [x] User model updated with `is_admin` boolean field (default: False)
|
||||
- [x] Admin-only dependency checks JWT token AND verifies is_admin flag
|
||||
- [x] All admin endpoints protected by server-side admin check (403 for non-admins)
|
||||
- [x] GET /api/v1/admin/items returns paginated list with search and sort parameters
|
||||
- [x] Response includes total count, page number, page size, and items array
|
||||
- [x] POST /api/v1/admin/items creates new item with validation
|
||||
- [x] PUT /api/v1/admin/items/{id} updates existing item (only admins allowed)
|
||||
- [x] DELETE /api/v1/admin/items/{id} deletes item after admin verification
|
||||
- [x] Admin Layout component renders sidebar navigation
|
||||
- [x] Admin Dashboard lists items with pagination controls and page size selector
|
||||
- [x] Search bar filters list by title or URL (case-insensitive, debounced 300ms)
|
||||
- [x] Sort controls for title (A-Z/Z-A), created_at (newest/oldest) and points
|
||||
- [x] Edit action navigates to edit page with pre-filled form data
|
||||
- [x] Delete action triggers confirmation dialog before deletion
|
||||
- [x] DeleteConfirmation modal has warning icon and requires explicit "Yes, delete" click
|
||||
- [x] EditItemPage accepts all item fields including title, url, points, content
|
||||
- [x] Lexical WYSIWYG editor with toolbar (bold, italic, underline, headings, lists, links, code blocks, undo/redo)
|
||||
- [x] Form validates required fields before submission
|
||||
- [x] Loading state displayed during API save operations
|
||||
- [x] Success/error notifications shown after submit
|
||||
- [x] Non-admin users receive 403 Forbidden on all admin routes (API + UI guard)
|
||||
- [x] Frontend auth context returns is_admin flag for UI conditionals
|
||||
|
||||
Implementation notes (deviations from the prompt sketch, matching project conventions):
|
||||
|
||||
- Endpoints live under `/api/v1/admin/items` (project uses the `/api/v1` prefix).
|
||||
- Files follow the existing layout: `backend/models/item.py`, `backend/schemas/item.py`,
|
||||
`backend/api/v1/admin.py`, `frontend/src/api/admin.ts`, `frontend/src/types/admin.ts`.
|
||||
- Delete is a hard delete (no soft-delete column on `Item`).
|
||||
- Rate limiting is implemented in-memory (1000 req/60s per admin; 429 on breach)
|
||||
rather than a placeholder.
|
||||
|
||||
QA findings from M6 (all fixed):
|
||||
|
||||
- The editor's `initialHtml` ingest called `$generateNodesFromDOM` but
|
||||
discarded the returned nodes, so stored content never appeared in the
|
||||
WYSIWYG editor in edit mode. Fixed by appending the parsed nodes to the
|
||||
root; covered by the E2E edit + hostile-HTML tests.
|
||||
- XSS: the E2E hostile-HTML test loads `<script>`, `onerror`/`onload`
|
||||
handlers and `javascript:` links through the real editor and asserts
|
||||
none of it survives into the contenteditable (nothing executes).
|
||||
- SQL injection: the backend search test feeds `1=1' OR '1'='1` as a
|
||||
search term and asserts literal-substring behaviour plus table integrity.
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Database Schema Update
|
||||
|
||||
```python
|
||||
# backend/app/models.py (add to User model)
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(128))
|
||||
is_admin: Mapped[bool] = mapped_column(Boolean, default=False) # ← NEW
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
```
|
||||
|
||||
### Admin Dependency (Server-Side Protection)
|
||||
|
||||
```python
|
||||
# backend/app/main.py
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
async def get_current_admin(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Admin-only dependency - validates token AND admin flag."""
|
||||
if credentials is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM]
|
||||
)
|
||||
except jwt.PyJWTError:
|
||||
raise HTTPException(status_code=401, detail="Invalid or expired token")
|
||||
|
||||
username = payload.get("sub")
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Unknown user")
|
||||
|
||||
if not user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
|
||||
return user
|
||||
|
||||
@app.get("/api/admin/items", response_model=dict)
|
||||
async def list_admin_items(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
search: str = "",
|
||||
sort_by: Literal["title", "created_at"] = "created_at",
|
||||
sort_order: Literal["asc", "desc"] = "desc",
|
||||
current_user: User = Depends(get_current_admin), # ← Admin check
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all items with pagination, search, and sorting."""
|
||||
query = db.query(models.Item)
|
||||
|
||||
# Apply search filter
|
||||
if search:
|
||||
search_query = f"%{search}%"
|
||||
query = query.filter(
|
||||
models.Item.title.like(search_query) | models.Item.url.like(search_query)
|
||||
)
|
||||
|
||||
# Apply sorting
|
||||
order_by = [models.Item.created_at]
|
||||
if sort_order == "asc":
|
||||
query = query.order_by(desc(sort_by))
|
||||
else:
|
||||
query = query.order_by(sort_by)
|
||||
|
||||
# Pagination
|
||||
total = query.count()
|
||||
items = query.offset((page - 1) * page_size).limit(page_size).all()
|
||||
|
||||
return {
|
||||
"items": [ItemAdminOut.model_validate(item) for item in items],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size,
|
||||
}
|
||||
|
||||
@app.delete("/api/admin/items/{item_id}", status_code=204)
|
||||
async def delete_admin_item(
|
||||
item_id: int,
|
||||
current_user: User = Depends(get_current_admin), # ← Admin check
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Delete an item (admin only)."""
|
||||
item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
# Optional: Soft delete by setting published=False instead of hard delete
|
||||
# db.delete(item) # Hard delete
|
||||
|
||||
return "OK"
|
||||
```
|
||||
|
||||
### Frontend Admin API Client
|
||||
|
||||
```typescript
|
||||
// frontend/src/adminApi.ts
|
||||
|
||||
import { api } from "./api/client";
|
||||
|
||||
interface AdminListResponse {
|
||||
items: Array<{
|
||||
id: number;
|
||||
title: string;
|
||||
url: string;
|
||||
points: number;
|
||||
user: { username: string };
|
||||
created_at: Date | string;
|
||||
}>;
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
const ADMIN_BASE_URL = "/api/admin";
|
||||
|
||||
export const adminApi = {
|
||||
async listItems(page: number, pageSize: number, search: string, sortBy?: "title" | "created_at"): Promise<AdminListResponse> {
|
||||
const params = new URLSearchParams();
|
||||
params.set("page", page.toString());
|
||||
params.set("page_size", pageSize.toString());
|
||||
if (search) params.set("search", search);
|
||||
|
||||
return api.get(`${ADMIN_BASE_URL}/items?${params}`) as Promise<AdminListResponse>;
|
||||
},
|
||||
|
||||
async getItem(id: number): Promise<any> {
|
||||
return api.get(`/api/admin/items/${id}`) as Promise<any>;
|
||||
},
|
||||
|
||||
async createItem(data: any): Promise<any> {
|
||||
return api.post("/api/admin/items", data) as Promise<any>;
|
||||
},
|
||||
|
||||
async updateItem(id: number, data: any): Promise<any> {
|
||||
return api.put(`/api/admin/items/${id}`, data) as Promise<any>;
|
||||
},
|
||||
|
||||
async deleteItem(id: number): Promise<void> {
|
||||
return api.delete(`/api/admin/items/${id}`) as Promise<void>;
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Lexical Editor Setup
|
||||
|
||||
```typescript
|
||||
// frontend/src/components/LexicalEditor.tsx (or integrated inline)
|
||||
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import {
|
||||
LexicalComposer,
|
||||
RichTextPlugin,
|
||||
HistoryPlugin,
|
||||
} from "@lexical/react/LexicalComposerPlugins";
|
||||
import ContentEditable from "@lexical/react/LexicalContentEditable";
|
||||
|
||||
function LexicalEditor() {
|
||||
const editorRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
return (
|
||||
<div ref={editorRef}>
|
||||
<LexicalComposer initialState={{ theme: {} }}>
|
||||
<RichTextPlugin>
|
||||
{/* Additional plugins here */}
|
||||
</RichTextPlugin>
|
||||
<HistoryPlugin />
|
||||
</LexicalComposer>
|
||||
<ContentEditable
|
||||
className="lexical-editor"
|
||||
contentEditable
|
||||
onChange={(e) => handleSave(e.currentTarget.textContent)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LexicalEditor;
|
||||
```
|
||||
|
||||
### Delete Confirmation Component
|
||||
|
||||
```typescript
|
||||
// frontend/src/components/DeleteConfirmation.tsx
|
||||
|
||||
import { useAuth } from "../auth";
|
||||
import { adminApi } from "../adminApi";
|
||||
import { alert as SweetAlert, AlertParams } from "sweetalert2";
|
||||
|
||||
interface DeleteConfirmationProps {
|
||||
itemId: number;
|
||||
itemName: string;
|
||||
onConfirm: () => Promise<void>;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function DeleteConfirmation({ itemId, itemName, onConfirm, onCancel }: DeleteConfirmationProps) {
|
||||
const { username } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="delete-modal-overlay" onClick={onCancel}>
|
||||
<div className="delete-modal-content">
|
||||
<i className="icon-warning"></i>
|
||||
<h3>Are you sure you want to delete "{itemName}"?</h3>
|
||||
<p>This action cannot be undone.</p>
|
||||
<div className="modal-actions">
|
||||
<button onClick={onCancel}>Cancel</button>
|
||||
<button
|
||||
className="btn-danger"
|
||||
onClick={async () => {
|
||||
await onConfirm();
|
||||
onCancel();
|
||||
}}
|
||||
>
|
||||
Yes, Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## QA Notes
|
||||
|
||||
### Testing Checklist - Backend
|
||||
- [x] Admin dependency returns 403 for non-admin users
|
||||
- [x] Non-admin JWT tokens rejected with proper error message
|
||||
- [x] Admin endpoints work correctly for authenticated admins
|
||||
- [x] Pagination works (page 1, page 2, etc.)
|
||||
- [x] Search finds items by title OR url
|
||||
- [x] Sort order changes work (asc/desc switching)
|
||||
- [x] Delete requires explicit confirmation
|
||||
- [x] Hard delete functional (chosen implementation)
|
||||
|
||||
### Testing Checklist - Frontend
|
||||
- [x] AdminLayout only renders for admin users
|
||||
- [x] Admin routes protected with auth context check (`RequireAdmin`)
|
||||
- [x] List view displays all items correctly
|
||||
- [x] Pagination controls update page state
|
||||
- [x] Search debounced (300ms delay before API call)
|
||||
- [x] Sort buttons toggle sort_by and sort_order
|
||||
- [x] Edit button loads correct item data in form
|
||||
- [x] Delete button shows confirmation modal
|
||||
- [x] Cancel delete dismisses modal
|
||||
- [x] Confirm delete performs API request
|
||||
- [x] Form validation blocks empty submissions
|
||||
- [x] Lexical editor saves properly formatted content
|
||||
- [x] Loading states show during async operations
|
||||
|
||||
### Security Testing Checklist
|
||||
- [x] Direct URL access to /api/v1/admin/items → 403 for non-admins
|
||||
- [x] Token tampering doesn't bypass admin check (JWT signature validation)
|
||||
- [x] Rate limiting active (in-memory, 1000 req/60s per admin → 429)
|
||||
- [x] Input sanitization prevents SQL injection (SQLAlchemy parameterized queries; verified by `test_search_with_sql_metacharacters_is_treated_as_text`)
|
||||
- [x] XSS prevention in Lexical editor output (verified by the E2E hostile-HTML test: scripts, event handlers and `javascript:` links are stripped by the node-model round trip and nothing executes)
|
||||
|
||||
### Performance Considerations
|
||||
- Search with 10,000 items: <2 seconds response time
|
||||
- Pagination queries use LIMIT/OFFSET efficiently
|
||||
- Frontend debounces search to reduce API calls
|
||||
- Admin pages lazy-loaded (optional optimization)
|
||||
|
||||
### Known Issues / Limitations
|
||||
- No role-based permissions beyond admin flag yet
|
||||
- Lexical editor could benefit with image/file upload support
|
||||
- Audit logging not implemented (M7 scope)
|
||||
- No version history for deleted items
|
||||
- Mobile UX could use improvement
|
||||
|
||||
### Success Metrics
|
||||
- Admin can list all 100+ items on first page load in <2s
|
||||
- Search returns correct results consistently
|
||||
- Sort order persists while navigating pages
|
||||
- Lexical editor renders and saves rich text content
|
||||
- Delete confirmation prevents at least 95% of accidental deletions
|
||||
- Non-admin users never see admin UI or API endpoints
|
||||
Reference in new issue
Block a user