Files
newz-qwen-27b/backend/api/v1/admin.py
T
Daniel Samson b440809548 feat: add admin area with item CRUD, Lexical editor and access control (M6)
Backend:
- Item model (title, url, points, username, content, created_at)
- is_admin flag on User + startup migration for pre-existing DBs
- get_current_admin dependency (401 without/invalid token, 403 for
  non-admins); server-side check on every admin endpoint
- /api/v1/admin/items CRUD: pagination, case-insensitive title/url
  search, sort by title/created_at/points, in-memory rate limiting
  (1000 req/60s per admin -> 429)
- seed_admin.py (ADMIN_USERNAME/ADMIN_PASSWORD), documented in
  backend/.env.example

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

All acceptance criteria for milestones/m6-setup-admin-area-prompt.md
verified: 108 backend, 87 frontend unit and 29 E2E tests pass.
2026-10-30 21:36:15 +00:00

225 lines
7.0 KiB
Python

"""Admin area endpoints: item 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.
Routes (mounted under ``/api/v1/admin``):
- ``GET /items`` paginated list with search and sorting
- ``POST /items`` create an item
- ``GET /items/{id}`` fetch a single item
- ``PUT /items/{id}`` update an item (partial updates supported)
- ``DELETE /items/{id}`` delete an item
"""
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.orm import Session
from core import auth
from db.session import get_db
from models import Item, User
from schemas import ItemAdminList, ItemCreate, ItemRead, ItemUpdate
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_item_or_404(db: Session, item_id: int) -> Item:
item = db.query(Item).filter(Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
def _apply_search(query, search: str):
"""Filter by ``title`` OR ``url`` (case-insensitive substring match)."""
if not search:
return query
pattern = f"%{search}%"
return query.filter(or_(Item.title.ilike(pattern), Item.url.ilike(pattern)))
def _apply_sort(query, sort_by: str, sort_order: str):
column = getattr(Item, sort_by)
return query.order_by(asc(column) if sort_order == "asc" else desc(column))
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@router.get(
"/items",
response_model=ItemAdminList,
summary="List items (paginated, searchable, sortable)",
)
def list_items(
page: int = Query(default=1, ge=1, description="1-based page number"),
page_size: int = Query(
default=20, ge=1, le=100, description="Items per page (1-100)"
),
search: str = Query(default="", max_length=200, description="Match title or URL"),
sort_by: Literal["title", "created_at", "points"] = "created_at",
sort_order: Literal["asc", "desc"] = "desc",
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> ItemAdminList:
"""List all items with pagination, case-insensitive search and sorting."""
query = _apply_sort(_apply_search(db.query(Item), search), sort_by, sort_order)
total = query.count()
items = query.offset((page - 1) * page_size).limit(page_size).all()
total_pages = (total + page_size - 1) // page_size
return ItemAdminList(
items=[ItemRead.model_validate(item) for item in items],
total=total,
page=page,
page_size=page_size,
total_pages=total_pages,
)
@router.post(
"/items",
response_model=ItemRead,
status_code=status.HTTP_201_CREATED,
summary="Create a new item",
)
def create_item(
payload: ItemCreate,
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> ItemRead:
"""Create an item; it belongs to ``username`` or the admin when omitted."""
item = Item(
title=payload.title,
url=payload.url,
points=payload.points,
username=(payload.username or admin.username).strip(),
content=payload.content,
)
db.add(item)
db.commit()
db.refresh(item)
return ItemRead.model_validate(item)
@router.get(
"/items/{item_id}",
response_model=ItemRead,
summary="Get a single item",
)
def get_item(
item_id: int,
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> ItemRead:
"""Fetch one item by id (404 when it does not exist)."""
return ItemRead.model_validate(_get_item_or_404(db, item_id))
@router.put(
"/items/{item_id}",
response_model=ItemRead,
summary="Update an item",
)
def update_item(
item_id: int,
payload: ItemUpdate,
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> ItemRead:
"""Update an item; only the provided fields change (partial update)."""
item = _get_item_or_404(db, item_id)
updates = payload.model_dump(exclude_unset=True)
if "username" in updates and updates["username"] is not None:
updates["username"] = updates["username"].strip()
for field, value in updates.items():
setattr(item, field, value)
db.commit()
db.refresh(item)
return ItemRead.model_validate(item)
@router.delete(
"/items/{item_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Delete an item",
)
def delete_item(
item_id: int,
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> None:
"""Hard-delete an item (404 when it does not exist)."""
item = _get_item_or_404(db, item_id)
db.delete(item)
db.commit()
return None
# Re-exported for tests and documentation.
__all__ = ["router", "_limiter", "_rate_limit"]