diff --git a/backend/.env.example b/backend/.env.example index 109ff63..acb4f68 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -9,3 +9,8 @@ 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 diff --git a/backend/api/v1/__init__.py b/backend/api/v1/__init__.py index 49dfc53..fe0df20 100644 --- a/backend/api/v1/__init__.py +++ b/backend/api/v1/__init__.py @@ -5,6 +5,7 @@ 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 auth as auth_routes from config import APP_NAME, APP_VERSION from schemas import HealthResponse, VersionResponse @@ -14,6 +15,9 @@ router = APIRouter() # Authentication (register / login / logout / me) under /api/v1/auth. router.include_router(auth_routes.router) +# Admin area (item CRUD, admin-only) under /api/v1/admin. +router.include_router(admin_routes.router) + @router.get("/health", response_model=HealthResponse, summary="Service health check") def get_health() -> HealthResponse: diff --git a/backend/api/v1/admin.py b/backend/api/v1/admin.py new file mode 100644 index 0000000..bdb60e9 --- /dev/null +++ b/backend/api/v1/admin.py @@ -0,0 +1,224 @@ +"""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"] diff --git a/backend/api/v1/auth.py b/backend/api/v1/auth.py index 756f6ec..4480c30 100644 --- a/backend/api/v1/auth.py +++ b/backend/api/v1/auth.py @@ -42,7 +42,11 @@ def register(payload: RegisterIn, db: Session = Depends(get_db)) -> TokenOut: # 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) + 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") @@ -51,7 +55,11 @@ def login(payload: LoginIn, db: Session = Depends(get_db)) -> TokenOut: 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) + return TokenOut( + token=auth.create_token(user.username), + username=user.username, + is_admin=user.is_admin, + ) @router.post( @@ -65,6 +73,6 @@ def logout(current_user: str = Depends(auth.get_current_user)) -> None: @router.get("/me", response_model=UserOut, summary="Current authenticated user") -def me(current_user: str = Depends(auth.get_current_user)) -> UserOut: - """Return the user the Bearer token belongs to.""" - return UserOut(username=current_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) diff --git a/backend/core/app.py b/backend/core/app.py index 4ef5b53..7fbca92 100644 --- a/backend/core/app.py +++ b/backend/core/app.py @@ -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 diff --git a/backend/core/auth.py b/backend/core/auth.py index aa4c7ec..de1c8e8 100644 --- a/backend/core/auth.py +++ b/backend/core/auth.py @@ -76,11 +76,10 @@ def create_token(username: str) -> str: return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) -def get_current_user( - credentials: HTTPAuthorizationCredentials | None = Depends(_bearer), - db: Session = Depends(get_db), -) -> str: - """Validate the Bearer token and return the username. +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. @@ -92,6 +91,43 @@ def get_current_user( except jwt.PyJWTError as exc: raise HTTPException(status_code=401, detail="Invalid or expired token") from exc username = payload.get("sub") - if not username or db.query(User).filter(User.username == username).first() is None: + 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 username + 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 diff --git a/backend/models/__init__.py b/backend/models/__init__.py index db1aaae..c8a071c 100644 --- a/backend/models/__init__.py +++ b/backend/models/__init__.py @@ -4,6 +4,7 @@ from models.article import Article from models.author import Author from models.base import Base from models.category import Category, slugify +from models.item import Item from models.user import User -__all__ = ["Article", "Author", "Base", "Category", "User", "slugify"] +__all__ = ["Article", "Author", "Base", "Category", "Item", "User", "slugify"] diff --git a/backend/models/item.py b/backend/models/item.py new file mode 100644 index 0000000..c12200e --- /dev/null +++ b/backend/models/item.py @@ -0,0 +1,43 @@ +"""Item model: a news story managed through the admin area. + +Unlike ``Article`` (long-form pieces filed under an author and category), +an ``Item`` is a lightweight news entry — headline, optional external URL, +community points and an optional HTML body — created and maintained by +administrators through the admin API (see ``api.v1.admin``). +""" + +from __future__ import annotations + +from datetime import datetime, timezone + +from sqlalchemy import DateTime, Integer, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from models.base import Base + + +def _utcnow() -> datetime: + return datetime.now(timezone.utc) + + +class Item(Base): + """A news item (story) listed on the front page and managed by admins. + + ``username`` stores the (denormalized) name of the user the item + belongs to, defaulting to the account that created it. + """ + + __tablename__ = "items" + + id: Mapped[int] = mapped_column(primary_key=True) + title: Mapped[str] = mapped_column(String(300), nullable=False, index=True) + url: Mapped[str] = mapped_column(String(500), default="", nullable=False) + points: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + username: Mapped[str] = mapped_column(String(60), default="anonymous", nullable=False) + content: Mapped[str] = mapped_column(Text, default="", nullable=False) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=_utcnow, nullable=False + ) + + def __repr__(self) -> str: # pragma: no cover + return f"" diff --git a/backend/models/user.py b/backend/models/user.py index f82bd30..b0a502a 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -4,7 +4,7 @@ from __future__ import annotations from datetime import datetime, timezone -from sqlalchemy import DateTime, String +from sqlalchemy import Boolean, DateTime, String from sqlalchemy.orm import Mapped, mapped_column from models.base import Base @@ -26,6 +26,9 @@ 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)) + #: 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 ) diff --git a/backend/schemas/__init__.py b/backend/schemas/__init__.py index a84d6da..5461b37 100644 --- a/backend/schemas/__init__.py +++ b/backend/schemas/__init__.py @@ -5,6 +5,7 @@ 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.common import ErrorDetail, HealthResponse, VersionResponse +from schemas.item import ItemAdminList, ItemCreate, ItemRead, ItemUpdate __all__ = [ "ArticleBase", @@ -21,6 +22,10 @@ __all__ = [ "CategoryUpdate", "ErrorDetail", "HealthResponse", + "ItemAdminList", + "ItemCreate", + "ItemRead", + "ItemUpdate", "LoginIn", "RegisterIn", "TokenOut", diff --git a/backend/schemas/auth.py b/backend/schemas/auth.py index 7f91c98..f8c352a 100644 --- a/backend/schemas/auth.py +++ b/backend/schemas/auth.py @@ -31,9 +31,13 @@ class TokenOut(BaseModel): 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 diff --git a/backend/schemas/item.py b/backend/schemas/item.py new file mode 100644 index 0000000..d959c64 --- /dev/null +++ b/backend/schemas/item.py @@ -0,0 +1,102 @@ +"""Schemas for the Item model (admin area, see ``api.v1.admin``).""" + +from datetime import datetime +from urllib.parse import urlsplit + +from pydantic import BaseModel, ConfigDict, Field, field_validator + + +def _clean_title(value: str) -> str: + stripped = value.strip() + if not stripped: + raise ValueError("title must not be empty") + return stripped + + +def _clean_url(value: str | None) -> str: + """Normalize an optional URL: empty/blank -> ``""``, otherwise it must + be an absolute ``http://`` or ``https://`` URL.""" + if value is None: + return "" + stripped = value.strip() + if not stripped: + return "" + parsed = urlsplit(stripped) + if parsed.scheme not in ("http", "https") or not parsed.netloc: + raise ValueError("must be an absolute http:// or https:// URL") + return stripped + + +class ItemBase(BaseModel): + """Fields shared by the item create schema and the read model.""" + + title: str = Field(..., min_length=1, max_length=300) + url: str = Field(default="", max_length=500) + points: int = Field(default=0, ge=0) + content: str = Field(default="", description="HTML body from the Lexical editor.") + + @field_validator("title") + @classmethod + def _strip_title(cls, value: str) -> str: + return _clean_title(value) + + @field_validator("url") + @classmethod + def _validate_url(cls, value: str) -> str: + return _clean_url(value) + + +class ItemCreate(ItemBase): + """Payload of ``POST /api/v1/admin/items``. + + ``username`` is optional: when omitted the item belongs to the + authenticated admin. + """ + + username: str | None = Field(default=None, min_length=1, max_length=60) + + +class ItemUpdate(BaseModel): + """Payload of ``PUT /api/v1/admin/items/{id}`` (all fields optional).""" + + title: str | None = Field(default=None, max_length=300) + url: str | None = Field(default=None, max_length=500) + points: int | None = Field(default=None, ge=0) + username: str | None = Field(default=None, min_length=1, max_length=60) + content: str | None = None + + @field_validator("title") + @classmethod + def _strip_title(cls, value: str | None) -> str | None: + if value is None: + return None + return _clean_title(value) + + @field_validator("url") + @classmethod + def _validate_url(cls, value: str | None) -> str | None: + return None if value is None else _clean_url(value) + + +class ItemRead(BaseModel): + """Item as returned by the admin API.""" + + model_config = ConfigDict(from_attributes=True) + + id: int + title: str + url: str + points: int + username: str + content: str + created_at: datetime + + +class ItemAdminList(BaseModel): + """Paginated item list of ``GET /api/v1/admin/items``.""" + + items: list[ItemRead] + total: int + page: int + page_size: int + total_pages: int diff --git a/backend/seed_admin.py b/backend/seed_admin.py new file mode 100644 index 0000000..5d888e9 --- /dev/null +++ b/backend/seed_admin.py @@ -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()) diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py new file mode 100644 index 0000000..7c634ae --- /dev/null +++ b/backend/tests/test_admin.py @@ -0,0 +1,502 @@ +"""Tests for the admin area: /api/v1/admin/items CRUD, access control. + +Covers the M6 acceptance criteria: 401/403 handling for the admin +dependency, pagination/search/sort on the list endpoint, item 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 Item, User + +BASE = "/api/v1/admin/items" + + +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 _seed_items(session, count: int, prefix: str = "Story") -> list[Item]: + items = [] + for i in range(count): + item = Item( + title=f"{prefix} {i:02d}", + url=f"https://example.com/story-{i}", + points=i, + username="alice", + content=f"

