Skip to content

Commit

Permalink
Use filtersets instead of manupulating query strings directly.
Browse files Browse the repository at this point in the history
  • Loading branch information
amanning9 committed Jun 10, 2024
1 parent 3ad45c9 commit 7cc2886
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 19 deletions.
21 changes: 21 additions & 0 deletions jasmin_services/api/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,30 @@


class RoleFilter(django_filters.rest_framework.FilterSet):
"""Filter to allow filtering roles by name.
Using an AllValuesMultipleFilter allows searching for more than one role at once.
"""

name = django_filters.rest_framework.AllValuesMultipleFilter()

class Meta:
model = models.Role
fields = ["name"]


class UserGrantsFilter(django_filters.rest_framework.FilterSet):
"""Filter to allow filtering user grants.
Allow filtering by service name, category name, or role name.
"""

service = django_filters.rest_framework.AllValuesFilter(
field_name="access__role__service__name", label="Service name"
)
category = django_filters.rest_framework.AllValuesFilter(
field_name="access__role__service__category__name", label="Category name"
)
role = django_filters.rest_framework.AllValuesMultipleFilter(
field_name="access__role__name", label="Role name"
)
20 changes: 1 addition & 19 deletions jasmin_services/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,32 +201,14 @@ class UserGrantsViewSet(rf_mixins.ListModelMixin, rf_viewsets.GenericViewSet):

required_scopes = ["jasmin.services.userservices.all"]
serializer_class = serializers.UserGrantSerializer
filterset_class = filters.UserGrantsFilter

def get_queryset(self):
queryset = models.Grant.objects.filter(
access__user__username=self.kwargs["user_username"],
revoked=False,
expires__gte=dt.datetime.now(),
).prefetch_related("access__role__service")

filter_params = {}

# Option to filter by service query param
service = self.request.query_params.get("service")
if service is not None:
filter_params["access__role__service__name"] = service

# Option to filter by category query param
category = self.request.query_params.get("category")
if category is not None:
filter_params["access__role__service__category__name"] = category

# Option to filter by grant role name
role = self.request.query_params.get("role")
if role is not None:
filter_params["access__role__name"] = role

queryset = queryset.filter(**filter_params)
return queryset


Expand Down

0 comments on commit 7cc2886

Please sign in to comment.