fix(web): render the signed-in header on error pages

Exception handlers run outside FastAPI's dependency injection, so the error handler never resolved the session and always passed user=None, making every error page (e.g. a 404 hit while signed in) show the 'Sign In with Forgejo' header instead of the account menu.

Resolve the session by hand from the request cookie via lookup_session, degrading to None on any failure so error rendering can never itself raise. A missing or invalid cookie (a real 401) still yields None and the correct signed-out header.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
ZTatman 2026-07-18 13:32:43 -04:00
parent 4bb8f1229d
commit 3c236a9d3a

View file

@ -7,6 +7,7 @@ from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import Response
from app.auth.session import SESSION_COOKIE, lookup_session
from app.templating import templates
ERROR_TITLES = {
@ -19,6 +20,26 @@ ERROR_TITLES = {
}
async def _optional_user(request: Request):
"""Best-effort session lookup so error pages render the right header.
Exception handlers run outside FastAPI's dependency injection, so the
session is resolved by hand here. Any failure degrades to None — error
rendering must never itself raise. A missing/invalid cookie (e.g. a 401)
correctly yields None, so those pages still show the signed-out header.
"""
session_factory = getattr(request.app.state, "db_session", None)
token = request.cookies.get(SESSION_COOKIE)
if session_factory is None or not token:
return None
try:
async with session_factory() as db:
sess = await lookup_session(db, token)
return sess.user if sess else None
except Exception:
return None
async def http_exception_handler(request: Request, exc: Exception) -> Response:
"""Render a styled error page for browser requests, JSON for API clients."""
# Starlette only routes StarletteHTTPException here; narrow for the type
@ -34,6 +55,7 @@ async def http_exception_handler(request: Request, exc: Exception) -> Response:
"status_code": exc.status_code,
"title": ERROR_TITLES.get(exc.status_code, "Error"),
"detail": exc.detail,
"user": await _optional_user(request),
},
status_code=exc.status_code,
)