TOP

基于django 的原始 RBAC 方案实现完整的权限控制

 用户模型视图中获取用户的当前所有权限

    @property
    def permissions(self):
        user_permissions = [perm.codename for perm in self.user_permissions.all()]
        group_permissions = []
        for group in self.groups.all():
            group_permissions += [perm.codename for perm in group.permissions.all()]
        return set(user_permissions + group_permissions)

 实现完整权限组件

# 租户管理权限控制
class AdminRBACPermission(permissions.BasePermission):

    # 行为级权限
    def has_permission(self, request, view):
        user = request.user
        if user.is_superuser:
            return True

        # 基于视图转换为当前具体的权限
        action_map = {
            "list": "view_",
            "retrieve": "view_",
            "destroy": "delete_",
            "create": "add_",
            "update": "change_",
        }
        permit = f"{action_map[view.action]}{view.queryset.model._meta.model_name}"
        if permit not in user.permissions:
            return False
        return True

 视图中具体使用

class XXXModelViewSet(ModelViewSet):
    queryset = xxx.objects.all()
    permission_classes = (AdminRBACPermission,)
    ....
    ordering_fields = ("id",)
    ordering = ("id",)

 

posted @ 2023-05-18 21:16  羊驼之歌  阅读(90)  评论(0编辑  收藏  举报