40 lines
1.4 KiB
Python
40 lines
1.4 KiB
Python
"""
|
|
Tenant middleware for handling multi-tenant requests
|
|
"""
|
|
import uuid
|
|
from typing import Optional
|
|
from fastapi import Request, HTTPException, status
|
|
from starlette.middleware.base import BaseHTTPMiddleware
|
|
from .config.settings import settings
|
|
from .models import Tenant
|
|
|
|
class TenantMiddleware(BaseHTTPMiddleware):
|
|
async def dispatch(self, request: Request, call_next):
|
|
# Get tenant ID from header or subdomain
|
|
tenant_id = request.headers.get(settings.TENANT_ID_HEADER)
|
|
|
|
if not tenant_id:
|
|
# Try to extract tenant from subdomain
|
|
host = request.headers.get("host", "")
|
|
tenant_id = self.extract_tenant_from_host(host)
|
|
|
|
if not tenant_id and settings.MULTI_TENANT_ENABLED:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Tenant ID is required"
|
|
)
|
|
|
|
# Attach tenant info to request
|
|
request.state.tenant_id = tenant_id
|
|
|
|
response = await call_next(request)
|
|
return response
|
|
|
|
def extract_tenant_from_host(self, host: str) -> Optional[str]:
|
|
"""
|
|
Extract tenant from host (subdomain.tenant.com)
|
|
"""
|
|
# For now, return a default tenant or None
|
|
# In a real implementation, you would parse the subdomain
|
|
# and look up the corresponding tenant in the database
|
|
return "default" |