Home > Software engineering >  Django rest framework custom permission for ViewSet
Django rest framework custom permission for ViewSet

Time:01-27

this is my modelViewSet

class UserViewSet(viewsets.ModelViewSet):
    def list(self, request):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request):
        serializer = UserSerializer(data=request.data)

        if serializer.is_valid(raise_exception=True):
            pass

    def retrieve(self, request, pk):
        user = get_object_or_404(User, pk=pk)
        serializer = UserSerializer(user)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def get_permissions(self):
        if self.action == "list":
            permission_classes = [
                IsAdminUser,
            ]
        elif self.action == "create":
            permission_classes = [AllowAny]
        else:
            permission_classes = [AccountOwnerPermission]

        return [permission() for permission in permission_classes]
 

and this is the custom permission class

class AccountOwnerPermission(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        print(object)
        print(request.user)
        return obj == request.user

i access this view from another user and it show me user retrieve, and that 2 prints on AccountOwnerPermission won't run. can someone tell me what is wrong with what i did and why has_object_permission wont run.

i change has_object_permission to has_permission and it works, but i dont have access to obj on the other hand

CodePudding user response:

From the docs:

If you're writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object.

So you'll need to call check_object_permissions in your retrieve to be able to trigger has_object_permission:

    def retrieve(self, request, pk):
        user = get_object_or_404(User, pk=pk)
        self.check_object_permissions(request, user) # Add this line
        serializer = UserSerializer(user)
        return Response(serializer.data, status=status.HTTP_200_OK)
  •  Tags:  
  • Related