Django Rest Framework将用户数据视图限制为管理员&自己的用户

问题描述:

我正在使用Django和DRF,我想检查一个用户(常规用户)在通过身份验证后是否被允许查看其自己的个人资料,而只能查看该个人资料(没有其他用户的个人资料)。

I am using Django and DRF, and I would like to check if a user (regular one), after it has been authenticated, is allowed to view it's own profile and only that (no other user's).

serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
    model = User
    fields = ('id', 'url', 'username', 'password', 'email', 'groups', 'is_staff')

def create(self, validated_data):
    user = super().create(validated_data)
    user.set_password(validated_data['password'])
    user.save()
    return user

Views.py

class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = (IsUser,)

permissions.py

class IsUser(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""

def has_permission(self, request, view, obj):
    # View or Write permissions are only allowed to the owner of the snippet.
    return obj.owner == request.user

这显然是行不通的,因为是错误的。我不知道如何允许用户查看:

This, obviously is not working, because is wrong. But I can not figure out how to allow a user to view:

http://127.0.0.1:8000/api/users/7

仅用于管理员,或完全相同

ONLY if its an admin, or the very same user doing the request.

和:
http://127.0.0.1:8000/api/users/
仅当它是管理员时。

And: http://127.0.0.1:8000/api/users/ Only if it's an admin.

谢谢!!

class UserViewSet(ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = UserSerializer

    def get_permissions(self):
        if self.action == 'list':
            self.permission_classes = [IsSuperUser, ]
        elif self.action == 'retrieve':
            self.permission_classes = [IsOwner]
        return super(self.__class__, self).get_permissions()

class IsSuperUser(BasePermission):

    def has_permission(self, request, view):
        return request.user and request.user.is_superuser

class IsOwner(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        if request.user:
            if request.user.is_superuser:
                return True
            else:
                return obj.owner == request.user
        else:
            return False

覆盖UserViewSet的列表和检索方法可能是最简单的方法。

override list and retrieve method for UserViewSet probably the easiest way.