authentik.admin.migrations.0001_initial

  1# Generated by Django 5.2.17 on 2026-09-15 08:23
  2
  3from json import loads
  4import authentik.lib.models
  5import authentik.lib.utils.time
  6import django.core.validators
  7from authentik.lib.config import CONFIG
  8from django.db import connections, migrations, models
  9
 10JSON_FIELDS = ("footer_links", "flags")
 11
 12FIELDS = [
 13    "avatars",
 14    "base_url",
 15    "default_user_change_name",
 16    "default_user_change_email",
 17    "default_user_change_username",
 18    "event_retention",
 19    "reputation_lower_limit",
 20    "reputation_upper_limit",
 21    "footer_links",
 22    "gdpr_compliance",
 23    "impersonation",
 24    "impersonation_require_reason",
 25    "default_token_duration",
 26    "default_token_length",
 27    "pagination_default_page_size",
 28    "pagination_max_page_size",
 29    "flags",
 30]
 31
 32
 33def create_system_settings(apps, schema_editor):
 34    db_alias = schema_editor.connection.alias
 35    SystemSettings = apps.get_model("authentik_admin", "SystemSettings")
 36    if SystemSettings.objects.using(db_alias).exists():
 37        return
 38
 39    settings = {}
 40    with connections[db_alias].cursor() as cursor:
 41        cursor.execute(
 42            "SELECT 1 FROM information_schema.tables WHERE table_name = 'authentik_tenants_tenant'"
 43        )
 44        if cursor.fetchone() is not None:
 45            cursor.execute(
 46                f"SELECT {', '.join(FIELDS)} FROM authentik_tenants_tenant WHERE schema_name = %s",  # nosec
 47                [CONFIG.get("postgresql.default_schema")],
 48            )
 49            tenant = cursor.fetchone()
 50            if tenant is not None:
 51                settings = dict(zip(FIELDS, tenant, strict=True))
 52                # The raw cursor returns jsonb as str, which JSONField would encode again
 53                for field in JSON_FIELDS:
 54                    if isinstance(settings[field], str):
 55                        settings[field] = loads(settings[field])
 56
 57    SystemSettings.objects.using(db_alias).create(**settings)
 58
 59
 60class Migration(migrations.Migration):
 61
 62    initial = True
 63
 64    dependencies = [
 65        ("authentik_tenants", "0009_alter_tenant_base_url"),
 66    ]
 67
 68    operations = [
 69        migrations.CreateModel(
 70            name="VersionHistory",
 71            fields=[
 72                ("id", models.BigAutoField(primary_key=True, serialize=False)),
 73                ("timestamp", models.DateTimeField()),
 74                ("version", models.TextField()),
 75                ("build", models.TextField()),
 76            ],
 77            options={
 78                "verbose_name": "Version history",
 79                "verbose_name_plural": "Version history",
 80                "db_table": "authentik_version_history",
 81                "ordering": ("-timestamp",),
 82                "managed": False,
 83                "default_permissions": [],
 84            },
 85        ),
 86        migrations.CreateModel(
 87            name="SystemSettings",
 88            fields=[
 89                ("id", models.BooleanField(default=True, primary_key=True, serialize=False)),
 90                (
 91                    "avatars",
 92                    models.TextField(
 93                        default="gravatar,initials",
 94                        help_text="Configure how authentik should show avatars for users.",
 95                    ),
 96                ),
 97                (
 98                    "base_url",
 99                    models.TextField(
100                        blank=True,
101                        default="",
102                        help_text="Configure the base URL under which this authentik instance is reachable, e.g. https://authentik.company",
103                        validators=[
104                            authentik.lib.models.DomainlessURLValidator(
105                                message="Enter a valid URL, for example https://authentik.company",
106                                schemes=("http", "https"),
107                            )
108                        ],
109                    ),
110                ),
111                (
112                    "default_user_change_name",
113                    models.BooleanField(
114                        default=True, help_text="Enable the ability for users to change their name."
115                    ),
116                ),
117                (
118                    "default_user_change_email",
119                    models.BooleanField(
120                        default=False,
121                        help_text="Enable the ability for users to change their email address.",
122                    ),
123                ),
124                (
125                    "default_user_change_username",
126                    models.BooleanField(
127                        default=False,
128                        help_text="Enable the ability for users to change their username.",
129                    ),
130                ),
131                (
132                    "event_retention",
133                    models.TextField(
134                        default="days=365",
135                        help_text="Events will be deleted after this duration.(Format: weeks=3;days=2;hours=3;seconds=2).",
136                        validators=[authentik.lib.utils.time.timedelta_string_validator],
137                    ),
138                ),
139                (
140                    "reputation_lower_limit",
141                    models.IntegerField(
142                        default=-5,
143                        help_text="Reputation cannot decrease lower than this value. Zero or negative.",
144                        validators=[django.core.validators.MaxValueValidator(0)],
145                    ),
146                ),
147                (
148                    "reputation_upper_limit",
149                    models.IntegerField(
150                        default=5,
151                        help_text="Reputation cannot increase higher than this value. Zero or positive.",
152                        validators=[django.core.validators.MinValueValidator(0)],
153                    ),
154                ),
155                (
156                    "footer_links",
157                    models.JSONField(
158                        blank=True,
159                        default=list,
160                        help_text="The option configures the footer links on the flow executor pages.",
161                    ),
162                ),
163                (
164                    "gdpr_compliance",
165                    models.BooleanField(
166                        default=True,
167                        help_text="When enabled, all the events caused by a user will be deleted upon the user's deletion.",
168                    ),
169                ),
170                (
171                    "impersonation",
172                    models.BooleanField(
173                        default=True, help_text="Globally enable/disable impersonation."
174                    ),
175                ),
176                (
177                    "impersonation_require_reason",
178                    models.BooleanField(
179                        default=True,
180                        help_text="Require administrators to provide a reason for impersonating a user.",
181                    ),
182                ),
183                (
184                    "default_token_duration",
185                    models.TextField(
186                        default="days=1",
187                        help_text="Default token duration",
188                        validators=[authentik.lib.utils.time.timedelta_string_validator],
189                    ),
190                ),
191                (
192                    "default_token_length",
193                    models.PositiveIntegerField(
194                        default=60,
195                        help_text="Default token length",
196                        validators=[django.core.validators.MinValueValidator(1)],
197                    ),
198                ),
199                (
200                    "pagination_default_page_size",
201                    models.PositiveIntegerField(
202                        default=20,
203                        help_text="Default page size for API responses, if no size was requested.",
204                    ),
205                ),
206                (
207                    "pagination_max_page_size",
208                    models.PositiveIntegerField(default=100, help_text="Maximum page size"),
209                ),
210                ("flags", models.JSONField(default=dict)),
211            ],
212            options={
213                "verbose_name": "System settings",
214                "verbose_name_plural": "System settings",
215                "default_permissions": [],
216            },
217            bases=(authentik.lib.models.InternallyManagedMixin, models.Model),
218        ),
219        migrations.RunPython(code=create_system_settings, reverse_code=migrations.RunPython.noop),
220    ]
JSON_FIELDS = ('footer_links', 'flags')
FIELDS = ['avatars', 'base_url', 'default_user_change_name', 'default_user_change_email', 'default_user_change_username', 'event_retention', 'reputation_lower_limit', 'reputation_upper_limit', 'footer_links', 'gdpr_compliance', 'impersonation', 'impersonation_require_reason', 'default_token_duration', 'default_token_length', 'pagination_default_page_size', 'pagination_max_page_size', 'flags']
def create_system_settings(apps, schema_editor):
34def create_system_settings(apps, schema_editor):
35    db_alias = schema_editor.connection.alias
36    SystemSettings = apps.get_model("authentik_admin", "SystemSettings")
37    if SystemSettings.objects.using(db_alias).exists():
38        return
39
40    settings = {}
41    with connections[db_alias].cursor() as cursor:
42        cursor.execute(
43            "SELECT 1 FROM information_schema.tables WHERE table_name = 'authentik_tenants_tenant'"
44        )
45        if cursor.fetchone() is not None:
46            cursor.execute(
47                f"SELECT {', '.join(FIELDS)} FROM authentik_tenants_tenant WHERE schema_name = %s",  # nosec
48                [CONFIG.get("postgresql.default_schema")],
49            )
50            tenant = cursor.fetchone()
51            if tenant is not None:
52                settings = dict(zip(FIELDS, tenant, strict=True))
53                # The raw cursor returns jsonb as str, which JSONField would encode again
54                for field in JSON_FIELDS:
55                    if isinstance(settings[field], str):
56                        settings[field] = loads(settings[field])
57
58    SystemSettings.objects.using(db_alias).create(**settings)
class Migration(django.db.migrations.migration.Migration):
 61class Migration(migrations.Migration):
 62
 63    initial = True
 64
 65    dependencies = [
 66        ("authentik_tenants", "0009_alter_tenant_base_url"),
 67    ]
 68
 69    operations = [
 70        migrations.CreateModel(
 71            name="VersionHistory",
 72            fields=[
 73                ("id", models.BigAutoField(primary_key=True, serialize=False)),
 74                ("timestamp", models.DateTimeField()),
 75                ("version", models.TextField()),
 76                ("build", models.TextField()),
 77            ],
 78            options={
 79                "verbose_name": "Version history",
 80                "verbose_name_plural": "Version history",
 81                "db_table": "authentik_version_history",
 82                "ordering": ("-timestamp",),
 83                "managed": False,
 84                "default_permissions": [],
 85            },
 86        ),
 87        migrations.CreateModel(
 88            name="SystemSettings",
 89            fields=[
 90                ("id", models.BooleanField(default=True, primary_key=True, serialize=False)),
 91                (
 92                    "avatars",
 93                    models.TextField(
 94                        default="gravatar,initials",
 95                        help_text="Configure how authentik should show avatars for users.",
 96                    ),
 97                ),
 98                (
 99                    "base_url",
100                    models.TextField(
101                        blank=True,
102                        default="",
103                        help_text="Configure the base URL under which this authentik instance is reachable, e.g. https://authentik.company",
104                        validators=[
105                            authentik.lib.models.DomainlessURLValidator(
106                                message="Enter a valid URL, for example https://authentik.company",
107                                schemes=("http", "https"),
108                            )
109                        ],
110                    ),
111                ),
112                (
113                    "default_user_change_name",
114                    models.BooleanField(
115                        default=True, help_text="Enable the ability for users to change their name."
116                    ),
117                ),
118                (
119                    "default_user_change_email",
120                    models.BooleanField(
121                        default=False,
122                        help_text="Enable the ability for users to change their email address.",
123                    ),
124                ),
125                (
126                    "default_user_change_username",
127                    models.BooleanField(
128                        default=False,
129                        help_text="Enable the ability for users to change their username.",
130                    ),
131                ),
132                (
133                    "event_retention",
134                    models.TextField(
135                        default="days=365",
136                        help_text="Events will be deleted after this duration.(Format: weeks=3;days=2;hours=3;seconds=2).",
137                        validators=[authentik.lib.utils.time.timedelta_string_validator],
138                    ),
139                ),
140                (
141                    "reputation_lower_limit",
142                    models.IntegerField(
143                        default=-5,
144                        help_text="Reputation cannot decrease lower than this value. Zero or negative.",
145                        validators=[django.core.validators.MaxValueValidator(0)],
146                    ),
147                ),
148                (
149                    "reputation_upper_limit",
150                    models.IntegerField(
151                        default=5,
152                        help_text="Reputation cannot increase higher than this value. Zero or positive.",
153                        validators=[django.core.validators.MinValueValidator(0)],
154                    ),
155                ),
156                (
157                    "footer_links",
158                    models.JSONField(
159                        blank=True,
160                        default=list,
161                        help_text="The option configures the footer links on the flow executor pages.",
162                    ),
163                ),
164                (
165                    "gdpr_compliance",
166                    models.BooleanField(
167                        default=True,
168                        help_text="When enabled, all the events caused by a user will be deleted upon the user's deletion.",
169                    ),
170                ),
171                (
172                    "impersonation",
173                    models.BooleanField(
174                        default=True, help_text="Globally enable/disable impersonation."
175                    ),
176                ),
177                (
178                    "impersonation_require_reason",
179                    models.BooleanField(
180                        default=True,
181                        help_text="Require administrators to provide a reason for impersonating a user.",
182                    ),
183                ),
184                (
185                    "default_token_duration",
186                    models.TextField(
187                        default="days=1",
188                        help_text="Default token duration",
189                        validators=[authentik.lib.utils.time.timedelta_string_validator],
190                    ),
191                ),
192                (
193                    "default_token_length",
194                    models.PositiveIntegerField(
195                        default=60,
196                        help_text="Default token length",
197                        validators=[django.core.validators.MinValueValidator(1)],
198                    ),
199                ),
200                (
201                    "pagination_default_page_size",
202                    models.PositiveIntegerField(
203                        default=20,
204                        help_text="Default page size for API responses, if no size was requested.",
205                    ),
206                ),
207                (
208                    "pagination_max_page_size",
209                    models.PositiveIntegerField(default=100, help_text="Maximum page size"),
210                ),
211                ("flags", models.JSONField(default=dict)),
212            ],
213            options={
214                "verbose_name": "System settings",
215                "verbose_name_plural": "System settings",
216                "default_permissions": [],
217            },
218            bases=(authentik.lib.models.InternallyManagedMixin, models.Model),
219        ),
220        migrations.RunPython(code=create_system_settings, reverse_code=migrations.RunPython.noop),
221    ]

