我很抱歉,如果我可能有错误的代码,但我还没有真正做django休息。我想检测来自django的内置User模型的权限。我向用户模型添加了权限,但由于某种原因,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)
当我在未经许可的情况下使用用户令牌发送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)
注意:即使我使用user.user_permissions.add(permission_object)
答案 0 :(得分:1)
听起来您正在尝试验证特定用户是否拥有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
<强> USAGE 强>
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',
)
}
答案 1 :(得分:0)
继承人我做了什么:我创建了一个扩展默认通用API视图的Mixin,我只是覆盖了put post和get函数
class MasterGenericAPIViewMixin(ListCreateAPIView, RetrieveUpdateDestroyAPIView):
codename = None
def post(self, request, *args, **kwargs):
permission = Permission.objects.get(codename=self.codename)
if permission not in request.user.user_permissions.all():
return Response(status=403, data={
"error": "not authorized to add"
})
return self.create(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
permission = Permission.objects.get(codename=self.codename)
if permission not in request.user.user_permissions.all():
return Response(status=403, data={
"error": "not authorized to edit"
})
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
permission = Permission.objects.get(codename=self.codename)
print(permission)
print(request.user)
if permission not in request.user.user_permissions.all():
return Response(status=403, data={
"error": "not authorized to delete"
})
return self.destroy(request, *args, **kwargs)
我的所有观点都扩展了这个课程