From 4327b35bc381c7510856670e0832febc6b65a6e5 Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Sun, 20 Jun 2021 14:39:21 +0200 Subject: [PATCH] tenants: fix tenant not being queried correctly when using accessing over a child domain closes #1044 Signed-off-by: Jens Langhammer --- authentik/tenants/tests.py | 19 +++++++++++++++++++ authentik/tenants/utils.py | 9 ++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/authentik/tenants/tests.py b/authentik/tenants/tests.py index f3455e8e4..d552fd25f 100644 --- a/authentik/tenants/tests.py +++ b/authentik/tenants/tests.py @@ -23,6 +23,25 @@ class TestTenants(TestCase): }, ) + def test_tenant_subdomain(self): + """Test Current tenant API""" + Tenant.objects.all().delete() + Tenant.objects.create(domain="bar.baz", branding_title="custom") + self.assertJSONEqual( + force_str( + self.client.get( + reverse("authentik_api:tenant-current"), HTTP_HOST="foo.bar.baz" + ).content + ), + { + "branding_logo": "/static/dist/assets/icons/icon_left_brand.svg", + "branding_favicon": "/static/dist/assets/icons/icon.png", + "branding_title": "custom", + "matched_domain": "bar.baz", + "ui_footer_links": CONFIG.y("authentik.footer_links"), + }, + ) + def test_fallback(self): """Test fallback tenant""" Tenant.objects.all().delete() diff --git a/authentik/tenants/utils.py b/authentik/tenants/utils.py index 8aafc30ce..35e9010b2 100644 --- a/authentik/tenants/utils.py +++ b/authentik/tenants/utils.py @@ -1,7 +1,8 @@ """Tenant utilities""" from typing import Any -from django.db.models import Q +from django.db.models import F, Q +from django.db.models import Value as V from django.http.request import HttpRequest from authentik import __version__ @@ -14,8 +15,10 @@ DEFAULT_TENANT = Tenant(domain="fallback") def get_tenant_for_request(request: HttpRequest) -> Tenant: """Get tenant object for current request""" - db_tenants = Tenant.objects.filter( - Q(domain__iendswith=request.get_host()) | _q_default + db_tenants = ( + Tenant.objects.annotate(host_domain=V(request.get_host())) + .filter(Q(host_domain__iendswith=F("domain")) | _q_default) + .order_by("default") ) if not db_tenants.exists(): return DEFAULT_TENANT