The base class for all migrations.

Migration files will import this from django.db.migrations.Migration and subclass it as a class called Migration. It will have one or more of the following attributes:

  • operations: A list of Operation instances, probably from django.db.migrations.operations
  • dependencies: A list of tuples of (app_path, migration_name)
  • run_before: A list of tuples of (app_path, migration_name)
  • replaces: A list of migration_names

Note that all migrations come out of migrations and into the Loader or Graph as instances, having been initialized with their app label and name.

initial = True
dependencies = [('authentik_tenants', '0009_alter_tenant_base_url')]
operations = [<CreateModel name='VersionHistory', fields=[('id', <django.db.models.fields.BigAutoField>), ('timestamp', <django.db.models.fields.DateTimeField>), ('version', <django.db.models.fields.TextField>), ('build', <django.db.models.fields.TextField>)], options={'verbose_name': 'Version history', 'verbose_name_plural': 'Version history', 'db_table': 'authentik_version_history', 'ordering': ('-timestamp',), 'managed': False, 'default_permissions': []}>, <CreateModel name='SystemSettings', fields=[('id', <django.db.models.fields.BooleanField>), ('avatars', <django.db.models.fields.TextField>), ('base_url', <django.db.models.fields.TextField>), ('default_user_change_name', <django.db.models.fields.BooleanField>), ('default_user_change_email', <django.db.models.fields.BooleanField>), ('default_user_change_username', <django.db.models.fields.BooleanField>), ('event_retention', <django.db.models.fields.TextField>), ('reputation_lower_limit', <django.db.models.fields.IntegerField>), ('reputation_upper_limit', <django.db.models.fields.IntegerField>), ('footer_links', <django.db.models.fields.json.JSONField>), ('gdpr_compliance', <django.db.models.fields.BooleanField>), ('impersonation', <django.db.models.fields.BooleanField>), ('impersonation_require_reason', <django.db.models.fields.BooleanField>), ('default_token_duration', <django.db.models.fields.TextField>), ('default_token_length', <django.db.models.fields.PositiveIntegerField>), ('pagination_default_page_size', <django.db.models.fields.PositiveIntegerField>), ('pagination_max_page_size', <django.db.models.fields.PositiveIntegerField>), ('flags', <django.db.models.fields.json.JSONField>)], options={'verbose_name': 'System settings', 'verbose_name_plural': 'System settings', 'default_permissions': []}, bases=(<class 'authentik.lib.models.InternallyManagedMixin'>, <class 'django.db.models.base.Model'>)>, <RunPython code=<function create_system_settings>, reverse_code=<function RunPython.noop>>]