Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest permissions allow both IsAdmin and custom permission

I have a views.py as below,

from webapi.permissions import IsOwner

class MemberDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = members.objects.all()
    serializer_class = MemberSerializer
    permission_classes = (permissions.IsAdminUser,IsOwner)

And the following is custom permission to check if the user is ower of object in webapi.permissions,

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

Now the issue is it is check if he is a admin user and gives permissions to update / delete, But if the owner is the user it should actually give permission to edit he data but in this case it is failing.

On seeing the question "Django Rest Framework won't let me have more than one permission" I tried as below also still it did not work when I use Or,

class MemberDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = members.objects.all()
    serializer_class = MemberSerializer
    permission_classes = (Or(permissions.IsAdminUser,IsOwner))

If I use Or it is failing with error during run time as "'Condition' object is not iterable"

like image 454
Naggappan Ramukannan Avatar asked Aug 08 '17 08:08

Naggappan Ramukannan


2 Answers

Since DRF 3.9, you can use the logical bitwise operators | and & (~ was added in 3.9.2).

As outlined in the docs you would just need

    permission_classes = (permissions.IsAdminUser|IsOwner,)
like image 79
esmail Avatar answered Sep 29 '22 15:09

esmail


If you need give edit permissions for admin and owner users only, you can implement custom permission class:

class IsOwnerOrAdmin(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.owner == request.user or request.user.is_admin

And use only this one in the view:

permission_classes = [IsOwnerOrAdmin]

This method is documented here.

like image 22
neverwalkaloner Avatar answered Sep 29 '22 13:09

neverwalkaloner