from fastapi import HTTPException, status, Depends, Request from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from config import settings import logging logger = logging.getLogger(__name__) security = HTTPBearer(auto_error=False) def verify_token(request: Request, credentials: HTTPAuthorizationCredentials = Depends(security)): """Verify the provided token matches the configured secret token, or allow no token for plugin compatibility""" token = None # Try Bearer token first if credentials: token = credentials.credentials logger.info(f"Bearer token received: {token[:10]}...") else: # Try query parameter token = request.query_params.get("token") if token: logger.info(f"Query token received: {token[:10]}...") else: # Try header without Bearer prefix auth_header = request.headers.get("authorization") if auth_header and not auth_header.startswith("Bearer "): token = auth_header logger.info(f"Direct auth header received: {token[:10]}...") # If no token provided, allow access (authentication is optional) if not token: logger.info("No token provided - allowing access") return None # If token provided, verify it if token != settings.SECRET_TOKEN: logger.warning(f"Invalid token provided: {token[:10]}...") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication token", headers={"WWW-Authenticate": "Bearer"}, ) logger.info("Token verification successful") return token