| 1 |
from typing import Any, Awaitable, Callable, cast |
| 2 |
|
| 3 |
from channels.db import database_sync_to_async |
| 4 |
from channels.middleware import BaseMiddleware |
| 5 |
from channels.routing import URLRouter |
| 6 |
from django.conf import settings |
| 7 |
from django.db.models import Q |
| 8 |
from django.urls import URLResolver, path |
| 9 |
from django.utils.encoding import force_bytes, force_str |
| 10 |
from django.utils.module_loading import import_string |
| 11 |
|
| 12 |
from django_pgschemas.models import TenantModel as TenantModelBase |
| 13 |
from django_pgschemas.routing.info import DomainInfo, HeadersInfo |
| 14 |
from django_pgschemas.routing.urlresolvers import get_ws_urlconf_from_schema |
| 15 |
from django_pgschemas.schema import Schema |
| 16 |
from django_pgschemas.settings import get_tenant_header |
| 17 |
from django_pgschemas.utils import get_domain_model, get_tenant_model, remove_www |
| 18 |
|
| 19 |
|
| 20 |
def TenantURLRouter() -> Callable[[dict[str, Any], Any, Any], Awaitable[None]]: |
| 21 |
async def router(scope: dict[str, Any], receive: Any, send: Any) -> None: |
| 22 |
schema: Schema | None = scope.get("tenant") |
| 23 |
routes = [] |
| 24 |
|
| 25 |
if schema is not None: |
| 26 |
ws_urlconf = get_ws_urlconf_from_schema(schema) if schema else None |
| 27 |
|
| 28 |
if ws_urlconf: |
| 29 |
routes = import_string(ws_urlconf + ".urlpatterns") |
| 30 |
match (routes, schema.routing): |
| 31 |
case ([URLResolver()], DomainInfo(_, folder)) if folder: |
| 32 |
routes = [path(f"{folder}/", URLRouter(routes[0].url_patterns))] |
| 33 |
case _: |
| 34 |
pass |
| 35 |
|
| 36 |
_router = URLRouter(routes) |
| 37 |
return await _router(scope, receive, send) |
| 38 |
|
| 39 |
return router |
| 40 |
|
| 41 |
|
| 42 |
class BaseRoutingMiddleware(BaseMiddleware): |
| 43 |
@database_sync_to_async |
| 44 |
def get_scope_tenant(self, scope: dict[str, Any]) -> Schema | None: |
| 45 |
raise NotImplementedError |
| 46 |
|
| 47 |
async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> Any: |
| 48 |
scope = dict(scope) |
| 49 |
scope["tenant"] = await self.get_scope_tenant(scope) |
| 50 |
|
| 51 |
return await super().__call__(scope, receive, send) |
| 52 |
|
| 53 |
|
| 54 |
class DomainRoutingMiddleware(BaseRoutingMiddleware): |
| 55 |
@database_sync_to_async |
| 56 |
def get_scope_tenant(self, scope: dict[str, Any]) -> Schema | None: |
| 57 |
hostname = force_str(dict(scope["headers"]).get(b"host", b"")) |
| 58 |
hostname = remove_www(hostname.split(":")[0]) |
| 59 |
|
| 60 |
tenant: Schema | None = None |
| 61 |
|
| 62 |
# Checking for static tenants |
| 63 |
for schema, data in settings.TENANTS.items(): |
| 64 |
if schema in ["public", "default"]: |
| 65 |
continue |
| 66 |
if hostname in data.get("DOMAINS", []): |
| 67 |
tenant = Schema.create( |
| 68 |
schema_name=schema, |
| 69 |
routing=DomainInfo(domain=hostname), |
| 70 |
) |
| 71 |
break |
| 72 |
|
| 73 |
# Checking for dynamic tenants |
| 74 |
else: |
| 75 |
DomainModel = get_domain_model() |
| 76 |
|
| 77 |
prefix = scope["path"].split("/")[1] |
| 78 |
domain = None |
| 79 |
|
| 80 |
if DomainModel is not None: |
| 81 |
try: |
| 82 |
domain = DomainModel.objects.select_related("tenant").get( |
| 83 |
domain=hostname, folder=prefix |
| 84 |
) |
| 85 |
except DomainModel.DoesNotExist: |
| 86 |
try: |
| 87 |
domain = DomainModel.objects.select_related("tenant").get( |
| 88 |
domain=hostname, folder="" |
| 89 |
) |
| 90 |
except DomainModel.DoesNotExist: |
| 91 |
pass |
| 92 |
|
| 93 |
if domain is not None: |
| 94 |
tenant = cast(TenantModelBase, domain.tenant) |
| 95 |
tenant.routing = DomainInfo(domain=hostname) |
| 96 |
|
| 97 |
if prefix and domain.folder == prefix: |
| 98 |
tenant.routing = DomainInfo(domain=hostname, folder=prefix) |
| 99 |
|
| 100 |
# Checking fallback domains |
| 101 |
if not tenant: |
| 102 |
for schema, data in settings.TENANTS.items(): |
| 103 |
if schema in ["public", "default"]: |
| 104 |
continue |
| 105 |
if hostname in data.get("FALLBACK_DOMAINS", []): |
| 106 |
tenant = Schema.create( |
| 107 |
schema_name=schema, |
| 108 |
routing=DomainInfo(domain=hostname), |
| 109 |
) |
| 110 |
break |
| 111 |
|
| 112 |
return tenant |
| 113 |
|
| 114 |
|
| 115 |
class HeadersRoutingMiddleware(BaseRoutingMiddleware): |
| 116 |
@database_sync_to_async |
| 117 |
def get_scope_tenant(self, scope: dict[str, Any]) -> Schema | None: |
| 118 |
tenant_header = get_tenant_header() |
| 119 |
tenant_ref = force_str(dict(scope["headers"]).get(force_bytes(tenant_header), b"")) |
| 120 |
|
| 121 |
if not tenant_ref: |
| 122 |
return None |
| 123 |
|
| 124 |
tenant: Schema | None = None |
| 125 |
|
| 126 |
# Checking for static tenants |
| 127 |
for schema, data in settings.TENANTS.items(): |
| 128 |
if schema in ["public", "default"]: |
| 129 |
continue |
| 130 |
if tenant_ref == schema or tenant_ref == data.get("HEADER"): |
| 131 |
tenant = Schema.create( |
| 132 |
schema_name=schema, routing=HeadersInfo(reference=tenant_ref) |
| 133 |
) |
| 134 |
break |
| 135 |
|
| 136 |
# Checking for dynamic tenants |
| 137 |
else: |
| 138 |
if (TenantModel := get_tenant_model()) is not None: |
| 139 |
tenant = TenantModel._default_manager.filter( |
| 140 |
Q(pk__iexact=tenant_ref) | Q(schema_name=tenant_ref) |
| 141 |
).first() |
| 142 |
if tenant is not None: |
| 143 |
tenant.routing = HeadersInfo(reference=tenant_ref) |
| 144 |
|
| 145 |
return tenant |