-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtenant.py
More file actions
80 lines (65 loc) · 2.94 KB
/
Copy pathtenant.py
File metadata and controls
80 lines (65 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from src.core.config.setting import get_settings
settings = get_settings()
_default_tenant_id: int | None = None
def set_default_tenant_id(tenant_id: int) -> None:
global _default_tenant_id
_default_tenant_id = tenant_id
class TenantMiddleware(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
if not settings.MULTITENANT_ENABLED:
request.state.tenant_id = _default_tenant_id
return await call_next(request)
if request.method == "OPTIONS":
return await call_next(request)
path = request.url.path.rstrip("/")
public_paths = {"/health", "/live", "/ready", "/metrics", "/docs", "/redoc", "/openapi.json"}
if path in public_paths:
return await call_next(request)
from sqlalchemy import select
from src.core.database.postgres.session import AsyncSessionLocal
from src.modules.tenants.infrastructure.models.tenant_model import TenantModel
tenant_header = request.headers.get("X-Tenant-ID")
if tenant_header:
async with AsyncSessionLocal() as session:
result = await session.execute(
select(TenantModel.id).where(TenantModel.slug == tenant_header)
)
tid = result.scalar_one_or_none()
if tid is not None:
request.state.tenant_id = tid
return await call_next(request)
host = request.headers.get("host", "")
if host and "." in host and host.count(".") >= 2:
async with AsyncSessionLocal() as session:
result = await session.execute(
select(TenantModel.id).where(TenantModel.domain == host)
)
tid = result.scalar_one_or_none()
if tid is not None:
request.state.tenant_id = tid
return await call_next(request)
auth_header = request.headers.get("Authorization", "")
if auth_header.startswith("Bearer "):
from jose import jwt as jose_jwt
try:
payload = jose_jwt.decode(
auth_header.split(" ", 1)[1],
settings.SECRET_KEY,
algorithms=[settings.ALGORITHM],
options={"verify_aud": False},
)
tid = payload.get("tenant_id")
if tid:
request.state.tenant_id = int(tid) if isinstance(tid, str) else tid
return await call_next(request)
except Exception:
pass
return JSONResponse(
status_code=400,
content={"detail": "Tenant not identified. Provide X-Tenant-ID header."},
)