简体   繁体   English

Django DRF-限制通过权限访问列表视图

[英]Django DRF - Restrict Access to List View via Permissions

I have a DRF ViewSet to which I am adding the CanViewAndEditStaff permission. 我具有向其添加CanViewAndEditStaff权限的DRF ViewSet。 I want only certain users ( user.access_level < 2 ) to be able to view the list of staff. 我只希望某些用户( user.access_level < 2 )能够查看人员列表。 In my Permissions class, how can I differentiate between a call to the list view and to the get item view. 在我的Permissions类中,如何区分对list视图的调用和对get项目视图的调用。 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. 您可以使用view.action知道这是列表还是其他。

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. 我在Ykh的答案上使用了一种变体,该变体允许在显示各种不同模型的许多视图中广泛使用同一权限类。

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. 这感觉有些笨拙,但是直到我找到更好的方法之前,我都会坚持下去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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