gpt4 book ai didi

django-rest-framework - Django REST框架:检查用户是否在组中

转载 作者:行者123 更新时间:2023-12-03 10:33:44 25 4
gpt4 key购买 nike

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

即:

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)

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

非常感谢,

最佳答案

参数化权限类的明智方法是将参数放在 View 类上。这样一来,您就可以在不同的 View 之间更改行为。

这是一个例子:

# 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)

然后,您可以像这样使用 HasGroupPermission类:
# views.py
class MyView(APIView):
permission_classes = [HasGroupPermission]
required_groups = {
'GET': ['moderators', 'members'],
'POST': ['moderators', 'someMadeUpGroup'],
'PUT': ['__all__'],
}

...

希望有帮助!

关于django-rest-framework - Django REST框架:检查用户是否在组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19372553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com