2026-03-31 04:31:47 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from fastapi import Request
|
|
|
|
|
from fastapi.responses import JSONResponse
|
2026-04-03 15:00:08 +00:00
|
|
|
from sqlmodel import Session
|
2026-03-31 04:31:47 +00:00
|
|
|
from starlette.middleware.base import BaseHTTPMiddleware
|
|
|
|
|
|
2026-04-03 15:00:08 +00:00
|
|
|
from bootstrap.auth_access import RouteAccessMode, extract_bot_id, resolve_route_access_mode
|
|
|
|
|
from core.database import engine
|
|
|
|
|
from services.platform_auth_service import (
|
|
|
|
|
resolve_bot_request_auth,
|
|
|
|
|
resolve_panel_request_auth,
|
|
|
|
|
)
|
2026-03-31 04:31:47 +00:00
|
|
|
|
|
|
|
|
|
2026-04-03 15:00:08 +00:00
|
|
|
def _unauthorized(detail: str) -> JSONResponse:
|
|
|
|
|
return JSONResponse(status_code=401, content={"detail": detail})
|
2026-03-31 04:31:47 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class PasswordProtectionMiddleware(BaseHTTPMiddleware):
|
|
|
|
|
async def dispatch(self, request: Request, call_next):
|
2026-04-03 15:00:08 +00:00
|
|
|
if request.method.upper() == "OPTIONS":
|
2026-03-31 04:31:47 +00:00
|
|
|
return await call_next(request)
|
|
|
|
|
|
2026-04-03 15:00:08 +00:00
|
|
|
path = request.url.path
|
|
|
|
|
access_mode = resolve_route_access_mode(path, request.method)
|
|
|
|
|
if access_mode == RouteAccessMode.PUBLIC:
|
2026-03-31 04:31:47 +00:00
|
|
|
return await call_next(request)
|
|
|
|
|
|
2026-04-03 15:00:08 +00:00
|
|
|
bot_id = extract_bot_id(path)
|
|
|
|
|
with Session(engine) as session:
|
|
|
|
|
panel_principal = resolve_panel_request_auth(session, request)
|
|
|
|
|
if panel_principal.authenticated:
|
|
|
|
|
request.state.auth_principal = panel_principal
|
|
|
|
|
return await call_next(request)
|
|
|
|
|
|
|
|
|
|
if access_mode == RouteAccessMode.PANEL_ONLY:
|
|
|
|
|
return _unauthorized("Panel authentication required")
|
|
|
|
|
|
|
|
|
|
if not bot_id:
|
|
|
|
|
return _unauthorized("Bot authentication required")
|
|
|
|
|
|
|
|
|
|
bot_principal = resolve_bot_request_auth(session, request, bot_id)
|
|
|
|
|
if bot_principal.authenticated:
|
|
|
|
|
request.state.auth_principal = bot_principal
|
|
|
|
|
return await call_next(request)
|
2026-03-31 04:31:47 +00:00
|
|
|
|
2026-04-03 15:00:08 +00:00
|
|
|
if access_mode == RouteAccessMode.PUBLIC_BOT_OR_PANEL:
|
|
|
|
|
return _unauthorized("Bot or panel authentication required to access this resource")
|
|
|
|
|
return _unauthorized("Bot or panel authentication required")
|