2013-10-15 42 views
15

我想知道創建自定義權限來檢查用戶是否在特定組中的最佳方式。以前,我有一個裝飾器可以在視圖上使用,以便將組名與用戶對象一起傳遞,然後檢查用戶是否在指定的組中。Django REST框架:檢查用戶是否在組

即:

def in_group_views(*group_names): 
    """Requires user membership in at least one of the groups passed in.""" 

    def in_groups(u): 
     if u.is_authenticated(): 
      if bool(u.groups.filter(name__in=group_names)) | u.is_superuser: 
       return True 
     return False 

    return user_passes_test(in_groups) 

我將如何做到這一點的DRF一個視圖集,考慮到我需要檢查針對不同的行動不同的組成員(POST,PUT,GET)等

非常感謝, 本

回答

32

參數化權限類的明智方法是將參數放在視圖類。這可以讓你改變從查看到查看的行爲。

下面是一個例子:

def is_in_group(user, group_name): 
    """ 
    Takes a user and a group name, and returns `True` if the user is in that group. 
    """ 
    return Group.objects.get(name=group_name).user_set.filter(id=user.id).exists() 

class HasGroupPermission(permissions.BasePermission): 
    """ 
    Ensure user is in required groups. 
    """ 

    def has_permission(self, request, view): 
     # Get a mapping of methods -> required group. 
     required_groups_mapping = getattr(view, 'required_groups', {}) 

     # Determine the required groups for this particular request method. 
     required_groups = required_groups_mapping.get(request.method, []) 

     # Return True if the user has all the required groups. 
     return all([is_in_group(request.user, group_name) for group_name in required_groups]) 

然後,您可以使用HasGroupPermission類,像這樣:

class MyView(APIView): 
    permission_classes = [HasGroupPermission] 
    required_groups = { 
     'GET': ['moderators', 'members'], 
     'POST': ['moderators'], 
    } 

    ... 

希望幫助!

+2

你先生是紳士和學者,非常感謝! –

+0

不客氣。 –

+0

感謝您的幫助 –