Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework restrict user data view to admins & the very own user

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!

like image 409
Martin Avatar asked Jun 13 '17 23:06

Martin


Video Answer


1 Answers

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

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

like image 169
Ykh Avatar answered Oct 08 '22 19:10

Ykh