diff --git a/authentik/core/api/users.py b/authentik/core/api/users.py index a1bef44dc5..d90ee68fb4 100644 --- a/authentik/core/api/users.py +++ b/authentik/core/api/users.py @@ -373,7 +373,7 @@ class UsersFilter(FilterSet): method="filter_attributes", ) - is_superuser = BooleanFilter(field_name="ak_groups", lookup_expr="is_superuser") + is_superuser = BooleanFilter(field_name="ak_groups", method="filter_is_superuser") uuid = UUIDFilter(field_name="uuid") path = CharFilter(field_name="path") @@ -391,6 +391,11 @@ class UsersFilter(FilterSet): queryset=Group.objects.all().order_by("name"), ) + def filter_is_superuser(self, queryset, name, value): + if value: + return queryset.filter(ak_groups__is_superuser=True).distinct() + return queryset.exclude(ak_groups__is_superuser=True).distinct() + def filter_attributes(self, queryset, name, value): """Filter attributes by query args""" try: diff --git a/authentik/core/tests/test_users_api.py b/authentik/core/tests/test_users_api.py index 140746f7c7..bd88dae787 100644 --- a/authentik/core/tests/test_users_api.py +++ b/authentik/core/tests/test_users_api.py @@ -1,6 +1,7 @@ """Test Users API""" from datetime import datetime +from json import loads from django.contrib.sessions.backends.cache import KEY_PREFIX from django.core.cache import cache @@ -15,7 +16,11 @@ from authentik.core.models import ( User, UserTypes, ) -from authentik.core.tests.utils import create_test_admin_user, create_test_brand, create_test_flow +from authentik.core.tests.utils import ( + create_test_admin_user, + create_test_brand, + create_test_flow, +) from authentik.flows.models import FlowDesignation from authentik.lib.generators import generate_id, generate_key from authentik.stages.email.models import EmailStage @@ -41,6 +46,32 @@ class TestUsersAPI(APITestCase): ) self.assertEqual(response.status_code, 200) + def test_filter_is_superuser(self): + """Test API filtering by superuser status""" + self.client.force_login(self.admin) + # Test superuser + response = self.client.get( + reverse("authentik_api:user-list"), + data={ + "is_superuser": True, + }, + ) + self.assertEqual(response.status_code, 200) + body = loads(response.content) + self.assertEqual(len(body["results"]), 1) + self.assertEqual(body["results"][0]["username"], self.admin.username) + # Test non-superuser + response = self.client.get( + reverse("authentik_api:user-list"), + data={ + "is_superuser": False, + }, + ) + self.assertEqual(response.status_code, 200) + body = loads(response.content) + self.assertEqual(len(body["results"]), 1, body) + self.assertEqual(body["results"][0]["username"], self.user.username) + def test_list_with_groups(self): """Test listing with groups""" self.client.force_login(self.admin)