I'm trying to create REST API with django-rest-framework. My question is can I print the instance of has_object_permission
method so I can see what is going on in that part. I'm trying that only the owner of an object can update and delete the object but right now anyone can delete or update anybody object. Please tell if there is other way to do besides permissions. Can we do all these with checks in serializer. If yes then please guide me that too with example. I shall be very thankful.
class ObjectOwnerPermission(BasePermission):
message = "This object is expired." # custom error message
def has_object_permission(self, request, view, obj):
if request.user.is_authenticated:
return True
return False
if obj.author == request.user:
return True
return False
class RetrieveUpdateProjectAPIView(generics.RetrieveUpdateAPIView,ObjectOwnerPermission):
"""This endpoint allows for updating a specific Project by passing in the id of the
Project to update/Retrieve"""
permissions_classes = [ObjectOwnerPermission]
queryset = Project.objects.all()
serializer_class = serializers.ProjectSerializer
class DeleteProjectAPIView(generics.DestroyAPIView,ObjectOwnerPermission):
"""This endpoint allows for deletion of a specific Project from the database"""
permissions_classes = [ObjectOwnerPermission]
queryset = Project.objects.all()
serializer_class = serializers.ProjectSerializer
CodePudding user response:
Your permissions dont work because your return True
in your ObjectOwnerPermission
when user is authenticated which means that ANYONE who is authenticated can pass this permission.
EDIT:
In the original question permissionS_classes
whas used instead of permission_classes
Here is my fixed version:
class ObjectOwnerPermission(BasePermission):
message = "This object is expired." # custom error message
def has_object_permission(self, request, view, obj):
return obj.author == request.user
class RetrieveUpdateProjectAPIView(generics.RetrieveUpdateAPIView):
"""This endpoint allows for updating a specific Project by passing in the id of the
Project to update/Retrieve"""
permission_classes = [IsAuthenticated, ObjectOwnerPermission]
queryset = Project.objects.all()
serializer_class = serializers.ProjectSerializer
class DeleteProjectAPIView(generics.DestroyAPIView):
"""This endpoint allows for deletion of a specific Project from the database"""
permission_classes = [IsAuthenticated, ObjectOwnerPermission]
queryset = Project.objects.all()
serializer_class = serializers.ProjectSerializer
- DONT inherit from permission class in your views - it should be only used in
permission_classes
- if you want to chain your permission, it should be implemented in
permission_classes
list - permission classes are read from left to right which means that
IsAuthenticated
is checked first before your class (in your class you are sure that user is logged in)