Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django view skips checking permission classes

I’m trying to filter lists according to:

  • the user can work with all of their lists
  • the user can use safe methods on public lists

I have this code:

In views.py:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class LinkListViewSet(viewsets.ModelViewSet,
                  generics.ListAPIView,
                  generics.RetrieveAPIView):
queryset = LinkList.objects.all()
serializer_class = LinkListSerializer
permission_classes = [IsOwnerOrPublic]

In permissions.py:

class IsOwnerOrPublic(BasePermission):
def has_permission(self, request, view):
    return request.user and request.user.is_authenticated

def has_object_permission(self, request, view, obj):
    return obj.owner == request.user or (
        obj.public and (request.method in SAFE_METHODS))

The problem is, I believe the view just skips checking the permission classes and returns all lists, and I am not sure why, or how to fix it.

>Solution :

It will only check the has_object_permission for requests that work with an object, so for example the RetrieveAPIView, not the ListAPIView.

You should filter for the latter, so we can make a custom IsOwnerOrPublicFilterBackend filter backend:

from django.db.models import Q
from rest_framework import filters

class IsOwnerOrPublicFilterBackend(filters.BaseFilterBackend):
    
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(Q(owner=request.user) | Q(public=True))

and then use that filter as filter_backend in the ModelViewSet:

class LinkListViewSet(viewsets.ModelViewSet):
    queryset = LinkList.objects.all()
    serializer_class = LinkListSerializer
    filter_backends = [IsOwnerOrPublicFilterBackend]
    permission_classes = [IsOwnerOrPublic]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading