tenants: fix tenant not being queried correctly when using accessing over a child domain

closes #1044

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2021-06-20 14:39:21 +02:00
parent f7047df40e
commit 4327b35bc3
2 changed files with 25 additions and 3 deletions

View File

@ -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()

View File

@ -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