Django Rest Framework restrict user data view to a

2019-05-19 01:39发布

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.

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

Thanks!

2条回答
Anthone
2楼-- · 2019-05-19 02:08
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 = [IsUser]
        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 IsUser(permissions.BasePermission):

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

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

查看更多
何必那么认真
3楼-- · 2019-05-19 02:08

Add a additional check in IsUser permission .

if request.method == permissions.SAFE_METHOD:
    return True
查看更多
登录 后发表回答