如何实现动态创建具有不同端点集的权限组 Django Rest Framework

问题描述

在我的项目中,我有很多端点视图(APIViews、ViewSets)。现在我为所有这些设置了权限,其中一些是认的(例如 AllowAny),一些是自定义创建的:

permission_classes = (IsUserHaveSomePermission,)

现在我想实现一些灵活的系统,这将允许我为每个用户指定一组允许的端点,例如:

在前端,我想选择一些用户并有一个与项目端点对应的复选框列表。

enter image description here

这只是一个乌托邦式的解决方案,可能会更改一些细节,但主要问题是如何制作类似的东西,以便管理员基本上可以动态更改用户允许的端点/视图列表? 提前致谢

解决方法

这个方案可以通过存储用户是否有权限访问当前的请求方法和请求路径来实现。

创建一个新的数据库模型,用于存储用户、请求方法和请求路径。假设模型的名称是 RequestPermission

您可以存储表示 url 的常量而不是路径,以便您以后可以灵活地编辑路径。这个常量可以是 django 支持的 url name

class RequestPermission(models.Model):
    user = user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='request_permissions')
    method = models.CharField(max_length=10)
    path_name = models.CharField(max_length=200)

创建自定义权限类:

class IsUserResuestAllowed(permissions.BasePermission):

    def has_permission(self,request,view):
        user = request.user
        # you can choose how to get the path_name from the path
        path_name = get_path_name(request.path)
        return RequestPermission.objects.filter(user=user,method=request.method,path_name=path_name).exists()

现在你可以在休息框架设置中使用这个类作为默认权限类,或者在每个视图中使用它。