fmproService / backend /app /core /middleware.py
Hkoradiya123
feat: Initialize frontend with Zustand for state management, Tailwind CSS for styling, and TypeScript for type safety
4854e2b
Raw History Blame Contribute Delete
1.76 kB
"""Multi-tenant middleware"""
from fastapi import Request, HTTPException, status
from starlette.middleware.base import BaseHTTPMiddleware
import logging
logger = logging.getLogger(__name__)
class MultiTenantMiddleware(BaseHTTPMiddleware):
"""
Middleware to enforce multi-tenant isolation.
Ensures tenant_id in JWT matches the request context.
"""
async def dispatch(self, request: Request, call_next):
# Skip middleware for public endpoints
public_paths = ["/health", "/", "/docs", "/openapi.json", "/api/auth/register", "/api/auth/login"]
if request.url.path in public_paths:
return await call_next(request)
# For protected endpoints, validate tenant isolation
# This is a basic implementation - can be enhanced
response = await call_next(request)
return response
class TenantContextMiddleware(BaseHTTPMiddleware):
"""
Middleware to store tenant context in request state.
Makes tenant_id accessible throughout the request lifecycle.
"""
async def dispatch(self, request: Request, call_next):
# Extract tenant_id from token if available
from app.core.security import decode_token
auth_header = request.headers.get("Authorization")
tenant_id = None
if auth_header:
try:
token = auth_header.replace("Bearer ", "")
payload = decode_token(token)
tenant_id = payload.get("tenant_id")
except Exception:
pass
# Store in request state
request.state.tenant_id = tenant_id
response = await call_next(request)
return response