python - 同时使用组和个人权限

标签 python django python-3.x django-permissions

在 Django 中,我创建了一个包含各种 用户的系统。使用 django.auth 我还创建了 permission groups 并为每个组关联了适当的应用程序权限。

这对于基于角色的访问非常有用,但现在我有一个要求,我还需要能够从组中的特定用户中删除个人权限。这意味着我需要组权限,但同时这些组权限可以取消分配给单个用户。

使用 Django 组这似乎无法直接实现,因为权限是从单个用户中抽象出来的。

我怎样才能做到这一点?

我正在将所有内容更改为个人用户权限,但这对客户来说似乎有点乏味,因为他们必须为每个新用户手动设置权限,我希望有人知道更好的方法。

最佳答案

此解决方案只需要在我的 User 模型中使用 ManyToMany 字段来保存已撤销的权限和自定义后端身份验证。

用户:

revoked_permissions = models.ManyToManyField(权限,blank=True)

身份验证后端:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import Permission


class UsersAuthenticationBackend(ModelBackend):
    def _get_revoked_perms(self, user_obj):
        if user_obj.is_superuser or user_obj.is_admin:
            revoked_perms = Permission.objects.none()
        elif hasattr(user_obj, 'revoked_permissions'):
            revoked_perms = getattr(user_obj, 'revoked_permissions').values_list('content_type__app_label', 'codename')
        else:
            revoked_perms = Permission.objects.none()

        revoked_perms = ["{}.{}".format(perm[0], perm[1]) for perm in revoked_perms]
        return revoked_perms

    def has_perm(self, user_obj, perm, obj=None):
        if not user_obj.is_active:
            return False

        revoked_perms = self._get_revoked_perms(user_obj)
        all_perms = self.get_all_permissions(user_obj)
        allowed_perms = [p for p in all_perms if not p in revoked_perms]

        return perm in allowed_perms

    def has_module_perms(self, user_obj, app_label):
        if not user_obj.is_active:
            return False

        revoked_perms = self._get_revoked_perms(user_obj)
        all_perms = self.get_all_permissions(user_obj)
        allowed_perms = [p for p in all_perms if not p in revoked_perms]

        for perm in allowed_perms:
            if perm[:perm.index('.')] == app_label:
                return True
        return False

设置.py:

AUTHENTICATION_BACKENDS = [
    "apps.users.backends.UsersAuthenticationBackend"
]

使用它,我现在能够设置整体组权限,然后还可以单独撤销特定用户的权限。

关于python - 同时使用组和个人权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56711040/

相关文章:

python - Scikit train_test_split 按指数

django - 如何删除 Flutter 中的 "XMLHttpRequest error"? (Django 后端,Flutter 前端)

python - celery django解释

python - Adobe Acrobat DC 和 Python 自动化

python - Try/Except,不返回 except

python - 基本 Python 列表练习

python - 渲染表单字段随机时间

python - pip3 install Flask-MongoEngine 安装失败

python - 使用 BeautifulSoup、Python、Regex 在 Javascript 函数中获取变量

python - html.parser 奇怪的行为