4

I have a base permission class that two ViewSets are sharing and one other permission class each that is custom to each of the ViewSets, so 3 permissions all together, is there a way to pass a specific variable down from the base permission class to the other permission classes? My setup looks like this:

class BasePerm(permissions.BasePermission):
    def has_permission(self, request, view):
        some_var = # call an API using request variable

class Perm1(permissions.BasePermission):
    def has_permission(self, request, view):
        # get the value of some_var from BasePerm


class Perm2(permissions.BasePermission):
    def has_permission(self, request, view):
        # get the value of some_var from BasePerm


class MyViewSet1(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [BasePerm, Perm1]


class MyViewSet2(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [BasePerm, Perm2]
hello
  • 1,168
  • 4
  • 24
  • 59
  • 1
    Some ideas: 1) You could set an attribute on the view parameter to has_permission(), and retrieve it in the subclassed version. 2) The base permission class could call a method defined on the subclass, passing the output of the API call. Then the subclass could override the behavior of the permissions check, without overriding has_permission(). PS: You may find it helpful to read [APIView](https://github.com/encode/django-rest-framework/blob/3.13.1/rest_framework/views.py#L104) for how permission checks are implemented - it's pretty short. – Nick ODell Aug 19 '22 at 22:38
  • Maybe you can elaborate a bit more what the purpose of the "specific variable" is? Is it some sort of authentication mechanism? – Bernhard Vallant Aug 25 '22 at 12:15

1 Answers1

6

i don't understand why you don't use mixin. For you ask:

class BasePerm(permissions.BasePermission):

    def has_permission(self, request, view):
        self.some_var = # call an API using request variable
        return True

class Perm1(BasePerm):

    def has_permission(self, request, view):
        # get the value of some_var from BasePerm
        return super().has_permission(request, view) and some_staff_with(self.some_var)


class Perm2(BasePerm):

    def has_permission(self, request, view):
        # get the value of some_var from BasePerm
        return super().has_permission(request, view) and some_other_staff_with(self.some_var)

class MyViewSet1(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [Perm1]


class MyViewSet2(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [Perm2]
Maxim Danilov
  • 2,472
  • 1
  • 3
  • 8