api/util.py

42 lines
1.2 KiB
Python
Raw Normal View History

2024-08-10 22:49:00 -04:00
#!/usr/bin/env python3.12
import logging
2024-08-14 22:43:20 -04:00
from fastapi import FastAPI, Response, HTTPException, Security
2024-08-10 22:49:00 -04:00
class Utilities:
2024-08-14 22:43:20 -04:00
def __init__(self, app: FastAPI, constants):
self.constants = constants
2024-08-10 22:49:00 -04:00
self.blocked_response_status = 422
self.blocked_response_content = None
def get_blocked_response(self, path: str | None = None):
logging.error("Rejected request: Blocked")
return Response(content=self.blocked_response_content,
status_code=self.blocked_response_status)
def get_no_endpoint_found(self, path: str | None = None):
logging.error("Rejected request: No such endpoint")
raise HTTPException(detail="Unknown endpoint", status_code=404)
2024-08-14 22:43:20 -04:00
def check_key(self, path: str, key: str):
"""
Accepts path as an argument to allow fine tuning access for each API key, not currently in use.
"""
print(f"Testing with path: {path}, key: {key}")
if not key or not key.startswith("Bearer "):
return False
key = key.split("Bearer ", maxsplit=1)[1].strip()
if not key in self.constants.API_KEYS:
print("Auth failed.")
return False
2024-08-10 22:49:00 -04:00
2024-08-14 22:43:20 -04:00
print("Auth succeeded")
return True
2024-08-10 22:49:00 -04:00