Django Rest Framework custom permissions per view

前端 未结 3 2053
-上瘾入骨i
-上瘾入骨i 2021-02-10 00:36

I want to create permissions in Django Rest Framework, based on view + method + user permissions.

Is there a way to achieve this without manually writing each permission

3条回答
  •  眼角桃花
    2021-02-10 01:17

    thanks, I took this idea and got it to work like so:

    class genericPermissionCheck(permissions.BasePermission):

    def __init__(self, action, entity):
        self.action = action
        self.entity = entity
    
    def has_permission(self, request, view):
        print self.action
        print self.entity
        if request.user and request.user.role.access_rights.filter(action=self.action,entity=self.entity):
            print 'permission granted'            
            return True
        else:
            return False
    

    I used partial in the decorator for the categories action in my viewset class like so:

    @list_route(methods=['get'],permission_classes=[partial(genericPermissionCheck,'Fetch','Categories')])
    def Categories(self, request):
    

    BTW, "access_rights" maps to an array of objects with a pair of action and object e.g. 'Edit' and 'Blog'

提交回复
热议问题