From 309cd2fcbf31fde3e2a0571b5c7321483d2f13a4 Mon Sep 17 00:00:00 2001 From: Konrad Mohrfeldt <konrad.mohrfeldt@farbdev.org> Date: Fri, 24 Jan 2025 13:39:29 +0100 Subject: [PATCH] feat: add permission names to schema This is helpful for applications like the dashboard that use static typing and can use the `AnyPermission` type to catch typos and missing/renamed permission names during the build phase. --- steering/schema.py | 20 ++++++++++++++++++++ steering/settings.py | 1 + 2 files changed, 21 insertions(+) diff --git a/steering/schema.py b/steering/schema.py index d607d104..e2c85a95 100644 --- a/steering/schema.py +++ b/steering/schema.py @@ -1,5 +1,7 @@ from typing import Iterable, Tuple +from django.contrib.auth.models import Permission + def _generate_choices_description(choices: Iterable[Tuple[str, str]]): def _gen(): @@ -53,3 +55,21 @@ def fix_schedule_pk_type(result, generator, request, public): parameter["schema"]["type"] = "integer" break return result + + +def _get_all_relevant_permission_names(): + for perm in Permission.objects.all(): + action, module_name, model_name = perm.natural_key() + if module_name not in {"program", "steering", "auth"}: + # we’re only interested in some permissions + continue + yield f"{module_name}.{action}" + + +def add_permission_type_to_schema(result, *args, **kwargs): + result["components"]["schemas"]["AnyPermission"] = { + "description": "Permissions used by steering.", + "enum": sorted(_get_all_relevant_permission_names()), + "type": "string", + } + return result diff --git a/steering/settings.py b/steering/settings.py index b3d9acbf..0ce92c81 100644 --- a/steering/settings.py +++ b/steering/settings.py @@ -104,6 +104,7 @@ SPECTACULAR_SETTINGS = { "drf_spectacular.hooks.postprocess_schema_enums", "steering.schema.add_enum_documentation", "steering.schema.fix_schedule_pk_type", + "steering.schema.add_permission_type_to_schema", "drf_spectacular.contrib.djangorestframework_camel_case.camelize_serializer_fields", ], "VERSION": "1.0.0", -- GitLab