ifixkart-backend/app/core/middleware/kill_switch_middleware.py

60 lines
2.3 KiB
Python

import time
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
from sqlalchemy.orm import Session
from app.core.database.db_session import SessionLocal
from app.models.SettingModel import Setting
from jose import jwt, JWTError
from app.core.config.Config import settings, load_public_key_bytes
MASTER_ADMIN_EMAIL = "adithiyan.elan@gmail.com"
_cached_global_disable = False
_last_check_time = 0.0
_CACHE_TTL_SECONDS = 5.0
class KillSwitchMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# Allow docs and OpenAPI schemas to always bypass
if request.url.path in ["/docs", "/redoc", "/openapi.json"]:
return await call_next(request)
global _cached_global_disable, _last_check_time
now = time.time()
# Refresh cached setting every 5 seconds to eliminate per-request DB round-trips
if (now - _last_check_time) > _CACHE_TTL_SECONDS:
db: Session = SessionLocal()
try:
item = db.query(Setting).filter(Setting.setting_key == "GLOBAL_DISABLE").first()
if item and isinstance(item.setting_value, dict):
_cached_global_disable = bool(item.setting_value.get("enabled", False))
else:
_cached_global_disable = False
_last_check_time = now
except Exception:
pass
finally:
db.close()
if not _cached_global_disable:
return await call_next(request)
# Bypass check for MASTER ADMIN
auth_header = request.headers.get("Authorization")
if auth_header and auth_header.startswith("Bearer "):
token = auth_header.split(" ")[1]
try:
public_key = load_public_key_bytes()
payload = jwt.decode(token, public_key, algorithms=[settings.ALGORITHM])
email = payload.get("email")
if email == MASTER_ADMIN_EMAIL:
# Let master bypass the lock
return await call_next(request)
except JWTError:
pass
return JSONResponse(
status_code=403,
content={"detail": "SYSTEM DISABLED BY EMERGENCY KILL SWITCH"}
)