Django REST框架:检查用户是否在组中 [英] Django REST framework: Check user is in group

查看:81
本文介绍了Django REST框架:检查用户是否在组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道创建自定义权限的最佳方法,该权限可以检查用户是否在特定组中。以前,我有一个装饰器,可以在视图中使用该装饰器来传递组名称和用户对象的元组,然后检查该用户是否在指定的组中。



即:

  def in_group_views(* group_names):
要求用户至少具有以下一种身份传入的组。

def in_groups(u):
如果u.is_authenticated():
如果bool(u.groups.filter(name__in = group_names) )| u.is_superuser:
返回True
返回False

return user_passes_test(in_groups)

考虑到我需要检查不同操作(POST,PUT,GET)等的不同组成员身份,我如何针对视图集的DRF执行此操作。



非常感谢,
Ben

解决方案

参数化权限类的明智方法是将视图类上的参数。



下面是一个示例:

 #Permissions.py 
from django.contrib.auth.models导入组
from rest_framework导入权限

def is_in_group(user,group_name):

获取一个用户和一个组名,如果该用户在该组中,则返回`True`。

尝试:
返回组。 objects.get(name = group_name).user_set.filter(id = user.id).exists()
,Group.DoesNotExist除外:
返回None

类HasGroupPermission(权限.BasePermission):

确保用户位于必需的组中。


def has_permission(self,request,view):
#获取方法的映射->必填组。
required_groups_mapping = getattr(view, required_groups,{})

#确定此特定请求方法所需的组。
required_groups = required_groups_mapping.get(request.method,[])

#如果用户具有所有必需的组或员工,则返回True。
返回all([is_in_group(request.user,group_name),如果group_name!= __all__否则对required_groups中的group_name正确])或(request.user和request.user.is_staff)

然后可以使用 HasGroupPermission 类,如下所示:

 #views.py 
class MyView(APIView):
Permission_classes = [HasGroupPermission]
required_groups = {
'GET':['主持人','成员'],
'POST':['主持人','someMadeUpGroup'],
'PUT':['__all__'],
}

...

希望有帮助!

I was wondering the best way to create a custom permission that checks if a user is in a particular group. Previously, I had a decorator I could use on a view to pass in a tuple of group names along with the user object and then check if that user was in the groups specified.

Ie:

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)

How would I do this for DRF for a viewset, taking into account I need to check for different group memberships for different actions (POST,PUT,GET) etc.

Many thanks, Ben

解决方案

The sensible way to parameterize permission classes is to put the parameters on the view class. That'll let you change the behaviour from view to view.

Here's an example:

# permissions.py
from django.contrib.auth.models import Group
from rest_framework import permissions

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

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 or is staff.
        return all([is_in_group(request.user, group_name) if group_name != "__all__" else True for group_name in required_groups]) or (request.user and request.user.is_staff)

You could then use the HasGroupPermission class like so:

# views.py
class MyView(APIView):
     permission_classes = [HasGroupPermission]
     required_groups = {
         'GET': ['moderators', 'members'],
         'POST': ['moderators', 'someMadeUpGroup'],
         'PUT': ['__all__'],
     }

     ...

Hope that helps!

这篇关于Django REST框架:检查用户是否在组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