django - 如何构建 Django 权限以拥有多个类别的权限组?
问题描述
我想使用 Django Rest Framework 为 API 提供多层权限,我怎样才能最好地实现这一点?
具体来说,我拥有的三类授权是:
- 角色:模型级别的访问权限,例如管理员和不同的客户类型。
- GroupAccess:按对象、组访问,例如一组用户。
- 敏感度:每个对象,敏感信息的附加标签。
后两个类别同样适用于所有模型,不需要为每个模型提供单独的权限会很好。
想法1:
为从标准 django auth 组继承的每个类别创建一个模型。将这些作为代理组执行,在我的代码中逻辑上有所不同,但尽可能与标准授权一致。然后使用 django-guardian 启用对象级权限。
想法2:
对角色使用标准组,并根据这些组分配模型级别的权限。对于对象级权限,在 Django Rest Framework 中编写自定义权限类来检查用户的对象级权限。
解决方案
我最近设计了这样一个架构,所以我想到的第一件事是这样的:
- 角色:您可以通过添加角色级别的选项来覆盖 django 的内置 AbstractUser 类,例如:
# models.py
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""Custom user model with an extra type field"""
SUPER_USER = 1
OTHER_ROLE = 2
SOME_OTHER_ROLE = 3
USER_TYPE_CHOICES = (
(SUPER_USER, 'Super user'),
(OTHER_ROLE, 'Other role'),
(SOME_OTHER_ROLE, 'Some other role'),
)
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
# -------------------------------------------------------------------------
# Don't forget to set this User model as your default model
# settings.py
AUTH_USER_MODEL = 'my_app.User'
- You can get use of django's built-in
Group
model and put a ForeignKey to yourTeam
models and do object-level permission manually.
# models.py
from django.contrib.auth.models import Group
from django.db import models
def Team(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
# -------------------------------------------------------------------------
# You can do object-level permission per group by
# ...
if team.group in permitted_groups:
# permission granted
pass
else:
# permission not granted
pass
# ...
- You can define a
Tag
model and add as ManyToManyField to your sensitive information model. Similar to the second solution above, you can manually do object-level permission during runtime by relying on your current information's tags.
推荐阅读
- laravel - Laravel/PHPUnit:如何模拟方法(或构造函数控制器本身)的参数?
- mysql - MySQL查询具有不同字段的两个表
- nativescript - 在 nativescript 插件中使用 worker 的问题
- java - Java开关控制中的局部变量
- javascript - 联系表格(提交成功并重置)
- django - 如果只有另一个模型的字段包含某个值并且这两个模型具有外键,我如何过滤模型的对象
- php - Laravel 碳解析日期
- mariadb - ProxySQL 给我错误 Access denied for user
- android - Android Studio 在名称上给我一个错误,说它必须是 log.v 中的“throwable tr”。有人可以解释一下为什么
- arrays - 如何在arduino的char数组中放置变量?