File size: 644 Bytes
936f0bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from __future__ import annotations

import secrets

from fastapi import Security
from fastapi.security import APIKeyHeader

from app.core.config import settings
from app.core.exceptions import AuthenticationError

_api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)


async def require_api_key(api_key: str | None = Security(_api_key_header)) -> str:
    if not settings.API_KEY:
        return api_key or ""
    if not api_key:
        raise AuthenticationError("X-API-Key header is required")
    if not secrets.compare_digest(api_key, settings.API_KEY):
        raise AuthenticationError("Invalid API key")
    return api_key