ai-hackaton-backend/app/core/mode_middleware.py
2026-01-15 20:41:24 +05:00

56 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from fastapi import Request
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from app.core.config import settings
class LandingModeMiddleware(BaseHTTPMiddleware):
"""
Middleware that restricts API access when app is in landing mode.
Only allows access to:
- /health
- /api/v1/contact
- /api/v1/config/mode
- / (root)
- /docs, /redoc, /openapi.json (API documentation)
"""
ALLOWED_PATHS = [
"/",
"/health",
"/docs",
"/redoc",
"/openapi.json",
]
ALLOWED_PREFIXES = [
"/api/v1/contact",
"/api/v1/config",
]
async def dispatch(self, request: Request, call_next):
# If not in landing mode, allow all requests
if settings.app_mode != "landing":
return await call_next(request)
path = request.url.path
# Check if path is in allowed list
if path in self.ALLOWED_PATHS:
return await call_next(request)
# Check if path starts with allowed prefix
for prefix in self.ALLOWED_PREFIXES:
if path.startswith(prefix):
return await call_next(request)
# Block all other API requests in landing mode
return JSONResponse(
status_code=403,
content={
"detail": "API недоступен в режиме лендинга. Свяжитесь с нами через форму обратной связи.",
"mode": "landing",
},
)