Refactor auth middleware and update service config usage
- Remove redundant comments and docstrings in auth_middleware.py - Use TOKEN_SERVICE_URL env variable for AuthMiddleware - Fix sensor service proxy path in main.py - Use datetime.now() for request_stats start_time
This commit is contained in:
@@ -10,8 +10,6 @@ import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class AuthMiddleware:
|
||||
"""Authentication middleware for validating tokens"""
|
||||
|
||||
def __init__(self, token_service_url: str = "http://localhost:8001"):
|
||||
self.token_service_url = token_service_url
|
||||
logger.info(f"Initialized AuthMiddleware with token service URL: {self.token_service_url}")
|
||||
@@ -21,7 +19,6 @@ class AuthMiddleware:
|
||||
Verify authentication token from request headers
|
||||
Returns token payload if valid, raises HTTPException if invalid
|
||||
"""
|
||||
# Extract token from Authorization header
|
||||
auth_header = request.headers.get("Authorization")
|
||||
if not auth_header:
|
||||
raise HTTPException(status_code=401, detail="Authorization header required")
|
||||
@@ -29,17 +26,15 @@ class AuthMiddleware:
|
||||
if not auth_header.startswith("Bearer "):
|
||||
raise HTTPException(status_code=401, detail="Bearer token required")
|
||||
|
||||
token = auth_header[7:] # Remove "Bearer " prefix
|
||||
token = auth_header.split(" ")[1].strip() # Remove "Bearer " prefix
|
||||
|
||||
try:
|
||||
# Validate token with token service
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
f"{self.token_service_url}/tokens/validate",
|
||||
json={"token": token},
|
||||
json={'token': token},
|
||||
timeout=aiohttp.ClientTimeout(total=5)
|
||||
) as response:
|
||||
|
||||
if response.status != 200:
|
||||
raise HTTPException(status_code=401, detail="Token validation failed")
|
||||
|
||||
@@ -49,7 +44,6 @@ class AuthMiddleware:
|
||||
error_msg = token_data.get("error", "Invalid token")
|
||||
raise HTTPException(status_code=401, detail=error_msg)
|
||||
|
||||
# Token is valid, return decoded payload
|
||||
return token_data.get("decoded")
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
@@ -68,10 +62,8 @@ class AuthMiddleware:
|
||||
if not token_payload:
|
||||
return False
|
||||
|
||||
# Get list of resources the token has access to
|
||||
token_resources = token_payload.get("list_of_resources", [])
|
||||
|
||||
# Check if token has access to all required resources
|
||||
for resource in required_resources:
|
||||
if resource not in token_resources:
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user