Reputation: 3355
Am I using django rest framework (v3.4.6) object level permissions. However, I cannot figure out a few things. First I created a custom permission that checks if user works for a specific shop:
class Works4Shop(BasePermission):
def has_object_permission(self, request, view, obj):
profile = request.user.profile
if obj.shop in profile.shops.all():
return True
else:
return False
I then added permission_classes = (Works4Shop,)
to a new custom view class ShopItemsView(APIView)
Now starts the curious part first I read that I need to explicitly check for object level permissions by calling self.check_object_permissions(request,obj)
. However what I see is that getting any object through model manager enforces the policy on retrieved objects. Well not exactly, it does call the has_object_permission(self, request, view, obj)
but it ignores the result. The issue is the performance, this kind of thing creates to many unnecessary selects to DB. Can anyone explain this? I can also post logs from the DB.
Upvotes: 0
Views: 189
Reputation: 3355
So the answer was more simple than I thought. Basically this problem only occurs when using the browsable API. During rendering of the template there are many template tags for forms that use each kind of request specified in the View class (post,put,delete, etc.) and the object permissions is checked for each form individually. When I used pure json format everything started to work as it should, no unnecessary checks etc.
There is however one issue. The browsable api checks permissions for every object fetched which in turn creates an issue: you don't know what is the class of obj in has_object_permission(self, request, view, obj)
so you should make an explicit check or the APIView will throw a TypeError
Upvotes: 1