api/util.py

56 lines
1.6 KiB
Python
Raw Normal View History

2024-08-10 22:49:00 -04:00
#!/usr/bin/env python3.12
import logging
2025-02-15 21:09:33 -05:00
from typing import Optional
2025-01-11 20:59:10 -05:00
from fastapi import FastAPI, Response, HTTPException
from fastapi.responses import RedirectResponse
2024-08-14 22:43:20 -04:00
2024-08-10 22:49:00 -04:00
class Utilities:
2025-02-15 21:09:33 -05:00
"""
API Utilities
"""
2025-01-11 20:59:10 -05:00
def __init__(self, app: FastAPI, constants):
2024-08-14 22:43:20 -04:00
self.constants = constants
self.blocked_redirect_uri = "https://codey.lol"
2025-01-11 20:59:10 -05:00
self.app = app
2024-08-10 22:49:00 -04:00
2025-02-15 21:09:33 -05:00
def get_blocked_response(self, path: Optional[str] = None):
"""
Get Blocked HTTP Response
"""
2024-08-10 22:49:00 -04:00
logging.error("Rejected request: Blocked")
return RedirectResponse(url=self.blocked_redirect_uri)
2024-08-10 22:49:00 -04:00
2025-02-15 21:09:33 -05:00
def get_no_endpoint_found(self, path: Optional[str] = None):
"""
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)
2025-02-15 21:09:33 -05:00
def check_key(self, path: str, key: str,
req_type: int = 0) -> bool:
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.
"""
if not key or not key.startswith("Bearer "):
return False
2025-02-15 21:09:33 -05:00
_key: str = key.split("Bearer ", maxsplit=1)[1].strip()
2024-08-14 22:43:20 -04:00
2025-02-15 21:09:33 -05:00
if not _key in self.constants.API_KEYS:
2024-08-19 11:42:23 -04:00
return False
2024-08-27 20:47:29 -04:00
if req_type == 2:
2025-02-15 21:09:33 -05:00
return _key.startswith("PRV-")
elif req_type == 4:
2025-02-15 21:09:33 -05:00
return _key.startswith("RAD-")
2024-08-27 20:47:29 -04:00
2025-02-15 21:09:33 -05:00
if path.lower().startswith("/xc/")\
and not key.startswith("XC-"):
return False
2025-02-10 20:29:57 -05:00
return True