forked from sagnik/Project_Velocity
50 lines
1.2 KiB
Python
50 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
from typing import Mapping
|
|
|
|
|
|
_SUPPORTED_ENV_KEYS = (
|
|
"DREAM_WEAVER_GATEWAY_API_KEY",
|
|
"DREAM_WEAVER_API_KEY",
|
|
)
|
|
|
|
|
|
def load_gateway_api_key(env: Mapping[str, str] | None = None) -> str | None:
|
|
values = env if env is not None else os.environ
|
|
for key in _SUPPORTED_ENV_KEYS:
|
|
raw = values.get(key)
|
|
if raw is None:
|
|
continue
|
|
trimmed = raw.strip()
|
|
if trimmed:
|
|
return trimmed
|
|
return None
|
|
|
|
|
|
def extract_gateway_api_key(headers: Mapping[str, str]) -> str | None:
|
|
for header_name in ("x-dream-weaver-api-key", "x-api-key"):
|
|
value = headers.get(header_name)
|
|
if value:
|
|
trimmed = value.strip()
|
|
if trimmed:
|
|
return trimmed
|
|
|
|
authorization = headers.get("authorization", "")
|
|
if authorization.lower().startswith("bearer "):
|
|
token = authorization[7:].strip()
|
|
if token:
|
|
return token
|
|
|
|
return None
|
|
|
|
|
|
def is_gateway_request_authorized(
|
|
headers: Mapping[str, str],
|
|
required_api_key: str | None,
|
|
) -> bool:
|
|
if required_api_key is None:
|
|
return True
|
|
presented = extract_gateway_api_key(headers)
|
|
return presented == required_api_key
|