19 lines
659 B
Python
19 lines
659 B
Python
import hmac
|
||
|
||
from fastapi import HTTPException, Security
|
||
from fastapi.security import APIKeyHeader
|
||
|
||
from app.config.settings import settings
|
||
|
||
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
||
|
||
|
||
def verify_api_key(api_key: str | None = Security(api_key_header)) -> None:
|
||
"""Проверка общего секрета с бэкендом. Выключена, пока API_KEY не задан."""
|
||
if settings.API_KEY is None:
|
||
return
|
||
|
||
expected = settings.API_KEY.get_secret_value().encode()
|
||
if api_key is None or not hmac.compare_digest(api_key.encode(), expected):
|
||
raise HTTPException(status_code=401, detail="Invalid API key")
|