REFACTOR ALL APIs

This commit is contained in:
Urtzi Alfaro
2025-10-06 15:27:01 +02:00
parent dc8221bd2f
commit 38fb98bc27
166 changed files with 18454 additions and 13605 deletions

View File

@@ -108,6 +108,11 @@ class AuthMiddleware(BaseHTTPMiddleware):
content={"detail": f"Access denied to tenant {tenant_id}"}
)
# Get tenant subscription tier and inject into user context
subscription_tier = await self._get_tenant_subscription_tier(tenant_id, request)
if subscription_tier:
user_context["subscription_tier"] = subscription_tier
# Set tenant context in request state
request.state.tenant_id = tenant_id
request.state.tenant_verified = True
@@ -115,6 +120,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
logger.debug(f"Tenant access verified",
user_id=user_context["user_id"],
tenant_id=tenant_id,
subscription_tier=subscription_tier,
path=request.url.path)
# ✅ STEP 5: Inject user context into request
@@ -386,7 +392,72 @@ class AuthMiddleware(BaseHTTPMiddleware):
b"x-tenant-id", tenant_id.encode()
))
# Add subscription tier if available
subscription_tier = user_context.get("subscription_tier", "")
if subscription_tier:
request.headers.__dict__["_list"].append((
b"x-subscription-tier", subscription_tier.encode()
))
# Add gateway identification
request.headers.__dict__["_list"].append((
b"x-forwarded-by", b"bakery-gateway"
))
))
async def _get_tenant_subscription_tier(self, tenant_id: str, request: Request) -> Optional[str]:
"""
Get tenant subscription tier from tenant service
Args:
tenant_id: Tenant ID
request: FastAPI request for headers
Returns:
Subscription tier string or None
"""
try:
# Check cache first
if self.redis_client:
cache_key = f"tenant:tier:{tenant_id}"
try:
cached_tier = await self.redis_client.get(cache_key)
if cached_tier:
if isinstance(cached_tier, bytes):
cached_tier = cached_tier.decode()
logger.debug("Subscription tier from cache", tenant_id=tenant_id, tier=cached_tier)
return cached_tier
except Exception as e:
logger.warning(f"Cache lookup failed for tenant tier: {e}")
# Get from tenant service
async with httpx.AsyncClient(timeout=5.0) as client:
headers = {"Authorization": request.headers.get("Authorization", "")}
response = await client.get(
f"{settings.TENANT_SERVICE_URL}/api/v1/tenants/{tenant_id}",
headers=headers
)
if response.status_code == 200:
tenant_data = response.json()
subscription_tier = tenant_data.get("subscription_tier", "basic")
# Cache for 5 minutes
if self.redis_client:
try:
await self.redis_client.setex(
f"tenant:tier:{tenant_id}",
300, # 5 minutes
subscription_tier
)
except Exception as e:
logger.warning(f"Failed to cache tenant tier: {e}")
logger.debug("Subscription tier from service", tenant_id=tenant_id, tier=subscription_tier)
return subscription_tier
else:
logger.warning(f"Failed to get tenant subscription tier: {response.status_code}")
return "basic" # Default to basic
except Exception as e:
logger.error(f"Error getting tenant subscription tier: {e}")
return "basic" # Default to basic on error