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

import hmac
from datetime import UTC, datetime
from typing import Any
from urllib.parse import urlsplit

from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import JSONResponse, RedirectResponse
from gnexus_gauth.exceptions import WebhookPayloadException, WebhookVerificationException
from pydantic import BaseModel
from starlette.concurrency import run_in_threadpool

from ..config import Settings, get_settings
from ..storage.db import Database
from .service import AuthError, AuthService
from .sessions import SUPPORTED_LOCALES, revoke_session, set_user_locale
from .users import serialize_user
from .webhooks import handle_webhook_event

router = APIRouter()


class MeUpdate(BaseModel):
    locale: str | None = None


def get_auth_service(
    settings: Settings = Depends(get_settings),
) -> AuthService | None:
    if not settings.auth_enabled:
        return None
    return AuthService(settings, Database.from_settings(settings))


def _me_payload(request: Request, settings: Settings) -> dict[str, Any]:
    user = getattr(request.state, "user", None)
    return {
        "auth_enabled": settings.auth_enabled,
        "user": serialize_user(user) if user else None,
        "locale": user.locale if user else None,
        "locale_effective": user.effective_locale if user else "en",
    }


def _safe_return_to(value: str | None) -> str | None:
    if not value or "\\" in value or any(ord(character) < 32 for character in value):
        return None
    parts = urlsplit(value)
    if parts.scheme or parts.netloc:
        return None
    if not value.startswith("/") or value.startswith("//"):
        return None
    return value


@router.get("/me")
def me(request: Request, settings: Settings = Depends(get_settings)) -> dict[str, Any]:
    return _me_payload(request, settings)


@router.patch("/me")
def update_me(
    payload: MeUpdate,
    request: Request,
    settings: Settings = Depends(get_settings),
) -> dict[str, Any]:
    if not settings.auth_enabled:
        raise HTTPException(status_code=400, detail="Authentication is not configured")
    user = getattr(request.state, "user", None)
    if user is None:
        raise HTTPException(status_code=401, detail="Not authenticated")
    if payload.locale not in {None, "", *SUPPORTED_LOCALES}:
        raise HTTPException(status_code=400, detail="locale must be en, uk, ru, or empty")

    updated = set_user_locale(
        Database.from_settings(settings), user.id, payload.locale or None
    )
    return {
        "auth_enabled": True,
        "user": serialize_user(updated),
        "locale": updated.locale,
        "locale_effective": updated.effective_locale,
    }


@router.get("/auth/login")
def auth_login(
    return_to: str | None = Query(default=None),
    settings: Settings = Depends(get_settings),
    service: AuthService | None = Depends(get_auth_service),
) -> RedirectResponse:
    if service is None:
        raise HTTPException(status_code=400, detail="Authentication is not configured")
    url, state = service.build_login_url(return_to=_safe_return_to(return_to))
    response = RedirectResponse(url, status_code=303)
    response.set_cookie(
        key=settings.auth_state_cookie,
        value=state,
        max_age=settings.auth_state_ttl_seconds,
        httponly=True,
        secure=settings.auth_cookie_secure,
        samesite="lax",
        path="/",
    )
    return response


@router.get("/auth/callback")
def auth_callback(
    request: Request,
    code: str | None = Query(default=None),
    state: str | None = Query(default=None),
    error: str | None = Query(default=None),
    settings: Settings = Depends(get_settings),
    service: AuthService | None = Depends(get_auth_service),
) -> RedirectResponse:
    if service is None:
        raise HTTPException(status_code=400, detail="Authentication is not configured")
    if error:
        response = RedirectResponse("/?auth_error=access_denied", status_code=303)
        response.delete_cookie(settings.auth_state_cookie, path="/")
        return response
    if not code or not state:
        raise HTTPException(status_code=400, detail="Missing code or state")

    state_cookie = request.cookies.get(settings.auth_state_cookie)
    if not state_cookie or not hmac.compare_digest(state, state_cookie):
        raise HTTPException(status_code=400, detail="Invalid OAuth state")

    try:
        _, token, expires_at, return_to = service.exchange_code(
            code,
            state,
            user_agent=request.headers.get("user-agent"),
            ip_address=request.client.host if request.client else None,
        )
    except AuthError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=400, detail="Authentication failed") from exc

    response = RedirectResponse(_safe_return_to(return_to) or "/", status_code=303)
    response.delete_cookie(settings.auth_state_cookie, path="/")
    max_age = max(0, int((expires_at - datetime.now(UTC)).total_seconds()))
    response.set_cookie(
        key=settings.auth_session_cookie,
        value=token,
        max_age=max_age,
        httponly=True,
        secure=settings.auth_cookie_secure,
        samesite="lax",
        path="/",
    )
    return response


@router.post("/auth/logout")
def auth_logout(
    request: Request, settings: Settings = Depends(get_settings)
) -> JSONResponse:
    token = request.cookies.get(settings.auth_session_cookie)
    if token:
        revoke_session(Database.from_settings(settings), token)
    response = JSONResponse({"status": "ok"})
    response.delete_cookie(settings.auth_session_cookie, path="/")
    return response


@router.post("/webhooks/gnexus-auth")
@router.post("/webhooks/gnexus-auth/")
async def gnexus_auth_webhook(
    request: Request, settings: Settings = Depends(get_settings)
) -> dict[str, Any]:
    if not settings.auth_enabled or not settings.auth_webhook_secret:
        raise HTTPException(status_code=503, detail="Webhook endpoint is not configured")

    raw_bytes = await request.body()
    try:
        raw_body = raw_bytes.decode("utf-8")
    except UnicodeDecodeError as exc:
        raise HTTPException(status_code=400, detail="Invalid webhook payload") from exc

    service = AuthService(settings, Database.from_settings(settings))
    try:
        event = service.verify_and_parse_webhook(raw_body, dict(request.headers))
    except WebhookVerificationException as exc:
        raise HTTPException(status_code=401, detail="Invalid webhook signature") from exc
    except WebhookPayloadException as exc:
        raise HTTPException(status_code=400, detail="Invalid webhook payload") from exc

    processed = await run_in_threadpool(
        handle_webhook_event, Database.from_settings(settings), event
    )
    return {"status": "ok", "event_id": event.event_id, "duplicate": not processed}