Newer
Older
gnexus-book / server / app / auth / middleware.py
from __future__ import annotations

from typing import Callable

from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send

from ..config import Settings
from ..storage.db import Database
from .actor import actor_for_current_user
from .context import current_actor
from .sessions import resolve_session


class SessionAuthMiddleware:
    """Resolve the browser session and guard non-exempt routes.

    Authentication is disabled when the gnexus-auth client is not configured, so
    local development and the file backend keep working without credentials.
    """

    def __init__(
        self, app: ASGIApp, settings_provider: Callable[[], Settings]
    ) -> None:
        self.app = app
        self._settings_provider = settings_provider
        self._database: Database | None = None

    def _db(self, settings: Settings) -> Database:
        if self._database is None:
            self._database = Database.from_settings(settings)
        return self._database

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        settings = self._settings_provider()
        if not settings.auth_enabled:
            await self.app(scope, receive, send)
            return

        request = Request(scope)
        state = scope.setdefault("state", {})
        token = request.cookies.get(settings.auth_session_cookie)
        user = None
        if token:
            try:
                user = await run_in_threadpool(resolve_session, self._db(settings), token)
            except Exception:
                response = JSONResponse(
                    {"detail": "Authentication storage is unavailable"},
                    status_code=503,
                )
                await response(scope, receive, send)
                return

        state["user"] = user
        actor_token = current_actor.set(actor_for_current_user(user, via="ui"))
        try:
            if user is None and not _is_exempt(request.url.path):
                response = JSONResponse({"detail": "Not authenticated"}, status_code=401)
                await response(scope, receive, send)
                return
            await self.app(scope, receive, send)
        finally:
            current_actor.reset(actor_token)


def _is_exempt(path: str) -> bool:
    return (
        path == "/health"
        or path == "/me"
        or path.startswith("/auth/")
        or path.startswith("/webhooks/gnexus-auth")
    )