Jun 28 Optimize code

This commit is contained in:
2026-06-28 10:16:20 -04:00
parent ee7b0286b2
commit 45ae2b9c64
13 changed files with 536 additions and 61 deletions
+40 -1
View File
@@ -7,6 +7,8 @@ Wires tenant resolution into the Flask request lifecycle.
* always clears g.tenant / g.tenant_engine (so downstream code can rely on them)
* does NOTHING further when MULTI_TENANT_ENABLED is False → today's behaviour
* bypasses static + configured exempt paths (health checks)
* MT-4: checks session['impersonating_tenant_id'] and short-circuits Host
resolution when a superadmin is impersonating a tenant
* otherwise resolves the Host header to a tenant and selects its engine
* returns a 404 page for an unknown / unverified / suspended host
@@ -15,7 +17,7 @@ so each request rebinds via RoutingSession.get_bind against the fresh
g.tenant_engine — no teardown handler is needed here.
"""
from flask import g, request, current_app, Response
from flask import g, request, current_app, Response, session
from app.tenancy.resolver import resolve_tenant
from app.tenancy.engine_cache import get_tenant_engine
@@ -60,6 +62,43 @@ def init_tenancy(app):
if _is_exempt(request.path):
return
# ── MT-4: Superadmin impersonation override ───────────────────────
# When the control panel places a signed token in the session via
# /auth/impersonate, bypass Host resolution and bind directly to that
# tenant's DB. The session is server-signed so this is safe.
imp_id = session.get('impersonating_tenant_id')
if imp_id is not None:
from control.base import control_session
from control.models import Tenant
from app.tenancy.context import TenantContext
with control_session() as s:
t = s.get(Tenant, imp_id)
if t and t.status == 'active':
plan = t.plan
ctx = TenantContext(
id=t.id,
slug=t.slug,
name=t.name,
plan_id=t.plan_id,
db_uri=t.db_uri,
plan_code=plan.code if plan else None,
max_users=plan.max_users if plan else None,
max_facilities=plan.max_facilities if plan else None,
max_inspections_month=plan.max_inspections_month if plan else None,
max_issues_month=plan.max_issues_month if plan else None,
allow_mobile_api=plan.allow_mobile_api if plan else True,
allow_scheduled_reports=plan.allow_scheduled_reports if plan else True,
allow_branding=plan.allow_branding if plan else True,
allow_custom_domain=plan.allow_custom_domain if plan else True,
)
g.tenant = ctx
g.tenant_engine = get_tenant_engine(ctx)
return # skip normal Host resolution
# Impersonation target invalid or suspended — clear and fall through
session.pop('impersonating_tenant_id', None)
session.pop('impersonating_superadmin_id', None)
# ── Normal Host → tenant resolution ──────────────────────────────
host = (request.host or '').split(':')[0].strip().lower()
tenant = resolve_tenant(host)
if tenant is None: