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!