"""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"]