Add improvements

This commit is contained in:
Urtzi Alfaro
2026-01-12 14:24:14 +01:00
parent 6037faaf8c
commit 230bbe6a19
61 changed files with 1668 additions and 894 deletions

View File

@@ -27,41 +27,36 @@ class ServiceAuthenticator:
self.jwt_handler = JWTHandler(config.JWT_SECRET_KEY)
self._cached_token = None
self._token_expires_at = 0
self._cached_tenant_id = None # Track tenant context for cached tokens
async def get_service_token(self) -> str:
async def get_service_token(self, tenant_id: Optional[str] = None) -> str:
"""Get a valid service token, using cache when possible"""
current_time = int(time.time())
# Return cached token if still valid (with 5 min buffer)
# Return cached token if still valid (with 5 min buffer) and tenant context matches
if (self._cached_token and
self._token_expires_at > current_time + 300):
self._token_expires_at > current_time + 300 and
(tenant_id is None or self._cached_tenant_id == tenant_id)):
return self._cached_token
# Create new service token
token_expires_at = current_time + 3600 # 1 hour
service_payload = {
"sub": f"{self.service_name}-service",
"user_id": f"{self.service_name}-service",
"email": f"{self.service_name}-service@internal",
"type": "service",
"role": "admin",
"exp": token_expires_at,
"iat": current_time,
"iss": f"{self.service_name}-service",
"service": self.service_name,
"full_name": f"{self.service_name.title()} Service",
"is_verified": True,
"is_active": True,
"tenant_id": None
}
# Create new service token using unified JWT handler
try:
token = self.jwt_handler.create_access_token_from_payload(service_payload)
token = self.jwt_handler.create_service_token(
service_name=self.service_name,
tenant_id=tenant_id
)
# Extract expiration from token for caching
import json
from jose import jwt
payload = jwt.decode(token, self.jwt_handler.secret_key, algorithms=[self.jwt_handler.algorithm], options={"verify_signature": False})
token_expires_at = payload.get("exp", current_time + 3600)
self._cached_token = token
self._token_expires_at = token_expires_at
self._cached_tenant_id = tenant_id # Store tenant context for caching
logger.debug("Created new service token", service=self.service_name, expires_at=token_expires_at)
logger.debug("Created new service token", service=self.service_name, expires_at=token_expires_at, tenant_id=tenant_id)
return token
except Exception as e:
@@ -181,8 +176,8 @@ class BaseServiceClient(ABC):
Called by _make_request through circuit breaker.
"""
try:
# Get service token
token = await self.authenticator.get_service_token()
# Get service token with tenant context for tenant-scoped requests
token = await self.authenticator.get_service_token(tenant_id)
# Build headers
request_headers = self.authenticator.get_request_headers(tenant_id)