0010_allauth_oidc_from_env_var.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # Generated by Django 4.2.5 on 2023-10-02 14:31
  2. import os
  3. import re
  4. from django.db import migrations
  5. def add_OIDC_settings_from_env(apps, schema_editor):
  6. SocialApp = apps.get_model("socialaccount", "SocialApp")
  7. oidc_prefix = "SOCIALACCOUNT_PROVIDERS_openid_connect_SERVERS_"
  8. oidc_pattern = re.compile(r"{prefix}\w+".format(prefix=oidc_prefix))
  9. oidc_apps = {}
  10. for key, value in {
  11. key.replace(oidc_prefix, ""): val
  12. for key, val in os.environ.items()
  13. if oidc_pattern.match(key)
  14. }.items():
  15. number, setting = key.split("_", 1)
  16. if number in oidc_apps:
  17. oidc_apps[number][setting] = value
  18. else:
  19. oidc_apps[number] = {setting: value}
  20. oidc_apps = [x for x in oidc_apps.values()]
  21. for app in oidc_apps:
  22. app_id = app.get("id")
  23. app_server_url = app.get("server_url")
  24. if app_id and app_server_url:
  25. db_social_app = SocialApp.objects.filter(provider=app_id).first()
  26. if db_social_app and not db_social_app.settings:
  27. db_social_app.provider = "openid_connect"
  28. db_social_app.provider_id = app_id
  29. db_social_app.settings = {"server_url": app_server_url}
  30. db_social_app.save()
  31. class Migration(migrations.Migration):
  32. dependencies = [
  33. ("users", "0009_alter_user_created"),
  34. ]
  35. operations = [
  36. migrations.RunPython(
  37. code=add_OIDC_settings_from_env, reverse_code=migrations.RunPython.noop
  38. )
  39. ]