simple-ocpp-cs/app/security.py

34 lines
979 B
Python
Raw Normal View History

2024-03-28 21:23:25 +01:00
import os
from fastapi import HTTPException, Security, status
from fastapi.security import APIKeyHeader, HTTPBasic
basic_auth = HTTPBasic()
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def get_api_key(
api_key_header: str = Security(api_key_header),
) -> str:
"""Retrieve and validate an API key from the HTTP header.
Args:
api_key_header: The API key passed in the HTTP header.
Returns:
The validated API key.
Raises:
HTTPException: If the API key is invalid or missing.
"""
api_key = os.getenv("CS_API_KEY", "default")
if api_key == "default":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="API key not set. Authentication not possible.",
)
if api_key_header == api_key:
return api_key_header
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or missing API Key",
)