3👍
@adeleinr I am guessing you have declared your own get_object method( i would have asked you this in the comment but don’t have sufficient points to do that :D), in that case you have to use check_object_permissions in the get_object ( also in PUT, DELETE ) .Use this in your get_object
obj = get_object_or_404(queryset, **filter)
self.check_object_permissions(self.request, obj)
2👍
I was inspired by article How I could delete any video on YouTube
and wanted to check if in my django project everything is working safe, and ended up here.
This is pretty important question!
And the answer is very good.
The Django Rest Framework
makes false impression that everything is working fine, when one looks at it through browsable API view.
Object, which authenticate user owns:
Object, which authenticate user does NOT owns:
Hidden DELETE button makes you feel, that everything is fine.
You are authenticated, delete button hidden.
Cool! You stay unaware until you test it wit CURL or some other tool and notice this huge security hole.
Django is sometimes too much magic….
Example:
views.py
@authentication_classes((ExpiringTokenAuthentication, SessionAuthentication))
@permission_classes((IsOwnerOrReadOnly, ))
class UserFavouritesSpotDetail(RetrieveUpdateDestroyAPIView):
model = UsersSpotsList
serializer_class = FavouritesSpotsListSerializer
def get_queryset(self):
queryset = UsersSpotsList.objects.filter(
role=1)
return queryset
def get_object(self):
queryset = self.get_queryset()
obj = get_object_or_404(
queryset,
pk=self.kwargs['pk'],
role=1)
self.check_object_permissions(self.request, obj)
return obj
Notice the crucial line mentioned by Shivansh:
self.check_object_permissions(self.request, obj)
When I was missing it the vulnerability was existing.
permissions.py
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `user` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
return obj.user == request.user
TEST it e.g with http://www.getpostman.com/
provide Token of user not owning the object.
if everything is fine you should see “detail”: “You do not have permission to perform this action.”
- [Django]-Django Rest Framework regroup queryset by a category
- [Django]-Django Query Performance Filtering Vs Foreign Key Set Lookup
- [Django]-Deploy Django\Tornado on Heroku
- [Django]-Django inline-formset with an image field not updating