I don't seem to be triggering the has_object_permission function.
class MyPermission(DefaultPermission):
def has_permission(self, request, view):
return request.user.is_superuser
def has_object_permission(self, request, view, obj):
import pdb;pdb.set_trace()
return request.user == obj.submitter
Going to mydomain.com/api/mymodel/100, this should be considered accessing the object, correct? I am viewing object 100 here. Why isn't my trace() being picked up?
View
class MyModelViewSet(viewsets.ModelViewSet):
serializer_class = MyModelSerializer
permission_classes = (MyPermission,)
def get_queryset(self):
queryset = MyModel.objects.all()
return queryset
In a DRF generic views check_permissions(request) is always called in every request since it is inside the dispatch method.
check_permissions method collects all the permissions from the permission classes and checks each permission. If any permission return false the method raises an exception.
So if your has_permission method returns false has_object_permission is not called.
check_object_permissions(request, obj) calls has_object_permission method on each permission class. It is called inside get_object method.
So the rule is if has_permission for all permission classes returns true then and only then has_object_permission is checked.
class MyPermission(DefaultPermission):
def has_permission(self, request, view):
# check if the request is for a single object
if view.lookup_url_kwarg in view.kwargs:
return True
return request.user.is_superuser
def has_object_permission(self, request, view, obj):
import pdb;pdb.set_trace()
return request.user == obj.submitter
Permission won't work because check_object_permissions method is called only in get_object function. So you should call that function in your views:
def check(self, request, pk=None):
obj = self.get_object()
Or you could add permissions directly in the decorator,
Example
class MyViewSet(ModelViewSet):
queryset = MyModel.objects.all()
....
permission_classes = (MyPermission, )
#detail_route(methods=['GET', ])
def custom(self, request, pk=None):
my_obj = self.get_object() # do this and your permissions shall be checked
return Response('whatever')
From the docs(django-rest-framework)
Note: The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call .check_object_permissions(request, obj). If you are using the generic views then this will be handled for you by default.
Related
I want users to have access only to the records that belong to them, not to any other users' records so
I've created the following view:
class AddressViewSet(viewsets.ModelViewSet):
authentication_classes = (TokenAuthentication,)
permission_classes = [IsAuthenticated, IsOwner]
queryset = Address.objects.all()
def retrieve(self, request, pk):
address = self.address_service.get_by_id(pk)
serializer = AddressSerializer(address)
return Response(serializer.data, status=status.HTTP_200_OK)
I want only the owner of the records to have access to all the methods in this view ie retrieve, list, etc (I'll implement the remaining methods later) so I created the following permissions.py file in my core app:
class IsOwner(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
print('here in has_object_permission...')
return obj.user == request.user
this wasn't working, so after going through stackoverflow answers I found this one Django Rest Framework owner permissions where it indicates that has_permission method must be implemented. But as you can see in that answer, it's trying to get the id from the view.kwargs but my view.kwargs contains only the pk and not the user. How can I fix this? Do I need to implicitly pass the user id in the request url? that doesn't sound right.
Here's the test I'm using to verify a user cannot access other user's records:
def test_when_a_user_tries_to_access_another_users_address_then_an_error_is_returned(self):
user2 = UserFactory.create()
addresses = AddressFactory.create_batch(3, user=user2)
address_ids = [address.id for address in addresses]
random_address_id = random.choice(address_ids)
url = reverse(self.ADDRESSES_DETAIL_URL, args=(random_address_id,))
res = self.client.get(url, format='json')
print(res.data)
Currently just using the test to check the data returned, will implement the assertions later on.
Edit
So I added has_permission method to IsOwner:
def has_permission(self, request, view):
return request.user and request.user.is_authenticated
if I put a print statement here it gets printed, but doesn't seem to be hitting the has_object_permission method, none of the prints I added there are being displayed
This answer was the right one for me.
It says:
The has_object_permission is not called for list views. The
documentation says the following:
Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you
require object-level filtering of list views, you'll need to filter
the queryset separately. See the filtering documentation for more
details.
Link to documentation
Note: The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed.
You need to write the has_permission too in order to make your custom permission works.
Here is the official docs and mentioned it. It should works after you add in has_permission.
As mentioned in the docs, permissions are checked on self.get_object method call.
def get_object(self):
obj = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"])
self.check_object_permissions(self.request, obj)
return obj
Which basically is all retrieve method does in ModelViewSet
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response(serializer.data)
Whatever it is you do in self.address_service.get_by_id(pk) should either be moved to self.get_object or call self.check_object_permissions(self.request, obj) in retrieve method.
In the basic scenario this is all you need. There's no need to overwrite retrieve method.
class AddressViewSet(viewsets.ModelViewSet):
serializer_class = AddressSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = [IsAuthenticated, IsOwner]
queryset = Address.objects.all()
I looked through similar questions on the same topic and I think I am following all the rules specified for has_object_permission.
This is what I have in my settings.
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'users.permissions.CanAccessData', # this is my custom class
],
...
}
This is my permission class
class CanAccessData(permissions.BasePermission):
message = 'You do not have permission to perform this action.'
def has_permission(self, request, view):
print "has_permission`"
return True
def has_object_permission(self, request, view, obj):
print "has_object_permission"
return False
Here is my view structure:
class CompleteList(generics.ListCreateAPIView):
permission_classes = (CanAccessData,)
serializer_class = SomeSerializer
model = Some
filter_backends = (filters.OrderingFilter, filters.SearchFilter)
ordering_fields = (tuple of Some fields)
search_fields = ordering_fields
ordering = ('-create_date')
Still, has_object_permission is not getting called, has_permission gets called though.
The has_object_permission is not called for list views. The documentation says the following:
Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.
I ran into the same problem. The has_object_permission function is never called when listing objects.
Even if the following may not be the most efficient solution, you can override the list method in your view as follows, which is how I solved it for me:
from typing import List
import rest_framework.permissions as drf_permissions
def list(self, request, *args, **kwargs):
# base query set
queryset: QuerySet = self.filter_queryset(self.get_queryset())
# check object permissions for each object individually
valid_pks: List[int] = [] # # storage for keys of valid objects
permissions: List[drf_permissions.BasePermission] = self.get_permissions()
for obj in queryset:
for permission in permissions:
if permission.has_object_permission(request, self, obj):
valid_pks.append(obj.pk)
# remove not valid objects from the queryset
queryset = queryset.filter(pk__in=valid_pks)
# ... business as usual (original code)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
This basically is the original implementation except that it prefetches the relevant objects and checks the permission individually.
However, this may be DRY in the sense that you don't have to override the get_queryset() method to somehow reinvent your has_object_permission logic. But also it is slow, since it fetches objects twice. You could improve that situation by working with the already prefetched objects instead of filtering the queryset, though.
has_object_permission method will only be called if the view-level has_permission checks have already passed.
look this real-world example
olympia project on github (https://github.com/mozilla/addons-server/blob/master/src/olympia/ratings/permissions.py)
class CanDeleteRatingPermission(BasePermission):
"""A DRF permission class wrapping user_can_delete_rating()."""
def has_permission(self, request, view):
return request.user.is_authenticated
def has_object_permission(self, request, view, obj):
return user_can_delete_rating(request, obj)
when use this permission class, if has_permission is passed then has_object_permission ( user_can_delete_rating() function ) is called.
I am new to Django. I was trying to use django generic views, class based.
How do I implement following situation, I have two api end points login/ and logout/ and the same view class handles it ?
# Login and logout
class SignInActivity(generics.RetrieveUpdateAPIView):
serializer_class = UserSerializer
request = None
def get_queryset(self):
return User.objects.filter(Q(username=self.request.data["username"])
& Q(userpassword=self.request.data["userpassword"]))
def update(self, request, *args, **kwargs):
self.request = request
query_set = self.get_queryset()
if bool(query_set):
query_set.update_or_create(username=self.request.data["username"],
userpassword=self.request.data["userpassword"],
defaults={
"lastlogin": timezone.now()
})
return Response(data={"message": "User logged in successfully.", "response_code": 222}, status=201)
else:
return Response(data={"message": "User not found.", "response_code": 444}, status=201)
And my urls.py is
path('login/', SignInActivity.as_view())
This implementation hadles login/ with this class, PUT method. Now can I use same class with another method to handle logout/ PUT method?
By default generics.RetrieveUpdateAPIView provides 3 HTTP methods, which are GET,PUT,PATCH. You could override any of the following methods to logout procedure.
class SignInActivity(generics.RetrieveUpdateAPIView):
serializer_class = UserSerializer
request = None
def get_queryset(self):
return User.objects.filter(Q(username=self.request.data["username"])
& Q(userpassword=self.request.data["userpassword"]))
def update(self, request, *args, **kwargs):
return Response(data="HTTP PUT method")
def partial_update(self, request, *args, **kwargs):
return Response(data="HTTP PATCH method")
def retrieve(self, request, *args, **kwargs):
# your log-out logic
return Response(data="HTTP GET method")
I think you can use retrieve() method to do logout procedure, because, there is no need of sending additional payloads to the end-point, I assume
I think it's not possible to points two end points to same method function (POST or PUT) of the same view class.
One of the solution could be to use inheritance, where there could be a base class and login and logout endpoint classes inheriting from this class, and later implement respective method functions inside the child classes.
So basically, the two end points will still use functions of different class, with common properties inherited.
class SignInActivity(generics.RetrieveUpdateAPIView):
should be
from rest_framework.views import APIView
class SignInActivity(APIView):
Urls.py
path('login/', SignInActivity.as_view()),
path('logout/', SignInActivity.as_view())
This should be doing the fact as when the request is recieved our domain.com/logout/ it would forward it to the SignInActivity View as well as when request over domain.com/login/ is received!
I am confused with the BasePermission in Django-rest-framework.
Here I defined a class: IsAuthenticatedAndOwner.
class IsAuthenticatedAndOwner(BasePermission):
message = 'You must be the owner of this object.'
def has_permission(self, request, view):
print('called')
return False
def has_object_permission(self, request, view, obj):
# return obj.user == request.user
return False
Using in views.py
class StudentUpdateAPIView(RetrieveUpdateAPIView):
serializer_class = StudentCreateUpdateSerializer
queryset = Student.objects.all()
lookup_field = 'pk'
permissions_classes = [IsAuthenticatedAndOwner]
But it doesn't work at all. Everyone can pass the permission and update the data.
The called wasn't printed.
And I used to define this class: IsNotAuthenticated
class IsNotAuthenticated(BasePermission):
message = 'You are already logged in.'
def has_permission(self, request, view):
return not request.user.is_authenticated()
It works well in the function
class UserCreateAPIView(CreateAPIView):
serializer_class = UserCreateSerializer
queryset = User.objects.all()
permission_classes = [IsNotAuthenticated]
So, what are the differences between the examples above, and function has_object_permission & has_permission?
We have following two permission methods on BasePermission class:
def has_permission(self, request, view)
def has_object_permission(self, request, view, obj)
Those two different methods are called for restricting unauthorized users for data insertion and manipulation.
has_permission is called on all HTTP requests whereas, has_object_permission is called from DRF's method def get_object(self). Hence, has_object_permission method is available for GET, PUT, DELETE, not for POST request.
In summary:
permission_classes are looped over the defined list.
has_object_permission method is called after has_permission method returns value True except in POST method (in POST method only has_permission is executed).
When a False value is returned from the permission_classes method, the request gets no permission and will not loop more, otherwise, it checks all permissions on looping.
has_permission method will be called on all (GET, POST, PUT, DELETE) HTTP request.
has_object_permission method will not be called on HTTP POST request, hence we need to restrict it from has_permission method.
Basically, the first code denies everything because has_permission return False.
has_permission is a check made before calling the has_object_permission. That means that you need to be allowed by has_permission before you get any chance to check the ownership test.
What you want is:
class IsAuthenticatedAndOwner(BasePermission):
message = 'You must be the owner of this object.'
def has_permission(self, request, view):
return request.user and request.user.is_authenticated
def has_object_permission(self, request, view, obj):
return obj.user == request.user
This will also allow authenticated users to create new items or list them.
I think this can help:
class IsAuthorOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
# Read-only permissions are allowed for any request
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the author of a post
return obj.user == request.user
has_permission() is a method on the BasePermission class that is used to check if the user has permission to perform a certain action on the entire model. For example, you might use it to check if a user has permission to view a list of all objects of a certain model.
has_object_permission() is a method on the BasePermission class that is used to check if the user has permission to perform a certain action on a specific instance of the model. For example, you might use it to check if a user has permission to view, update or delete a specific object of a certain model.
For example, you might have a Book model and a User model in your application. You could use has_permission() to check if a user has permission to view a list of all books, while you use has_object_permission() to check if a user has permission to view, update or delete a specific book.
class IsBookOwnerOrAdmin(permissions.BasePermission):
def has_permission(self, request, view):
# Check if the user is authenticated
if not request.user.is_authenticated:
return False
# Allow access for superusers
if request.user.is_superuser:
return True
# Allow access if the user is the owner of the book
if request.method in permissions.SAFE_METHODS:
return True
return False
def has_object_permission(self, request, view, obj):
# Allow access for superusers
if request.user.is_superuser:
return True
# Allow access if the user is the owner of the book
return obj.owner == request.user
As far as I can see, you are not adding your custom permission to the class as an argument.
This is your code:
class StudentUpdateAPIView(RetrieveUpdateAPIView):
serializer_class = StudentCreateUpdateSerializer
queryset = Student.objects.all()
lookup_field = 'pk'
permissions_classes = [IsAuthenticatedAndOwner]
But it should be:
class StudentUpdateAPIView(RetrieveUpdateAPIView, IsAuthenticatedAndOwner):
serializer_class = StudentCreateUpdateSerializer
queryset = Student.objects.all()
lookup_field = 'pk'
permissions_classes = [IsAuthenticatedAndOwner]
Note the custom permission IsAuthenticatedAndOwner as an argument in the class header.
PS: I hope this helps, I am a beginner in DRF but this is one of the things I just learned.
Hi so I have a working view. I wanted to know if this is the best or a good way of doing it. I want to have a delete view that deletes a Photo object but only if the logged in user is the on associated with the object.
Here is my views.py
class PhotoDelete(DeleteView):
model = Photo
template_name = 'otologue/photo_delete.html'
success_url = reverse_lazy('otologue:photos')
def get(self, request, *args, **kwargs):
object_instance = self.get_object() # Get the object
object_user = object_instance.photoextended.user # Get the user who owns the object
user = get_object_or_404(User, username=self.request.user) # Get the user in the view
if object_user != user: # See if the object_user is the same as the user
return HttpResponseForbidden('Permission Error')
else:
return render(request, self.template_name, {'object': object_instance})
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
If you need more info like the models and such, please request it.
You don't have to call get_object_or_404(), since self.request.user already contains an instance of User, so you can compare it directly.
You should call (and return the result) DeleteView's get() method instead of rendering the template yourself.
I would also use LoginRequiredMixin instead of a decorator, since your dispatch() now does nothing apart from calling super's method.
Be aware, that the actual deletion is done in the post() method. You should move your user check to the dispatch() method, otherwise it will be possible to bypass the check with a forged POST request.
To have better idea what DeleteView does in its methods, check it's source code (for example at ccbv.co.uk)