From 4a936f85c25fc57960ce84506883058aaf8a54a6 Mon Sep 17 00:00:00 2001
From: Jonathan Weth <git@jonathanweth.de>
Date: Sat, 6 Nov 2021 20:23:51 +0100
Subject: [PATCH] Generate scope names for live documents via ORM

---
 aleksis/apps/resint/apps.py   | 20 +++++++++++++++-----
 aleksis/apps/resint/models.py |  4 +++-
 2 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/aleksis/apps/resint/apps.py b/aleksis/apps/resint/apps.py
index cc51922..2599170 100644
--- a/aleksis/apps/resint/apps.py
+++ b/aleksis/apps/resint/apps.py
@@ -1,5 +1,7 @@
 from django.apps import apps
-from django.utils.translation import gettext as _
+from django.db import models
+from django.db.models import functions
+from django.utils.translation import gettext_lazy as _
 
 from aleksis.core.util.apps import AppConfig
 
@@ -22,9 +24,17 @@ class ResintConfig(AppConfig):
     def get_all_scopes(cls) -> dict[str, str]:
         """Return all OAuth scopes and their descriptions for this app."""
         LiveDocument = apps.get_model("resint", "LiveDocument")
-        scopes = {}
-        for live_document in LiveDocument.objects.all():
-            scopes[live_document.scope] = _("Access PDF file for live document {}").format(
-                live_document.name
+        label_prefix = _("Access PDF file for live document")
+        scopes = dict(
+            LiveDocument.objects.annotate(
+                scope=functions.Concat(
+                    models.Value(f"{LiveDocument.SCOPE_PREFIX}_"),
+                    models.F("slug"),
+                    output_field=models.CharField(),
+                ),
+                label=functions.Concat(models.Value(f"{label_prefix}: "), models.F("name")),
             )
+            .values_list("scope", "label")
+            .distinct()
+        )
         return scopes
diff --git a/aleksis/apps/resint/models.py b/aleksis/apps/resint/models.py
index abf4b54..7c59730 100644
--- a/aleksis/apps/resint/models.py
+++ b/aleksis/apps/resint/models.py
@@ -149,6 +149,8 @@ class Poster(ExtensibleModel):
 class LiveDocument(ExtensiblePolymorphicModel):
     """Model for periodically/automatically updated files."""
 
+    SCOPE_PREFIX = "live_document_pdf"
+
     slug = models.SlugField(
         verbose_name=_("Slug"),
         help_text=_("This will be used for the name of the current PDF file."),
@@ -196,7 +198,7 @@ class LiveDocument(ExtensiblePolymorphicModel):
     @property
     def scope(self) -> str:
         """Return OAuth2 scope name to access PDF file via API."""
-        return f"live_document_pdf_{self.slug}"
+        return f"{self.SCOPE_PREFIX}_{self.slug}"
 
     def save(self, *args, **kwargs):
         with reversion.create_revision():
-- 
GitLab