api/util.py

55 lines
1.8 KiB
Python
Raw Normal View History

2024-08-10 22:49:00 -04:00
#!/usr/bin/env python3.12
import logging
2025-01-11 20:59:10 -05:00
from fastapi import FastAPI, Response, HTTPException
2024-08-14 22:43:20 -04:00
2024-08-10 22:49:00 -04:00
class Utilities:
2025-01-11 20:59:10 -05:00
"""API Utilities"""
def __init__(self, app: FastAPI, constants):
2024-08-14 22:43:20 -04:00
self.constants = constants
2024-08-10 22:49:00 -04:00
self.blocked_response_status = 422
self.blocked_response_content = None
2025-01-11 20:59:10 -05:00
self.app = app
2024-08-10 22:49:00 -04:00
2025-01-11 20:59:10 -05:00
def get_blocked_response(self, path: str | None = None): # pylint: disable=unused-argument
"""Get Blocked HTTP Response"""
2024-08-10 22:49:00 -04:00
logging.error("Rejected request: Blocked")
return Response(content=self.blocked_response_content,
status_code=self.blocked_response_status)
2025-01-11 20:59:10 -05:00
def get_no_endpoint_found(self, path: str | None = None): # pylint: disable=unused-argument
"""Get 404 Response"""
2024-08-10 22:49:00 -04:00
logging.error("Rejected request: No such endpoint")
raise HTTPException(detail="Unknown endpoint", status_code=404)
2024-08-27 20:47:29 -04:00
def check_key(self, path: str, key: str, req_type: int = 0):
2024-08-14 22:43:20 -04:00
"""
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}")
2024-08-14 22:43:20 -04:00
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")
2024-08-19 11:42:23 -04:00
return False
2024-08-27 20:47:29 -04:00
if req_type == 2:
if not key.startswith("PRV-"):
# print("Auth failed - not a PRV key")
2024-08-27 20:47:29 -04:00
return False
else:
return True
if path.lower().startswith("/xc/") and not key.startswith("XC-"):
# print("Auth failed - not an XC Key")
2024-08-14 22:43:20 -04:00
return False
2024-08-10 22:49:00 -04:00
# print("Auth succeeded")
2025-01-11 20:59:10 -05:00
return True