fanhualuojin154873
fanhualuojin154873

Reputation: 541

How can I let the superadmin user and user itself to access a API?

I have a UserUpdateAPIView, in it I can edit the user information:

class UserUpdateAPIView(RetrieveUpdateAPIView):
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)
    serializer_class = UserDetailSerializer  
    lookup_field = "username"
    def perform_update(self, serializer):
        serializer.save()

The UserDetailSerializer:

class UserDetailSerializer(ModelSerializer):
"""
user detail
"""
class Meta:
    model = User
    exclude = [
        'password',
    ]
    depth = 1

Now, every user can access the UserUpdateAPIView, so its a bad design. I just want the super admin and the user itself can access the APIView, how to implement it?

I know I can use permissions = [IsAdminUser] to allow the admin users to access this API, but I just want to let the super admin user and the user itself to access.

Upvotes: 0

Views: 479

Answers (1)

Ykh
Ykh

Reputation: 7717

from rest_framework import permissions
from rest_framework.compat import is_authenticated

class IsAdminUserOrSelf(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        # this methid is called in get_object method.
        # obj mean the object you retrieve.Here you retrieved is User instance.
        # It's can be any model instance,depend on the Molde you Retrieve in views.

        # if you want everyone can see user info
        if request.method in permissions.SAFE_METHODS:
            return True
        # if you use Django2.0 is_authenticated(request.user) should be changed to request.user.is_authenticated
        if request.user and is_authenticated(request.user):
            # is self or is superuser
            return obj == request.user or request.user.is_superuser
        else:
            return False

class UserUpdateAPIView(RetrieveUpdateAPIView):
    permissions = [IsAdminUserOrSelf,]
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)
    serializer_class = UserDetailSerializer  
    lookup_field = "username"
    def perform_update(self, serializer):
        serializer.save()

Upvotes: 1

Related Questions