pimco-charts/app/auth/middleware.py
Vadym Samoilenko 21d469bd82 Fix OAuth callback to use root path (match Azure AD registration)
Azure AD redirect URI is registered as /Pimco-charts (no /auth/callback),
so handle the code exchange in the index route and exempt root with ?code= in middleware.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 15:07:49 +00:00

32 lines
1.1 KiB
Python

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import RedirectResponse, Response
EXEMPT_PATHS = {"/auth/login", "/auth/logout"}
class AuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
path = request.url.path
# Strip root_path prefix for matching
root_path = request.scope.get("root_path", "")
if root_path and path.startswith(root_path):
path = path[len(root_path):]
if path in EXEMPT_PATHS:
return await call_next(request)
# OAuth callback arrives at "/" with ?code= query param
if path in ("/", "") and request.query_params.get("code"):
return await call_next(request)
if not request.session.get("user"):
if request.headers.get("HX-Request"):
return Response(
status_code=401,
headers={"HX-Redirect": "/auth/login"},
)
return RedirectResponse(url="/auth/login")
return await call_next(request)