From 764a999db8c6c59ad38b0b66c197188c7d47936d Mon Sep 17 00:00:00 2001 From: Marc 'risson' Schmitt Date: Thu, 28 Dec 2023 17:15:41 +0100 Subject: [PATCH] try with connection_created signal Signed-off-by: Marc 'risson' Schmitt --- authentik/tenants/apps.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/authentik/tenants/apps.py b/authentik/tenants/apps.py index e8af0e361..3a8f9b20d 100644 --- a/authentik/tenants/apps.py +++ b/authentik/tenants/apps.py @@ -1,14 +1,25 @@ """authentik tenants app""" -from django.core.signals import setting_changed from django.db import DEFAULT_DB_ALIAS +from django.db.backends.signals import connection_created from django.db.models.signals import post_migrate from django_tenants.utils import get_public_schema_name from authentik.blueprints.apps import ManagedAppConfig -def ensure_default_tenant(*args, using=DEFAULT_DB_ALIAS, **kwargs): +def ensure_default_tenant(*args, using=DEFAULT_DB_ALIAS, connection=None, **kwargs): """Make sure default tenant exists""" + # Make sure we've migrated before touching the database + if connection is not None: + with connection.cursor() as cursor: + cursor.execute( + "SELECT * FROM information_schema.tables " + "WHERE table_schema = 'public' AND table_name = 'authentik_tenants_tenant'" + ) + if not bool(cursor.rowcount): + return + using = connection.alias + from django_tenants.utils import schema_context from authentik.tenants.models import Tenant @@ -32,4 +43,4 @@ class AuthentikTenantsConfig(ManagedAppConfig): """Make sure default tenant exists, especially after a migration""" ensure_default_tenant() post_migrate.connect(ensure_default_tenant) - setting_changed.connect(ensure_default_tenant) + connection_created.connect(ensure_default_tenant)