35 lines
1.0 KiB
Python
35 lines
1.0 KiB
Python
from __future__ import annotations
|
|
|
|
from fastapi import HTTPException, Request, status
|
|
|
|
|
|
def require_bearer(request: Request, api_keys: list[str]) -> None:
|
|
if not api_keys:
|
|
return
|
|
|
|
auth = request.headers.get("authorization", "")
|
|
if not auth.startswith("Bearer "):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail={
|
|
"error": {
|
|
"message": "Missing or invalid Authorization header",
|
|
"type": "invalid_request_error",
|
|
"code": "invalid_api_key",
|
|
}
|
|
},
|
|
)
|
|
|
|
token = auth[len("Bearer ") :].strip()
|
|
if token not in api_keys:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail={
|
|
"error": {
|
|
"message": "Invalid API key",
|
|
"type": "invalid_request_error",
|
|
"code": "invalid_api_key",
|
|
}
|
|
},
|
|
)
|