File size: 1,055 Bytes
460e51f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import Security, HTTPException, status, Depends
from fastapi.security.api_key import APIKeyHeader
from config import API_KEY, API_KEY_NAME
from typing import Optional

# Define the API key header
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)


async def get_api_key(api_key_header: str = Security(api_key_header)) -> str:
    """
    Validate API key from header
    """
    if api_key_header == API_KEY:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid API Key",
    )


# Simple function to get a dummy user for API key auth
async def get_current_user_from_api_key(api_key: str = Depends(get_api_key)):
    """
    Return a dummy user for API key authentication
    """
    # This provides a compatible interface with the JWT auth
    return SimpleUser(username="api_user", disabled=False)


class SimpleUser:
    def __init__(self, username: str, disabled: bool = False):
        self.username = username
        self.disabled = disabled