File size: 873 Bytes
358dd8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import HTTPException, Security
from fastapi.security.api_key import APIKeyHeader

from .settings import settings

api_key_header = APIKeyHeader(name="Authorization", auto_error=False)

# TODO: Implement key in db once ready
# async def seed_key():
#     if db.connected:
#     existing = await db.client.api_key.find_first()
#     if not existing:
#         await db.client.api_key.create(data={"key": API_KEY})


async def require_key(auth: str = Security(api_key_header)) -> str | None:
    if settings.api_key is None:
        return None

    if not auth:
        raise HTTPException(401, "Missing API key")

    token = auth.removeprefix("Bearer ").strip()
    # found = await db.client.api_key.find_unique(where={"key": token})
    if not token == settings.api_key:
        raise HTTPException(status_code=401, detail="Invalid API key")
    return token