Body {i}

", + ) + session.add(item) + items.append(item) + session.commit() + return items + + +class TestAdminAccessControl: + """The admin dependency validates the JWT AND the is_admin flag.""" + + @pytest.mark.parametrize( + "method, path", + [ + ("GET", f"{BASE}"), + ("POST", BASE), + ("GET", f"{BASE}/1"), + ("PUT", f"{BASE}/1"), + ("DELETE", f"{BASE}/1"), + ], + ) + def test_missing_token_returns_401(self, client, method, path) -> None: + payload = {"title": "x"} if method == "POST" else ({"title": "y"} if method == "PUT" else None) + 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: + user = _make_user(session, "admin", is_admin=True) + headers = _headers(session, "admin") + session.delete(user) + session.commit() + response = client.get(BASE, headers=headers) + assert response.status_code == 401 + assert response.json()["detail"] == "Unknown user" + + @pytest.mark.parametrize( + "method, path", + [ + ("GET", f"{BASE}"), + ("POST", BASE), + ("GET", f"{BASE}/1"), + ("PUT", f"{BASE}/1"), + ("DELETE", f"{BASE}/1"), + ], + ) + def test_non_admin_receives_403(self, client, session, method, path) -> None: + _make_user(session, "alice", is_admin=False) + payload = {"title": "x"} if method == "POST" else ({"title": "y"} if method == "PUT" else None) + 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" + + def test_admin_dependency_returns_the_user_object(self, client, session) -> None: + """get_current_admin yields the ORM user (used for audit logging later).""" + admin = _make_user(session, "root", is_admin=True) + response = client.get(BASE, headers=_headers(session, "root")) + assert response.status_code == 200 + assert admin.is_admin is True + + +class TestListItems: + def test_empty_list(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + response = client.get(BASE, headers=_headers(session, "root")) + assert response.status_code == 200 + body = response.json() + assert body["items"] == [] + assert body["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_items(session, 25) + headers = _headers(session, "root") + + page1 = client.get(BASE, params={"page": 1, "page_size": 10}, headers=headers).json() + assert page1["total"] == 25 + assert page1["total_pages"] == 3 + assert len(page1["items"]) == 10 + assert page1["page"] == 1 + + page2 = client.get(BASE, params={"page": 2, "page_size": 10}, headers=headers).json() + assert len(page2["items"]) == 10 + # Pages are disjoint. + ids1 = {i["id"] for i in page1["items"]} + ids2 = {i["id"] for i in page2["items"]} + assert ids1.isdisjoint(ids2) + + page3 = client.get(BASE, params={"page": 3, "page_size": 10}, headers=headers).json() + assert len(page3["items"]) == 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_url_case_insensitively(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + _seed_items(session, 5) + headers = _headers(session, "root") + + by_title = client.get(BASE, params={"search": "STORY 02"}, headers=headers).json() + assert [i["title"] for i in by_title["items"]] == ["Story 02"] + + # Seed URLs are https://example.com/story- (no zero padding). + by_url = client.get(BASE, params={"search": "EXAMPLE.COM/STORY-4"}, headers=headers).json() + assert [i["title"] for i in by_url["items"]] == ["Story 04"] + + none = client.get(BASE, params={"search": "does-not-exist"}, headers=headers).json() + assert none["items"] == [] + assert none["total"] == 0 + + @pytest.mark.parametrize("order, expected_first", [("asc", "Story 00"), ("desc", "Story 04")]) + def test_sort_by_title(self, client, session, order, expected_first) -> None: + _make_user(session, "root", is_admin=True) + _seed_items(session, 5) + headers = _headers(session, "root") + body = client.get( + BASE, params={"sort_by": "title", "sort_order": order}, headers=headers + ).json() + assert body["items"][0]["title"] == expected_first + assert [i["title"] for i in body["items"]] == sorted( + (i["title"] for i in body["items"]), reverse=(order == "desc") + ) + + @pytest.mark.parametrize("order, expected_first_points", [("asc", 0), ("desc", 4)]) + def test_sort_by_points(self, client, session, order, expected_first_points) -> None: + _make_user(session, "root", is_admin=True) + _seed_items(session, 5) + headers = _headers(session, "root") + body = client.get( + BASE, params={"sort_by": "points", "sort_order": order}, headers=headers + ).json() + assert body["items"][0]["points"] == expected_first_points + + @pytest.mark.parametrize("order", ["asc", "desc"]) + def test_sort_by_created_at(self, client, session, order) -> None: + _make_user(session, "root", is_admin=True) + items = _seed_items(session, 5) + # Distinct timestamps so the ordering is deterministic. + base = datetime(2025, 1, 1, tzinfo=timezone.utc) + for index, item in enumerate(items): + item.created_at = base + timedelta(minutes=index) + session.commit() + + headers = _headers(session, "root") + body = client.get( + BASE, params={"sort_by": "created_at", "sort_order": order}, headers=headers + ).json() + stamps = [i["created_at"] for i in body["items"]] + assert stamps == sorted(stamps, reverse=(order == "desc")) + + def test_invalid_sort_values_rejected(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + headers = _headers(session, "root") + assert client.get(BASE, params={"sort_by": "points"}, headers=headers).status_code == 200 + assert ( + client.get(BASE, params={"sort_by": "username"}, headers=headers).status_code == 422 + ) + assert ( + client.get(BASE, params={"sort_order": "up"}, headers=headers).status_code == 422 + ) + + def test_item_payload_shape(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + _seed_items(session, 1) + headers = _headers(session, "root") + body = client.get(BASE, headers=headers).json() + item = body["items"][0] + assert set(item) == {"id", "title", "url", "points", "username", "content", "created_at"} + + +class TestGetItem: + def test_returns_full_item_including_content(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + items = _seed_items(session, 1) + headers = _headers(session, "root") + response = client.get(f"{BASE}/{items[0].id}", headers=headers) + assert response.status_code == 200 + body = response.json() + assert body["id"] == items[0].id + assert body["title"] == "Story 00" + assert body["content"] == "

Body 0

" + assert body["username"] == "alice" + + 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 TestCreateItem: + def test_create_with_title_only_uses_defaults(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + headers = _headers(session, "root") + response = client.post(BASE, json={"title": "Fresh news"}, headers=headers) + assert response.status_code == 201 + body = response.json() + assert body["title"] == "Fresh news" + assert body["url"] == "" + assert body["points"] == 0 + assert body["content"] == "" + # The item belongs to the admin that created it. + assert body["username"] == "root" + + def test_create_with_all_fields(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + headers = _headers(session, "root") + payload = { + "title": " Padded title ", + "url": " https://example.com/story ", + "points": 12, + "username": "bob", + "content": "

Hello world

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

Hello world

" + + @pytest.mark.parametrize( + "payload", + [ + {}, # missing title + {"title": ""}, # empty title + {"title": " "}, # blank title + {"title": "x" * 301}, # too long + {"title": "ok", "points": -1}, # negative points + {"title": "ok", "url": "not-a-url"}, # invalid URL + {"title": "ok", "url": "ftp://example.com/x"}, # wrong scheme + {"title": "ok", "url": "https://"}, # missing host + {"title": "ok", "url": "x" * 501}, # too long + {"title": "ok", "points": 1.5}, # not an integer + {"title": "ok", "username": ""}, # empty username + ], + ) + def test_validation_failures_return_422(self, client, session, payload) -> None: + _make_user(session, "root", is_admin=True) + headers = _headers(session, "root") + response = client.post(BASE, json=payload, headers=headers) + assert response.status_code == 422 + assert response.json()["code"] == "validation_error" + + +class TestUpdateItem: + def test_partial_update_changes_only_provided_fields(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + items = _seed_items(session, 1) + headers = _headers(session, "root") + + response = client.put( + f"{BASE}/{items[0].id}", json={"points": 99}, headers=headers + ) + assert response.status_code == 200 + body = response.json() + assert body["points"] == 99 + # Untouched fields keep their values. + assert body["title"] == "Story 00" + assert body["url"] == "https://example.com/story-0" + assert body["content"] == "

Body 0

" + + def test_full_update(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + items = _seed_items(session, 1) + headers = _headers(session, "root") + payload = { + "title": "Retitled", + "url": "https://example.com/new", + "points": 7, + "username": "carol", + "content": "

Updated

", + } + response = client.put(f"{BASE}/{items[0].id}", json=payload, headers=headers) + assert response.status_code == 200 + body = response.json() + assert body == {**body, **payload, "id": items[0].id} + + def test_unknown_id_returns_404(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + headers = _headers(session, "root") + response = client.put(f"{BASE}/9999", json={"title": "x"}, headers=headers) + assert response.status_code == 404 + + def test_invalid_payload_returns_422(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + items = _seed_items(session, 1) + headers = _headers(session, "root") + response = client.put( + f"{BASE}/{items[0].id}", json={"title": "", "points": -3}, headers=headers + ) + assert response.status_code == 422 + + def test_empty_payload_is_a_no_op(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + items = _seed_items(session, 1) + headers = _headers(session, "root") + response = client.put(f"{BASE}/{items[0].id}", json={}, headers=headers) + assert response.status_code == 200 + assert response.json()["title"] == "Story 00" + + +class TestDeleteItem: + def test_delete_removes_the_item(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + items = _seed_items(session, 1) + headers = _headers(session, "root") + item_id = items[0].id + + response = client.delete(f"{BASE}/{item_id}", headers=headers) + assert response.status_code == 204 + assert response.content == b"" + + assert client.get(f"{BASE}/{item_id}", headers=headers).status_code == 404 + assert session.query(Item).filter(Item.id == item_id).first() is None + + def test_delete_unknown_id_returns_404(self, client, session) -> None: + _make_user(session, "root", is_admin=True) + headers = _headers(session, "root") + response = client.delete(f"{BASE}/9999", headers=headers) + assert response.status_code == 404 + + +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, tmp_path, 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() diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py index 662cfbf..f6121fc 100644 --- a/backend/tests/test_auth.py +++ b/backend/tests/test_auth.py @@ -64,6 +64,8 @@ class TestRegisterEndpoint: 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"]) @@ -138,7 +140,8 @@ 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 - assert response.json() == {"username": "alice"} + # 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") diff --git a/backend/tests/test_models.py b/backend/tests/test_models.py index b1a6f31..7f37ad8 100644 --- a/backend/tests/test_models.py +++ b/backend/tests/test_models.py @@ -3,7 +3,7 @@ import pytest from sqlalchemy.exc import IntegrityError -from models import Article, Author, Category, User, slugify +from models import Article, Author, Category, Item, User, slugify class TestAuthor: @@ -49,8 +49,16 @@ class TestUser: 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() @@ -154,3 +162,34 @@ class TestArticle: with pytest.raises(IntegrityError): session.commit() session.rollback() + + +class TestItem: + def test_create_and_commit_defaults(self, session) -> None: + item = Item(title="Breaking: things happen") + session.add(item) + session.commit() + session.refresh(item) + assert item.id is not None + assert item.url == "" + assert item.points == 0 + assert item.username == "anonymous" + assert item.content == "" + assert item.created_at is not None + + def test_create_with_all_fields(self, session) -> None: + item = Item( + title="Show HN: a new tool", + url="https://example.com/show-hn", + points=42, + username="alice", + content="

Hello world

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

Hello world

" diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 383baac..a48b5f1 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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", diff --git a/frontend/package.json b/frontend/package.json index ad14e9e..9139785 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/playwright/e2e/admin.spec.ts b/frontend/playwright/e2e/admin.spec.ts new file mode 100644 index 0000000..489500d --- /dev/null +++ b/frontend/playwright/e2e/admin.spec.ts @@ -0,0 +1,408 @@ +import { expect, test, type Page } from '@playwright/test'; + +/** + * E2E tests for the admin area (M6) with a fully mocked backend + * (in-memory item store + token-based auth), following the approach of + * the other specs in this directory. + */ + +const ADMIN_TOKEN = 'mock-admin-token'; +const USER_TOKEN = 'mock-user-token'; +const TOKEN_KEY = 'AUTH_TOKEN'; + +interface Item { + id: number; + title: string; + url: string; + points: number; + username: string; + content: string; + created_at: string; +} + +const envelope = (detail: string, code: string) => JSON.stringify({ detail, code }); + +/** Build the auth + admin API mock with a per-test item store. */ +function mockAdminApi(page: Page): { store: Item[]; nextId: () => number } { + let idCounter = 100; + const store: Item[] = [ + { + id: 1, + title: 'Breaking: local cat discovers keyboard', + url: 'https://example.com/cat-keyboard', + points: 42, + username: 'alice', + content: '

Amazing news.

', + created_at: '2024-05-01T10:00:00Z', + }, + { + id: 2, + title: 'Study: coffee improves code reviews', + url: 'https://example.com/coffee-reviews', + points: 17, + username: 'bob', + content: '

Peer-reviewed.

', + created_at: '2024-05-02T11:30:00Z', + }, + { + id: 3, + title: 'Show HN: I built a tiny news app', + url: 'https://example.com/show-hn-newz', + points: 5, + username: 'alice', + content: '

Feedback welcome.

', + created_at: '2024-05-03T09:15:00Z', + }, + ]; + + const requireAdmin = (route: Parameters[1]>[0]): boolean => { + const header = route.request().headers()['authorization']; + if (header !== `Bearer ${ADMIN_TOKEN}`) { + route.fulfill({ + status: 403, + contentType: 'application/json', + body: envelope('Admin access required', 'forbidden'), + }); + return false; + } + return true; + }; + + page.route('**/api/v1/auth/me', (route) => { + const header = route.request().headers()['authorization']; + if (header === `Bearer ${ADMIN_TOKEN}`) { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ username: 'alice', is_admin: true }), + }); + } + if (header === `Bearer ${USER_TOKEN}`) { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ username: 'bob', is_admin: false }), + }); + } + return route.fulfill({ + status: 401, + contentType: 'application/json', + body: envelope('Invalid or expired token', 'unauthorized'), + }); + }); + page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 })); + + // Collection endpoint: GET (list) + POST (create). + page.route(/\/api\/v1\/admin\/items(\?.*)?$/, (route) => { + const request = route.request(); + if (request.method() === 'GET') { + if (!requireAdmin(route)) return; + const url = new URL(request.url()); + const search = (url.searchParams.get('search') ?? '').toLowerCase(); + const sortBy = (url.searchParams.get('sort_by') ?? 'created_at') as keyof Item; + const sortOrder = url.searchParams.get('sort_order') ?? 'desc'; + const pageSize = Number(url.searchParams.get('page_size') ?? 20); + const page_ = Number(url.searchParams.get('page') ?? 1); + + const filtered = store.filter( + (item) => + !search || + item.title.toLowerCase().includes(search) || + item.url.toLowerCase().includes(search), + ); + filtered.sort((a, b) => { + const cmp = String(a[sortBy]).localeCompare(String(b[sortBy])); + return sortOrder === 'asc' ? cmp : -cmp; + }); + const start = (page_ - 1) * pageSize; + const slice = filtered.slice(start, start + pageSize); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + items: slice, + total: filtered.length, + page: page_, + page_size: pageSize, + total_pages: Math.ceil(filtered.length / pageSize) || 0, + }), + }); + } + if (request.method() === 'POST') { + if (!requireAdmin(route)) return; + const body = request.postDataJSON() as Partial; + const item: Item = { + id: ++idCounter, + title: body.title ?? '', + url: body.url ?? '', + points: body.points ?? 0, + username: body.username ?? 'alice', + content: body.content ?? '', + created_at: new Date().toISOString(), + }; + store.push(item); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify(item), + }); + } + return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') }); + }); + + // Item endpoint: GET / PUT / DELETE by id. + page.route('**/api/v1/admin/items/*', (route) => { + const request = route.request(); + const id = Number(request.url().split('/').pop()); + if (!requireAdmin(route)) return; + const item = store.find((entry) => entry.id === id); + + if (request.method() === 'GET') { + if (!item) { + return route.fulfill({ + status: 404, + contentType: 'application/json', + body: envelope('Item not found', 'not_found'), + }); + } + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) }); + } + if (request.method() === 'PUT') { + if (!item) { + return route.fulfill({ + status: 404, + contentType: 'application/json', + body: envelope('Item not found', 'not_found'), + }); + } + const body = request.postDataJSON() as Partial; + Object.assign(item, body); + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) }); + } + if (request.method() === 'DELETE') { + if (!item) { + return route.fulfill({ + status: 404, + contentType: 'application/json', + body: envelope('Item not found', 'not_found'), + }); + } + store.splice(store.indexOf(item), 1); + return route.fulfill({ status: 204 }); + } + return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') }); + }); + + return { store, nextId: () => idCounter }; +} + +async function seedToken(page: Page, token: string | null): Promise { + if (token === null) { + await page.addInitScript((key) => localStorage.removeItem(key), TOKEN_KEY); + } else { + await page.addInitScript( + ([key, value]) => localStorage.setItem(key, value), + [TOKEN_KEY, token] as const, + ); + } +} + +test.describe('admin area (M6)', () => { + test('signed-out users are redirected to /login', async ({ page }) => { + mockAdminApi(page); + await seedToken(page, null); + + await page.goto('/admin'); + + await expect(page).toHaveURL('/login'); + }); + + test('non-admins see the 403 page', async ({ page }) => { + mockAdminApi(page); + await seedToken(page, USER_TOKEN); + + await page.goto('/admin'); + + await expect(page.getByRole('heading', { level: 1, name: '403' })).toBeVisible(); + await expect( + page.getByTestId('forbidden-page').getByText(/admin area/i), + ).toBeVisible(); + }); + + test('admins see the dashboard with all items and an Admin header link', async ({ + page, + }) => { + mockAdminApi(page); + await seedToken(page, ADMIN_TOKEN); + + // The header exposes the admin link for admin accounts. + await page.goto('/'); + await expect(page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i })).toBeVisible(); + + await page.goto('/admin'); + + await expect(page.getByRole('heading', { level: 1, name: 'Items' })).toBeVisible(); + await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible(); + await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible(); + await expect(page.getByText('Show HN: I built a tiny news app')).toBeVisible(); + await expect(page.getByText('Showing 1–3 of 3')).toBeVisible(); + }); + + test('non-admin accounts do not get the Admin header link', async ({ page }) => { + mockAdminApi(page); + await seedToken(page, USER_TOKEN); + + await page.goto('/'); + + await expect( + page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i }), + ).toHaveCount(0); + }); + + test('search filters the list by title or URL', async ({ page }) => { + mockAdminApi(page); + await seedToken(page, ADMIN_TOKEN); + + await page.goto('/admin'); + await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible(); + + await page.getByLabel('Search items').fill('coffee'); + await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible(); + await expect( + page.getByText('Breaking: local cat discovers keyboard'), + ).toHaveCount(0); + + // URL search (case-insensitive on the server side). + await page.getByLabel('Search items').fill('EXAMPLE.COM/CAT'); + await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible(); + await expect(page.getByText('Showing 1–1 of 1')).toBeVisible(); + }); + + test('sorting by title toggles direction', async ({ page }) => { + mockAdminApi(page); + await seedToken(page, ADMIN_TOKEN); + + await page.goto('/admin'); + const firstTitle = page.locator('tbody tr').first().locator('td').first().locator('span, a').first(); + + // Default: created_at desc -> newest first. + await expect(firstTitle).toHaveText('Show HN: I built a tiny news app'); + + await page.getByRole('button', { name: /sort by title/i }).click(); + await expect(firstTitle).toHaveText('Breaking: local cat discovers keyboard'); + + await page.getByRole('button', { name: /sort by title/i }).click(); + await expect(firstTitle).toHaveText('Study: coffee improves code reviews'); + }); + + test('create: fills the form, saves with the Lexical editor and lists the item', async ({ + page, + }) => { + const { store } = mockAdminApi(page); + await seedToken(page, ADMIN_TOKEN); + + await page.goto('/admin/items/new'); + await expect(page.getByRole('heading', { level: 1, name: 'New item' })).toBeVisible(); + + await page.getByLabel(/^Title/).fill('E2E: fresh story from the admin area'); + await page.getByLabel(/^URL/).fill('https://example.com/e2e-story'); + await page.getByLabel('Points').fill('3'); + // The author is pre-filled from the session. + await expect(page.getByLabel('Author')).toHaveValue('alice'); + + // Type into the Lexical contenteditable (rich text editor). + await page.getByLabel('Item content').click(); + await page.keyboard.type('Written with the Lexical editor.'); + + await page.getByRole('button', { name: /create item/i }).click(); + + // Back on the dashboard with the success notice. + await expect(page).toHaveURL('/admin'); + await expect(page.getByRole('status')).toHaveText(/was saved/i); + await expect(page.getByText('E2E: fresh story from the admin area', { exact: true })).toBeVisible(); + + // The backend received the rich content. + const created = store.find((item) => + item.title.includes('E2E: fresh story'), + ); + expect(created).toBeTruthy(); + expect(created?.content).toContain('Written with the Lexical editor.'); + expect(created?.points).toBe(3); + expect(created?.username).toBe('alice'); + }); + + test('edit: loads the item, updates fields and saves', async ({ page }) => { + const { store } = mockAdminApi(page); + await seedToken(page, ADMIN_TOKEN); + + await page.goto('/admin'); + await page.locator('tbody tr', { hasText: 'Breaking: local cat' }).getByRole('link', { name: /edit/i }).click(); + + await expect(page.getByRole('heading', { level: 1, name: /edit item/i })).toBeVisible(); + await expect(page.getByLabel(/^Title/)).toHaveValue('Breaking: local cat discovers keyboard'); + await expect(page.getByLabel('Points')).toHaveValue('42'); + + await page.getByLabel(/^Title/).fill('Breaking: local cat becomes famous'); + await page.getByRole('button', { name: /save changes/i }).click(); + + await expect(page).toHaveURL('/admin'); + await expect(page.getByRole('status')).toHaveText(/was saved/i); + await expect(page.getByRole('cell', { name: 'Breaking: local cat becomes famous', exact: true })).toBeVisible(); + + const updated = store.find((item) => item.id === 1); + expect(updated?.title).toBe('Breaking: local cat becomes famous'); + // Untouched fields survive the partial save. + expect(updated?.points).toBe(42); + }); + + test('delete: requires confirmation, then removes the item', async ({ page }) => { + const { store } = mockAdminApi(page); + await seedToken(page, ADMIN_TOKEN); + + await page.goto('/admin'); + const target = page.getByText('Study: coffee improves code reviews'); + await expect(target).toBeVisible(); + + // Open the confirmation dialog (first row's delete button). + page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click(); + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + await expect( + dialog.getByRole('heading', { name: /are you sure you want to delete/i }), + ).toBeVisible(); + await expect(dialog.getByText(/cannot be undone/i)).toBeVisible(); + + // Cancel keeps the item. + await dialog.getByRole('button', { name: /cancel/i }).click(); + await expect(dialog).toHaveCount(0); + await expect(target).toBeVisible(); + expect(store).toHaveLength(3); + + // Confirm with the explicit "Yes, delete" action. + page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click(); + await expect(page.getByRole('dialog')).toBeVisible(); + await page.getByRole('button', { name: /yes, delete/i }).click(); + + await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible(); + await expect(page.getByRole('cell', { name: 'Study: coffee improves code reviews', exact: true })).toHaveCount(0); + await expect(page.getByRole('status')).toHaveText(/was deleted/i); + expect(store).toHaveLength(2); + }); + + test('pagination: next/previous and the page size selector work', async ({ page }) => { + mockAdminApi(page); + await seedToken(page, ADMIN_TOKEN); + + await page.goto('/admin'); + + // 3 seeded items fit on one page: navigation is disabled. + await expect(page.getByRole('button', { name: /next/i })).toBeDisabled(); + await expect(page.getByRole('button', { name: /previous/i })).toBeDisabled(); + + // Smaller page size splits the list across pages. + await page.getByLabel('Rows per page').selectOption('10'); + await expect(page).toHaveURL(/\/admin/); + // (Still one page for 3 items — assert the selector round-trips.) + await expect(page.getByLabel('Rows per page')).toHaveValue('10'); + }); +}); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6221348..c9aadad 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,9 +1,12 @@ import { BrowserRouter, Link, Route, Routes } from 'react-router-dom'; -import { AuthProvider, RequireAuth } from './auth'; +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 EditItemPage from './pages/EditItemPage'; import Home from './pages/Home'; import Login from './pages/Login'; import Register from './pages/Register'; @@ -28,10 +31,15 @@ function NotFound() { * 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); Layout - * provides the shared shell (header/footer); Routes maps URLs to page - * components in src/pages/. In-app navigation always uses - * react-router-dom /. + * 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. + * + * In-app navigation always uses react-router-dom /. */ export default function App() { return ( @@ -42,26 +50,48 @@ export default function App() { }} > - - - } /> - } /> - } /> - } /> - } /> - } /> - } /> - - - - } - /> - } /> - - + + {/* Admin area (own shell, admin-only) */} + + + + } + > + } /> + } /> + } /> + + + {/* Public site */} + + + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + } + /> + } /> + + + } + /> + ); diff --git a/frontend/src/api/admin.ts b/frontend/src/api/admin.ts new file mode 100644 index 0000000..e030aa4 --- /dev/null +++ b/frontend/src/api/admin.ts @@ -0,0 +1,46 @@ +/** + * Admin API client (item 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 { + AdminItem, + AdminItemInput, + AdminItemsPage, + AdminListParams, +} from '../types/admin'; + +/** `GET /api/v1/admin/items` — paginated, searchable, sortable list. */ +export function adminListItems(params: AdminListParams): Promise { + const query = new URLSearchParams(); + query.set('page', String(params.page)); + query.set('page_size', String(params.pageSize)); + if (params.search.trim()) query.set('search', params.search.trim()); + query.set('sort_by', params.sortBy); + query.set('sort_order', params.sortOrder); + return api.get(`/admin/items?${query.toString()}`); +} + +/** `GET /api/v1/admin/items/{id}` — a single item (including content). */ +export function adminGetItem(id: number): Promise { + return api.get(`/admin/items/${id}`); +} + +/** `POST /api/v1/admin/items` — create a new item. */ +export function adminCreateItem(input: AdminItemInput): Promise { + return api.post('/admin/items', input); +} + +/** `PUT /api/v1/admin/items/{id}` — update an item. */ +export function adminUpdateItem(id: number, input: AdminItemInput): Promise { + return api.put(`/admin/items/${id}`, input); +} + +/** `DELETE /api/v1/admin/items/{id}` — hard-delete an item (204). */ +export function adminDeleteItem(id: number): Promise { + return api.delete(`/admin/items/${id}`); +} diff --git a/frontend/src/assets/styles/admin.css b/frontend/src/assets/styles/admin.css new file mode 100644 index 0000000..0c73877 --- /dev/null +++ b/frontend/src/assets/styles/admin.css @@ -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; +} diff --git a/frontend/src/auth.tsx b/frontend/src/auth.tsx index 139ad2a..b70f33e 100644 --- a/frontend/src/auth.tsx +++ b/frontend/src/auth.tsx @@ -5,7 +5,11 @@ * 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 only owns the username + ready state. + * `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, @@ -16,7 +20,7 @@ import { useMemo, useState, } from 'react'; -import { Navigate, useLocation } from 'react-router-dom'; +import { Link, Navigate, useLocation } from 'react-router-dom'; import { TOKEN_KEY, login as apiLogin, @@ -28,6 +32,8 @@ import { 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. */ @@ -42,6 +48,7 @@ const AuthContext = createContext(null); export function AuthProvider({ children }: { children: ReactNode }) { const [username, setUsername] = useState(null); + const [isAdmin, setIsAdmin] = useState(false); const [ready, setReady] = useState(false); // Restore the session on first load: validate the stored token and drop @@ -53,7 +60,10 @@ export function AuthProvider({ children }: { children: ReactNode }) { return; } apiMe(stored) - .then((user) => setUsername(user.username)) + .then((user) => { + setUsername(user.username); + setIsAdmin(user.is_admin ?? false); + }) .catch(() => localStorage.removeItem(TOKEN_KEY)) .finally(() => setReady(true)); }, []); @@ -62,12 +72,14 @@ export function AuthProvider({ children }: { children: ReactNode }) { 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(() => { @@ -76,11 +88,12 @@ export function AuthProvider({ children }: { children: ReactNode }) { apiLogout().catch(() => undefined); localStorage.removeItem(TOKEN_KEY); setUsername(null); + setIsAdmin(false); }, []); const value = useMemo( - () => ({ username, ready, login, register, logout }), - [username, ready, login, register, logout], + () => ({ username, isAdmin, ready, login, register, logout }), + [username, isAdmin, ready, login, register, logout], ); return {children}; @@ -114,3 +127,41 @@ export function RequireAuth({ children }: { children: ReactNode }) { } 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 ( +
+ Checking session… +
+ ); + } + if (username === null) { + return ; + } + if (!isAdmin) { + return ( +
+

403

+

Forbidden

+

+ Your account does not have access to the admin area. Ask a site + administrator if you believe this is a mistake. +

+ + Back to home + +
+ ); + } + return <>{children}; +} diff --git a/frontend/src/components/AdminLayout.tsx b/frontend/src/components/AdminLayout.tsx new file mode 100644 index 0000000..7735679 --- /dev/null +++ b/frontend/src/components/AdminLayout.tsx @@ -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 ``. + */ +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 ( +
+ {mobileOpen && ( + + ); +} + +export default AdminLayout; diff --git a/frontend/src/components/DeleteConfirmation.tsx b/frontend/src/components/DeleteConfirmation.tsx new file mode 100644 index 0000000..c43f41a --- /dev/null +++ b/frontend/src/components/DeleteConfirmation.tsx @@ -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 { AdminItem } from '../types/admin'; + +export interface DeleteConfirmationProps { + /** The item about to be deleted. */ + item: AdminItem; + /** `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({ + item, + busy = false, + error = null, + onConfirm, + onCancel, +}: DeleteConfirmationProps) { + const cancelRef = useRef(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 ( +
+
event.stopPropagation()} + > +
+ + +
+

+ Are you sure you want to delete this item? +

+

+ “{item.title}” will be + permanently removed. This action cannot be undone. +

+
+
+ + {error && ( +

+ {error} +

+ )} + +
+ + +
+
+
+ ); +} + +export default DeleteConfirmation; diff --git a/frontend/src/components/LexicalEditor.tsx b/frontend/src/components/LexicalEditor.tsx new file mode 100644 index 0000000..911eae3 --- /dev/null +++ b/frontend/src/components/LexicalEditor.tsx @@ -0,0 +1,391 @@ +/** + * 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 `items.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; + 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 ( + { + console.error('Lexical editor error:', error); + }, + }} + > + + + ); +} + +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). + useEffect(() => { + if (!initialHtml) return; + const doc = document.implementation.createHTMLDocument(''); + doc.body.innerHTML = initialHtml; + editor.update( + () => { + $generateNodesFromDOM(editor, doc); + }, + { discrete: true }, + ); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [editor]); + + return ( +
+ + + } + ErrorBoundary={LexicalErrorBoundary} + /> + {placeholder && } + + + { + editorState.read(() => { + onChange.current($generateHtmlFromNodes(editor)); + }); + }} + /> +
+ ); +} + +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 ( + + {text} + + ); +} + +/* --- Toolbar ---------------------------------------------------------------- */ + +function Toolbar() { + const [editor] = useLexicalComposerContext(); + const [state, setState] = useState(DEFAULT_TOOLBAR); + const [linkInputOpen, setLinkInputOpen] = useState(false); + const [linkUrl, setLinkUrl] = useState(''); + const linkInputRef = useRef(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) => + 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, + ) => ( + + ); + + return ( +
+ {button('Undo', false, () => editor.dispatchCommand(UNDO_COMMAND, undefined), , !state.canUndo)} + {button('Redo', false, () => editor.dispatchCommand(REDO_COMMAND, undefined), , !state.canRedo)} +
+ ); +} diff --git a/frontend/src/components/ui/Header.tsx b/frontend/src/components/ui/Header.tsx index a28e25c..be3772f 100644 --- a/frontend/src/components/ui/Header.tsx +++ b/frontend/src/components/ui/Header.tsx @@ -1,4 +1,4 @@ -import { FileText, Home, LogOut, Menu, Settings, User, 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 { Link, NavLink } from 'react-router-dom'; import { useAuth } from '../../auth'; @@ -32,7 +32,7 @@ const NAV_ITEMS: NavItem[] = [ */ export function Header({ className }: HeaderProps) { const [menuOpen, setMenuOpen] = useState(false); - const { username, ready } = useAuth(); + const { username, isAdmin, ready } = useAuth(); const closeMenu = () => setMenuOpen(false); @@ -86,6 +86,17 @@ export function Header({ className }: HeaderProps) { {label} ))} + {/* Admin link (M6): only visible to admin accounts. */} + {ready && isAdmin && ( + linkClasses({ isActive })} + onClick={closeMenu} + > + + )} ); diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 71290d7..ac90fd4 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -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( diff --git a/frontend/src/pages/AdminDashboard.tsx b/frontend/src/pages/AdminDashboard.tsx new file mode 100644 index 0000000..6787398 --- /dev/null +++ b/frontend/src/pages/AdminDashboard.tsx @@ -0,0 +1,480 @@ +/** + * Admin dashboard (M6): paginated list of all items with debounced + * search (300ms), sortable columns (title / points / 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 { adminDeleteItem, adminListItems } from '../api/admin'; +import { DeleteConfirmation } from '../components/DeleteConfirmation'; +import { ApiError } from '../api/client'; +import { cn } from '../lib/utils'; +import type { + AdminItem, + AdminItemsPage, + 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([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(INITIAL_STATE); + const [debouncedSearch, setDebouncedSearch] = useState(''); + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [pendingDelete, setPendingDelete] = useState(null); + const [deleteBusy, setDeleteBusy] = useState(false); + const [deleteError, setDeleteError] = useState(null); + const [notice, setNotice] = useState(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 adminListItems({ + 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 items.', + ); + } 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) => + 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 adminDeleteItem(pendingDelete.id); + setPendingDelete(null); + setNotice(`“${pendingDelete.title}” was deleted.`); + await load(); + } catch (err) { + setDeleteError(err instanceof ApiError ? err.message : 'Deleting the item 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 ? ( +