python - 权限混入 Django REST ListCreateAPIView

标签 python django django-rest-framework mixins django-generic-views

如果我可能有错误的代码,我很抱歉,但我并没有真正做太多的 django 休息。我想检测 django 内置用户模型的权限。我向用户模型添加了权限,但由于某种原因 has_perm 不起作用。我改为使用 user_objects.all() 并检测权限对象是否存在。如果用户没有权限,我想返回错误 400: Unauthorized。

这是我当前的解决方案(不起作用):

class ProgramListCreateView(PermissionRequiredMixin,ListCreateAPIView):
    permission_required = Permission.objects.get(name="Can CRUD")
    permission_classes = (IsAuthenticated,)
    queryset = Program.objects.all()
    serializer_class = ProgramSerializer

    def check_user(self,request):
        if self.permission_required in request.user.user_permissions.all():
            return True
        return Response(status=400)

当我在未经许可的情况下发送带有用户 token 的 json 时,它仍然会创建对象

这是我的混音:

 class PermissionRequiredMixin(object):
    user_check_failure_path = 'auth_login'
    permission_required = None

    def check_user(self, user):
        return user.has_perm(self.permission_required)

注意:由于某种原因,has_perm 总是返回 false,即使我使用 user.user_permissions.add(permission_object) 添加它

最佳答案

听起来您正在尝试验证特定用户是否有权访问您的 APIView

您可以简单地使用DjangoModelPermissions read more

class ProgramListCreateView(ListCreateAPIView):
    permission_classes = (IsAuthenticated, DjangoModelPermissions)
    ...

您还可以使用自定义权限read more

from rest_framework import permissions

class UserPermission(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        '''
         Object-level permission to only allow user model manipulation
        '''

        # IF you  would like to allow GET, HEAD or OPTIONS requests,
        if request.method in permissions.SAFE_METHODS:
            return True

        # check if user is owner
        return request.user == obj

使用

from custom_permission import UserPermission

class ProgramListCreateView(ListCreateAPIView):
    permission_classes = (UserPermission, )
    ...

如果您想在全局范围内授予您的权限,您可以将其包含在您的settings.py中

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.DjangoModelPermissions',
    )
}

关于python - 权限混入 Django REST ListCreateAPIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47185334/

相关文章:

python - python 3打印语法错误

python - 401 客户端错误 : Unauthorized for url

python - 将 csv 中的 unicode 转换为纯文本的最佳方法?

reactjs - Tauri 应用程序 api 请求被 cors 阻止,其 api 是使用 django rest 框架构建的

python - 在 Sanic 路由参数中指定 bool 值

python - 在我自己的 View 中使用 django PasswordResetView 功能

python - Django 读取/上传 CSV

javascript - react 错误: Target Container is not a DOM Element

django - 如何在 django Rest 框架中使用自定义错误代码抛出自定义异常并覆盖异常响应中的默认字段

python - Django 错误 __init__() 采用 1 个位置参数,但给出了 2 个