File size: 1,184 Bytes
c6c8587
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""
Simple API Key Authentication for Private Deployment
"""

import os
from fastapi import HTTPException, Security, status
from fastapi.security import APIKeyHeader
from typing import Optional

# Get API key from environment variable
API_KEY = os.getenv("API_KEY", None)

# Create API key header scheme
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)

async def verify_api_key(api_key: Optional[str] = Security(api_key_header)) -> bool:
    """
    Verify API key if one is configured
    
    If no API_KEY is set in environment, allows all requests (public mode)
    If API_KEY is set, requires matching key in X-API-Key header
    """
    # If no API key is configured, allow all requests (public mode)
    if not API_KEY:
        return True
    
    # If API key is configured but not provided in request
    if not api_key:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="API Key required"
        )
    
    # Verify the API key
    if api_key != API_KEY:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid API Key"
        )
    
    return True