3

I have a permission class that checks if the obj.account is equal to request.user.profile.account:

class IsOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return request.user.profile.account == obj.account

And this is the my view:

class ContactDetailView(APIView):
    permission_classes = (IsOwner, )

    def get(self, request, pk, format=None):
        contact = get_object_or_404(Contact, pk=pk)
        serializer = ContactSerializer(contact)

        return Response(
            serializer.data,
        )

But I don't get permission error. It returns the contact data with no problem.

Where is my mistake?

Umut Çağdaş Coşkun
  • 1,197
  • 2
  • 15
  • 33

1 Answers1

8

You need to call check_object_permissions method before response:

class ContactDetailView(APIView):
    permission_classes = (IsOwner, )

    def get(self, request, pk, format=None):
        contact = get_object_or_404(Contact, pk=pk)
        serializer = ContactSerializer(contact)
        self.check_object_permissions(request, contact)

        return Response(
            serializer.data,
        )

Note that generic view classes already call it by default. But since you are not using RetrieveAPIView you need to do it manually.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100