Reafctor app

This commit is contained in:
Oliver Traber 2024-04-13 22:43:03 +02:00
parent b8216f6ade
commit 7740be8bb5
Signed by: Bluemedia
GPG key ID: C0674B105057136C
36 changed files with 389 additions and 208 deletions

34
app/security.py Normal file
View file

@ -0,0 +1,34 @@
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",
)