Refactor test cases and base code for consistency and readability

- Updated byte representations in tests to use lowercase hex format for consistency.
- Reformatted code for better readability, including line breaks and indentation adjustments.
- Consolidated multiple lines into single lines where appropriate to enhance clarity.
- Ensured that all test cases maintain consistent formatting and style across the test suite.
This commit is contained in:
Lloyd
2026-05-27 20:15:10 +01:00
parent faa3296a50
commit 45a44eb47b
83 changed files with 2790 additions and 2138 deletions
+6 -6
View File
@@ -22,22 +22,22 @@ class APITokenManager:
def create_token(self, name: str) -> tuple[int, str]:
plaintext_token = self.generate_api_token()
token_hash = self.hash_token(plaintext_token)
token_id = self.db.create_api_token(name, token_hash)
logger.info(f"Created API token '{name}' with ID {token_id}")
return token_id, plaintext_token
def verify_token(self, token: str) -> Optional[Dict]:
token_hash = self.hash_token(token)
return self.db.verify_api_token(token_hash)
def revoke_token(self, token_id: int) -> bool:
deleted = self.db.revoke_api_token(token_id)
if deleted:
logger.info(f"Revoked API token ID {token_id}")
return deleted
def list_tokens(self) -> List[Dict]:
+13 -12
View File
@@ -8,7 +8,7 @@ logger = logging.getLogger("HTTPServer")
def check_auth():
"""
CherryPy tool to check authentication before processing request.
Checks for either JWT in Authorization header, API token in X-API-Key header,
or JWT token in query parameter (for EventSource/SSE connections).
Sets cherrypy.request.user on success.
@@ -17,26 +17,26 @@ def check_auth():
# Skip auth check for OPTIONS requests (CORS preflight)
if cherrypy.request.method == "OPTIONS":
return
# Skip auth check for /auth/login endpoint
if cherrypy.request.path_info == "/auth/login":
return
# Get auth handlers from config
jwt_handler = cherrypy.config.get("jwt_handler")
token_manager = cherrypy.config.get("token_manager")
if not jwt_handler or not token_manager:
logger.error("Auth handlers not initialized in cherrypy.config")
cherrypy.response.status = 500
return {"success": False, "error": "Authentication system not configured"}
# Check for JWT token in Authorization header first
auth_header = cherrypy.request.headers.get("Authorization", "")
if auth_header.startswith("Bearer "):
token = auth_header[7:] # Remove "Bearer " prefix
payload = jwt_handler.verify_jwt(token)
if payload:
cherrypy.request.user = {
"username": payload.get("sub"),
@@ -50,7 +50,7 @@ def check_auth():
query_token = cherrypy.request.params.get("token")
if query_token:
payload = jwt_handler.verify_jwt(query_token)
if payload:
cherrypy.request.user = {
"username": payload.get("sub"),
@@ -60,12 +60,12 @@ def check_auth():
# Remove token from params to avoid exposing it in logs
del cherrypy.request.params["token"]
return
# Check for API token in X-API-Key header
api_key = cherrypy.request.headers.get("X-API-Key", "")
if api_key:
token_info = token_manager.verify_token(api_key)
if token_info:
cherrypy.request.user = {
"token_id": token_info["id"],
@@ -79,6 +79,7 @@ def check_auth():
raise cherrypy.HTTPError(401, "Unauthorized - Valid JWT or API token required")
# Register the tool
cherrypy.tools.require_auth = cherrypy.Tool("before_handler", check_auth)
logger.info("CherryPy require_auth tool registered")
def register_require_auth_tool():
if not hasattr(cherrypy.tools, "require_auth"):
cherrypy.tools.require_auth = cherrypy.Tool("before_handler", check_auth)
logger.info("CherryPy require_auth tool registered")
+1 -1
View File
@@ -11,7 +11,7 @@ class JWTHandler:
def __init__(self, secret: str, expiry_minutes: int = 15):
self.secret = secret
self.expiry_minutes = expiry_minutes
def create_jwt(self, username: str, client_id: str) -> str:
now = int(time.time())