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

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

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

134 lines
4.5 KiB
Python

"""Authentication primitives.
- Passwords are stored only as PBKDF2-HMAC-SHA256 hashes with a random
per-password salt (never in plaintext).
- Sessions are stateless JWTs (HS256) signed with ``HN_SECRET_KEY``
(see ``config.Settings``), valid for 7 days.
- ``get_current_user`` is the FastAPI dependency that validates the
``Authorization: Bearer <token>`` header and returns the username.
"""
import hashlib
import secrets
import time
import jwt
from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from config import get_settings
from db.session import get_db
from models import User
# HS256 JWTs signed with the application secret. The dev default keeps
# tokens valid across container restarts; override via HN_SECRET_KEY.
SECRET_KEY = get_settings().secret_key
ALGORITHM = "HS256"
TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days
# PBKDF2-HMAC-SHA256 parameters (120,000 iterations per OWASP guidance).
PBKDF2_ITERATIONS = 120_000
# ``auto_error=False`` so missing headers produce our own 401 envelope
# instead of FastAPI's default 403.
_bearer = HTTPBearer(auto_error=False)
def hash_password(password: str) -> str:
"""Hash ``password`` with a fresh random salt.
Returns ``"<salt>$<digest>"`` where ``salt`` is 32 hex chars
(``secrets.token_hex(16)``) and ``digest`` is the PBKDF2 hex digest.
"""
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
).hex()
return f"{salt}${digest}"
def verify_password(password: str, stored: str) -> bool:
"""Verify ``password`` against a stored ``"<salt>$<digest>"`` hash.
The comparison is constant-time (``secrets.compare_digest``).
Malformed stored values simply verify as ``False``.
"""
try:
salt, digest = stored.split("$", 1)
salt_bytes = bytes.fromhex(salt)
except ValueError:
return False
candidate = hashlib.pbkdf2_hmac(
"sha256", password.encode(), salt_bytes, PBKDF2_ITERATIONS
).hex()
return secrets.compare_digest(candidate, digest)
def create_token(username: str) -> str:
"""Create a signed JWT for ``username`` (``sub``/``iat``/``exp``)."""
now = int(time.time())
payload = {
"sub": username,
"iat": now,
"exp": now + TOKEN_TTL_SECONDS,
}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
def _user_for_token(
credentials: HTTPAuthorizationCredentials | None, db: Session
) -> User:
"""Validate the Bearer token and return the matching :class:`User`.
Raises 401 when the header is missing, the token is invalid/expired
or was issued to a user that no longer exists.
"""
if credentials is None:
raise HTTPException(status_code=401, detail="Not authenticated")
try:
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
except jwt.PyJWTError as exc:
raise HTTPException(status_code=401, detail="Invalid or expired token") from exc
username = payload.get("sub")
user = db.query(User).filter(User.username == username).first() if username else None
if user is None:
raise HTTPException(status_code=401, detail="Unknown user")
return user
def get_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
db: Session = Depends(get_db),
) -> str:
"""Validate the Bearer token and return the username.
Raises 401 when the header is missing, the token is invalid/expired
or was issued to a user that no longer exists.
"""
return _user_for_token(credentials, db).username
def get_current_user_obj(
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
db: Session = Depends(get_db),
) -> User:
"""Validate the Bearer token and return the matching :class:`User`."""
return _user_for_token(credentials, db)
def get_current_admin(
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
db: Session = Depends(get_db),
) -> User:
"""Admin-only dependency: validates the token *and* the ``is_admin`` flag.
A valid JWT alone is not enough — the account must additionally have
``User.is_admin`` set. Raises 401 for missing/invalid tokens or unknown
users and 403 ("Admin access required") for authenticated non-admins.
"""
user = _user_for_token(credentials, db)
if not user.is_admin:
raise HTTPException(status_code=403, detail="Admin access required")
return user