Initial commit
This commit is contained in:
53
app/auth.py
Normal file
53
app/auth.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import httpx
|
||||
import os
|
||||
import logging
|
||||
from fastapi import HTTPException, Header
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LITELLM_URL = os.getenv("LITELLM_PROXY_URL", "http://litellm:4000")
|
||||
MASTER_KEY = os.getenv("LITELLM_MASTER_KEY")
|
||||
|
||||
async def verify_api_key(authorization: str = Header(...)) -> dict:
|
||||
token = authorization.removeprefix("Bearer ")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
# Master Key nutzen um Key-Info abzufragen
|
||||
resp = await client.get(
|
||||
f"{LITELLM_URL}/key/info",
|
||||
headers={
|
||||
"Authorization": f"Bearer {MASTER_KEY}"
|
||||
},
|
||||
params={"key": token},
|
||||
timeout=5.0
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
logger.error(f"LiteLLM nicht erreichbar: {e}")
|
||||
raise HTTPException(503, f"Auth service unavailable: {e}")
|
||||
|
||||
logger.debug(f"LiteLLM Status: {resp.status_code}")
|
||||
logger.debug(f"LiteLLM Response: {resp.text}")
|
||||
|
||||
if resp.status_code == 404:
|
||||
raise HTTPException(401, "Invalid API Key")
|
||||
if resp.status_code == 401:
|
||||
raise HTTPException(401, "Invalid API Key")
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(502, f"Auth service error: {resp.status_code}")
|
||||
|
||||
data = resp.json()
|
||||
|
||||
user_id = (
|
||||
data.get("info", {}).get("user_id") or
|
||||
data.get("user_id")
|
||||
)
|
||||
|
||||
if not user_id:
|
||||
raise HTTPException(400, "API Key hat keine user_id")
|
||||
|
||||
return {
|
||||
"user_id": user_id,
|
||||
"token": token,
|
||||
"key_alias": data.get("info", {}).get("key_alias"),
|
||||
}
|
||||
Reference in New Issue
Block a user