Resolves #15, addl unrelated changes

This commit is contained in:
2024-08-14 22:43:20 -04:00
parent 05e99718f8
commit ebc9460b8d
3 changed files with 110 additions and 7 deletions

30
util.py
View File

@ -2,13 +2,20 @@
import logging
from fastapi import Response
from fastapi import FastAPI, Response, HTTPException, Security
from fastapi.security import APIKeyHeader, APIKeyQuery
global api_key_query
global api_key_header
class Utilities:
def __init__(self):
def __init__(self, app: FastAPI, constants):
self.constants = constants
self.blocked_response_status = 422
self.blocked_response_content = None
pass
self.api_key_query = APIKeyQuery(name=constants.API_KEY_NAME, auto_error=False)
self.api_key_header = APIKeyHeader(name=f"x-{constants.API_KEY_NAME}", auto_error=False)
def get_blocked_response(self, path: str | None = None):
logging.error("Rejected request: Blocked")
@ -19,5 +26,22 @@ class Utilities:
logging.error("Rejected request: No such endpoint")
raise HTTPException(detail="Unknown endpoint", status_code=404)
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
print("Auth succeeded")
return True