GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat: add TenantMiddleware with header/subdomain/JWT resolution · IDTS-LAB/python-codebase@75a930f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src/core/middleware
    • tenant.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/core/middleware/tenant.py‎

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

0 commit comments

Comments
0 (0)
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.