Public Access
feat: phase r1+r2 recovery + r3-0 swiftly api ingestion
R1 stabilization: pytest harness with transactional db fixture, smoke + alembic + auth + scrape + approval + swiftly tests, github actions ci yaml. Bearer-token admin auth + signed-cookie session for family ui mutations. Async POST /api/admin/scrape (BackgroundTasks, returns 202). Path canonicalization (no /list, /planned suffixes). DATABASE_URL fail-fast on empty. R2 deferred-risk spikes: live lucky california fetch (R2-A), full email+per-voter approval click round trip with single-use enforcement (R2-B, console email backend, sendgrid stub). R3-0 phase 3 redesign: replaced playwright html scraper with requests based swiftly json api client. 17 categories, ~10k products per scrape, upsert by (source, external_id). 401 surfaces actionable token-refresh message via ScrapeLog.error_message. Pre-existing defects fixed: shopping_list.py syntax error blocking app import, MealPlan.votes orphan relationship, JSONB(astext=True) invalid kwarg, missing requests dep, calorie_target schema drift, every SQLEnum needed values_callable, 0001 had empty downgrade(), seed had duplicate ingredient rows. Migrations added: 0003 grocery_item.description, 0004 family_profile. calorie_target, 0005 grocery_item.external_id + source + composite index. Verified: 31/31 pytest green, alembic upgrade->downgrade->upgrade clean, frontend npm run build clean, live scrape 9,960 grocery_item rows in 36s. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
Auth dependencies for the MealPlanner backend.
|
||||
|
||||
Two flavors:
|
||||
- ``require_admin`` — bearer token for ``/api/admin/*`` routes; token compared
|
||||
to ``settings.ADMIN_TOKEN`` (must be set in env).
|
||||
- ``require_session`` — signed-cookie session (``itsdangerous``) gating
|
||||
mutations on the family-facing routers; reads stay open inside the
|
||||
trusted network.
|
||||
|
||||
The per-voter approval-token flow on meal items is intentionally NOT covered
|
||||
here — it has its own short-lived single-use tokens elsewhere.
|
||||
"""
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
from itsdangerous import BadSignature, SignatureExpired, TimestampSigner
|
||||
|
||||
from app.config import settings
|
||||
|
||||
bearer_header = "Authorization"
|
||||
|
||||
SESSION_COOKIE = "mp_session"
|
||||
SESSION_MAX_AGE = 60 * 60 * 24 * 30 # 30 days
|
||||
|
||||
|
||||
def require_admin(request: Request) -> None:
|
||||
"""Enforce a shared bearer token. 401 on bad/missing token, 503 if unset."""
|
||||
expected = settings.ADMIN_TOKEN
|
||||
if not expected:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Admin auth not configured",
|
||||
)
|
||||
auth = request.headers.get(bearer_header, "")
|
||||
if not auth.startswith("Bearer ") or auth[7:] != expected:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid admin token",
|
||||
)
|
||||
|
||||
|
||||
def _signer() -> TimestampSigner:
|
||||
return TimestampSigner(settings.SECRET_KEY)
|
||||
|
||||
|
||||
def issue_session(family_profile_id: str) -> str:
|
||||
"""Sign the family_profile_id and return the cookie value."""
|
||||
return _signer().sign(family_profile_id.encode()).decode()
|
||||
|
||||
|
||||
def require_session(request: Request) -> str:
|
||||
"""Return the family_profile_id stored in the signed session cookie."""
|
||||
raw = request.cookies.get(SESSION_COOKIE)
|
||||
if not raw:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Session required"
|
||||
)
|
||||
try:
|
||||
family_id = (
|
||||
_signer().unsign(raw.encode(), max_age=SESSION_MAX_AGE).decode()
|
||||
)
|
||||
except SignatureExpired:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Session expired"
|
||||
)
|
||||
except BadSignature:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid session"
|
||||
)
|
||||
return family_id
|
||||
Reference in New Issue
Block a user