Spaces:
Running
Running
File size: 1,325 Bytes
a056d23 | 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 | from fastapi import HTTPException, Request
from config import PROVIDER_KEYS
from proxy.providers import PROVIDERS, Provider
def _match_provider(token: str) -> tuple[str, str] | None:
"""Return (provider_name, configured_proxy_key) if token matches a known provider key."""
for name, configured_key in PROVIDER_KEYS.items():
if configured_key and token == configured_key:
return name, configured_key
return None
def resolve_provider(request: Request) -> Provider:
auth = request.headers.get("Authorization", "")
parts = auth.split(" ", 1)
if len(parts) != 2 or parts[0].lower() != "bearer":
raise HTTPException(status_code=401, detail="Missing or invalid Authorization header. Expected 'Bearer sk-{provider}-...'")
token = parts[1]
match = _match_provider(token)
if match is None:
raise HTTPException(status_code=401, detail="Unknown proxy key")
provider_name, _ = match
return PROVIDERS[provider_name]
def get_real_key(provider: Provider) -> str:
import os
key = os.getenv(provider.env_real_key, "")
if not key:
raise HTTPException(
status_code=500,
detail=f"Provider '{provider.name}' is configured in .env but its real API key ({provider.env_real_key}) is missing"
)
return key
|