# Generated by Django 3.2.6 on 2021-08-23 14:34
import django.contrib.postgres.fields
from django.apps.registry import Apps
from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor

from authentik.stages.password import BACKEND_APP_PASSWORD


def update_default_backends(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    PasswordStage = apps.get_model("authentik_stages_password", "passwordstage")
    db_alias = schema_editor.connection.alias

    stages = PasswordStage.objects.using(db_alias).filter(name="default-authentication-password")
    if not stages.exists():
        return
    stage = stages.first()
    if BACKEND_APP_PASSWORD not in stage.backends:
        stage.backends.append(BACKEND_APP_PASSWORD)
    stage.save()


class Migration(migrations.Migration):
    dependencies = [
        ("authentik_stages_password", "0006_passwordchange_rename"),
    ]

    operations = [
        migrations.AlterField(
            model_name="passwordstage",
            name="backends",
            field=django.contrib.postgres.fields.ArrayField(
                base_field=models.TextField(
                    choices=[
                        ("authentik.core.auth.InbuiltBackend", "User database + standard password"),
                        ("authentik.core.auth.TokenBackend", "User database + app passwords"),
                        (
                            "authentik.sources.ldap.auth.LDAPBackend",
                            "User database + LDAP password",
                        ),
                    ]
                ),
                help_text="Selection of backends to test the password against.",
                size=None,
            ),
        ),
        migrations.RunPython(update_default_backends),
    ]
