简体   繁体   中英

Django DRF - Restrict Access to List View via Permissions

I have a DRF ViewSet to which I am adding the CanViewAndEditStaff permission. I want only certain users ( user.access_level < 2 ) to be able to view the list of staff. In my Permissions class, how can I differentiate between a call to the list view and to the get item view. Here is my permissions class:

class CanViewAndEditStaff(permissions.BasePermission):

        def has_permission(self, request, view):

            # IF THIS IS A LIST VIEW, CHECK ACCESS LEVEL
            if ( request.user.access_level < 3 ):
                return True

            # ELSE, CONTINUE ON TO OBJECT PERMISSIONS

        def has_object_permission(self,request,view,account):

            # admin can do anything
            if ( request.user.access_level == 1 ):
                return True

            # view/edit/delete
            else:

                # users can view their own account
                if  account == request.user:
                    return True

                elif account.access_level >= request.user.access_level:
                    return True

            return False
class CanViewAndEditStaff(permissions.BasePermission):

    def has_permission(self, request, view):

        # IF THIS IS A LIST VIEW, CHECK ACCESS LEVEL
        if (view.action == 'list' and request.user.access_level < 3 ):
            return True

        # ELSE, CONTINUE ON TO OBJECT PERMISSIONS

you can use view.action to know if this is list or something else.

This doesn't exactly address the question, but this technique is applicable.

I used a variation on Ykh's answer that allows the same permission class to be used broadly across many views which display a variety of different models.

In my view class I added an attribute to distinguish the originating view, thus allowing the appropriate object comparison to determine permissions

# views.py
class SomeView(ListAPIView):
    permission_classes = (IsPermd, )
    is_some_view = True

class SomeOtherView(RetrieveAPIView
    permission_classes = (IsPermd, )
    is_some_other_view = True

# permissions.py
class IsPermd(BasePermission):
    def has_object_permissions(self, request, view, obj):
        if hasattr(view, 'is_some_view'):
            # whatever special considerations
        if hasattr(view, 'is_some_other_view'):
            # whatever other special considerations

This feels a little clunky, but until I find a better way I'll stick with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM