如何让superadmin用户和用户自己访问API?

时间:2017-12-15 07:50:47

标签: python django django-rest-framework

我有UserUpdateAPIView,其中我可以编辑用户信息:

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()

UserDetailSerializer

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

现在,每个用户都可以访问UserUpdateAPIView,因此设计很糟糕。我只想要超级管理员和用户本身可以访问APIView,如何实现它?

我知道我可以使用permissions = [IsAdminUser]来允许管理员用户访问此API,但我只想让超级管理员用户和用户自己访问。

1 个答案:

答案 0 :(得分:1)

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()