From 055c0da1889cbd38d912cfa8e8bce7a2b0a54d57 Mon Sep 17 00:00:00 2001
From: Ernesto Rico Schmidt <ernesto@helsinki.at>
Date: Fri, 12 Apr 2024 18:11:16 -0400
Subject: [PATCH] feat: add management command and Makefile target to delete
 OIDC clients

Closes #219
---
 Makefile                                      |  3 +++
 .../commands/delete_oidc_clients.py           | 26 +++++++++++++++++++
 2 files changed, 29 insertions(+)
 create mode 100644 program/management/commands/delete_oidc_clients.py

diff --git a/Makefile b/Makefile
index ed3edf87..7e571cc4 100644
--- a/Makefile
+++ b/Makefile
@@ -18,6 +18,9 @@ create_oidc_client.dashboard:
 create_oidc_client.tank:
 	$(POETRY_RUN_MANAGE) create_oidc_client tank confidential --client-id ${TANK_OIDC_CLIENT_ID} --client-secret ${TANK_OIDC_CLIENT_SECRET} -r "code" -u ${TANK_CALLBACK_BASE_URL}/tank/auth/oidc/callback
 
+delete_oidc_clients:
+	$(POETRY_RUN_MANAGE) delete_oidc_clients dashboard tank
+
 initialize: migrate collectstatic create_oidc_client.dashboard create_oidc_client.tank addpermissions
 	$(POETRY_RUN_MANAGE) createsuperuser --no-input
 	$(POETRY_RUN_MANAGE) creatersakey
diff --git a/program/management/commands/delete_oidc_clients.py b/program/management/commands/delete_oidc_clients.py
new file mode 100644
index 00000000..22c46f21
--- /dev/null
+++ b/program/management/commands/delete_oidc_clients.py
@@ -0,0 +1,26 @@
+from oidc_provider.models import Client
+
+from django.core.management.base import BaseCommand
+
+
+class Command(BaseCommand):
+    help = "Deletes OIDC clients"
+
+    def add_arguments(self, parser):
+        parser.add_argument(
+            "name",
+            help="The name(s) of the OIDC client(s) to delete",
+            nargs="*",
+            type=str,
+        )
+
+    def handle(self, *args, **options):
+        try:
+            count, _ = Client.objects.filter(name__in=options["name"]).delete()
+        except Exception:
+            self.stdout.write(self.style.ERROR("Failed to delete OIDC clients"))
+        else:
+            if count > 0:
+                self.stdout.write(self.style.SUCCESS(f"Deleted {str(count)} OIDC clients"))
+            else:
+                self.stdout.write(self.style.WARNING("No OIDC clients to delete"))
-- 
GitLab