[英]permissions checking in serializer, Django rest framework,
I'm fairly new and django rest framework and I have some questions regardin permissions. 我是相当新的和django rest框架,我对权限有一些疑问。
So I have a user who is a member of organization and member of some group. 因此,我有一个用户,该用户是组织的成员和某个组的成员。 Lets say we have a model:
假设我们有一个模型:
class SomeModel:
organization = models.ForeignKey(Organization)
name = models.CharField()
User can only create
/ update
SomeModel
for its own organization and if he's a group of "Coordinators" he can also create
/ update
for any organization. 用户只能为其自己的组织
create
/ update
SomeModel
,如果他是一组“协调员”,则他也可以为任何组织create
/ update
。
Currently my approach is to check these conditions in serializer, in .create()
and .update()
methods, since the data is already validated and I'm raising PermissionDenied
errors there. 目前,我的方法是使用
.create()
和.update()
方法在序列化程序中检查这些条件,因为数据已经通过验证,并且我在此处引发PermissionDenied
错误。 But it feels like that this is not "the right way". 但是感觉这不是“正确的方法”。 I tried making a custom permissions classes, but then the data is not validated, since permissions classes are checked before serializers.
我尝试制作自定义权限类,但随后数据未经验证,因为在序列化程序之前检查了权限类。 Do you have any suggestions how should I approach this?
您对我有什么建议吗?
Sorry for bad english, it's not my native language. 对不起,英语不好,这不是我的母语。 Thanks!
谢谢!
EDIT: Example: Request data is something like: 编辑:示例:请求数据是这样的:
payload = {'organization': 1, 'name': 'Name'}
So if a user is from organization 1 or he's a coordinator access should be granted and SomeModel
should be created 因此,如果用户来自组织1或他是协调员,则应授予访问权限并应创建
SomeModel
You can write a custom permission class HasWritePermissions
which will check whether a user has write/update permissions. 您可以编写一个自定义权限类
HasWritePermissions
,它将检查用户是否具有写/更新权限。
To create a custom permission class , you will need to override BasePermission
class and implement has_permission()
method. 要创建自定义权限类 ,您将需要重写
BasePermission
类并实现has_permission()
方法。 This method should return True
if request is to granted access, otherwise False
. 如果请求被授予访问权限,则此方法应返回
True
,否则返回False
。
class HasWritePermissions(BasePermission):
def has_permission(self, request, view):
# grant access to non-create/update requests
if request.method not in ['POST', 'PUT', 'PATCH']:
return True
# grant access if user is a member of organization of the object
# to be modified or is a coordinator
if (organization in user.organizations) or (user_is_a_coordinator):
return True
# Otherwise don't grant access
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.