health-apps-cms/middleware/auth_secret.py

29 lines
1023 B
Python

"""
Authentication middleware and dependency for agent (bot) requests.
Validates the presence and correctness of the X-Agent-Secret header.
"""
import os
from fastapi import HTTPException, status, Header
from typing import Optional
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Get the secret key from environment variables
AGENT_SECRET_KEY = os.getenv("AGENT_SECRET_KEY")
if not AGENT_SECRET_KEY:
raise ValueError("AGENT_SECRET_KEY environment variable not set")
async def verify_secret(x_agent_secret: Optional[str] = Header(None, alias="X-Agent-Secret")):
"""
Dependency function to verify the X-Agent-Secret header.
Can be used with Depends() in FastAPI route dependencies.
"""
if not x_agent_secret or x_agent_secret != AGENT_SECRET_KEY:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or missing X-Agent-Secret header",
headers={"WWW-Authenticate": "Bearer"},
)
return True