meisaicheck-api / simple_auth.py
vumichien's picture
simple authen
460e51f
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