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:
rafaeldpsilva
2025-10-08 14:04:50 +01:00
parent 863e0161b0
commit 8ff20935fc
2 changed files with 10 additions and 20 deletions

View File

@@ -10,8 +10,6 @@ import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class AuthMiddleware: class AuthMiddleware:
"""Authentication middleware for validating tokens"""
def __init__(self, token_service_url: str = "http://localhost:8001"): def __init__(self, token_service_url: str = "http://localhost:8001"):
self.token_service_url = token_service_url self.token_service_url = token_service_url
logger.info(f"Initialized AuthMiddleware with token service URL: {self.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 Verify authentication token from request headers
Returns token payload if valid, raises HTTPException if invalid Returns token payload if valid, raises HTTPException if invalid
""" """
# Extract token from Authorization header
auth_header = request.headers.get("Authorization") auth_header = request.headers.get("Authorization")
if not auth_header: if not auth_header:
raise HTTPException(status_code=401, detail="Authorization header required") raise HTTPException(status_code=401, detail="Authorization header required")
@@ -29,17 +26,15 @@ class AuthMiddleware:
if not auth_header.startswith("Bearer "): if not auth_header.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Bearer token required") 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: try:
# Validate token with token service
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.post( async with session.post(
f"{self.token_service_url}/tokens/validate", f"{self.token_service_url}/tokens/validate",
json={"token": token}, json={'token': token},
timeout=aiohttp.ClientTimeout(total=5) timeout=aiohttp.ClientTimeout(total=5)
) as response: ) as response:
if response.status != 200: if response.status != 200:
raise HTTPException(status_code=401, detail="Token validation failed") raise HTTPException(status_code=401, detail="Token validation failed")
@@ -49,7 +44,6 @@ class AuthMiddleware:
error_msg = token_data.get("error", "Invalid token") error_msg = token_data.get("error", "Invalid token")
raise HTTPException(status_code=401, detail=error_msg) raise HTTPException(status_code=401, detail=error_msg)
# Token is valid, return decoded payload
return token_data.get("decoded") return token_data.get("decoded")
except aiohttp.ClientError as e: except aiohttp.ClientError as e:
@@ -68,10 +62,8 @@ class AuthMiddleware:
if not token_payload: if not token_payload:
return False return False
# Get list of resources the token has access to
token_resources = token_payload.get("list_of_resources", []) token_resources = token_payload.get("list_of_resources", [])
# Check if token has access to all required resources
for resource in required_resources: for resource in required_resources:
if resource not in token_resources: if resource not in token_resources:
return False return False

View File

@@ -58,12 +58,7 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
# Service registry and load balancer
service_registry = ServiceRegistry()
load_balancer = LoadBalancer(service_registry)
auth_middleware = AuthMiddleware()
# Service configuration
SERVICES = { SERVICES = {
"token-service": ServiceConfig( "token-service": ServiceConfig(
name="token-service", name="token-service",
@@ -85,20 +80,23 @@ SERVICES = {
) )
} }
# Request statistics # Service registry and load balancer
service_registry = ServiceRegistry()
load_balancer = LoadBalancer(service_registry)
auth_middleware = AuthMiddleware(os.getenv("TOKEN_SERVICE_URL", "http://token-service:8001"))
request_stats = { request_stats = {
"total_requests": 0, "total_requests": 0,
"successful_requests": 0, "successful_requests": 0,
"failed_requests": 0, "failed_requests": 0,
"service_requests": {service: 0 for service in SERVICES.keys()}, "service_requests": {service: 0 for service in SERVICES.keys()},
"start_time": datetime.utcnow() "start_time": datetime.now()
} }
@app.get("/health", response_model=HealthResponse) @app.get("/health", response_model=HealthResponse)
async def gateway_health_check(): async def gateway_health_check():
"""Gateway health check endpoint""" """Gateway health check endpoint"""
try: try:
# Check all services
service_health = await service_registry.get_all_service_health() service_health = await service_registry.get_all_service_health()
healthy_services = sum(1 for status in service_health.values() if status.get("status") == "healthy") healthy_services = sum(1 for status in service_health.values() if status.get("status") == "healthy")
@@ -189,7 +187,7 @@ async def iot_control_service_proxy(request: Request, path: str):
@app.api_route("/api/v1/sensors/{path:path}", methods=["GET", "POST", "PUT", "DELETE"]) @app.api_route("/api/v1/sensors/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def sensor_service_proxy(request: Request, path: str): async def sensor_service_proxy(request: Request, path: str):
"""Proxy requests to sensor service""" """Proxy requests to sensor service"""
return await proxy_request(request, "sensor-service", f"/{path}") return await proxy_request(request, "sensor-service", f"/sensors/{path}")
# Data Ingestion Service Routes (SA4CPS FTP Monitoring) # Data Ingestion Service Routes (SA4CPS FTP Monitoring)
@app.api_route("/api/v1/ingestion/{path:path}", methods=["GET", "POST", "PUT", "DELETE"]) @app.api_route("/api/v1/ingestion/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
@@ -290,7 +288,7 @@ async def proxy_request(request: Request, service_name: str, path: str):
# Check authentication if required # Check authentication if required
if service_config.auth_required: if service_config.auth_required:
await auth_middleware.verify_token(request) decoded = await auth_middleware.verify_token(request)
# Get healthy service instance # Get healthy service instance
service_url = await load_balancer.get_service_url(service_name) service_url = await load_balancer.get_service_url(service_name)