简体   繁体   English

如何使用 has_object_permission 检查用户是否可以在基于 function 的视图中访问 object

[英]How to use has_object_permission to check if a user can access an object in function based views

I have a note object which can be accessd from notes/{pk}.我有一个笔记 object 可以从 notes/{pk} 访问。 If the method is GET or a read only method I was to allow anyone access to the note as long as the note is public ( note.is_private = False )如果该方法是 GET 或只读方法,我将允许任何人访问该便笺,只要该便笺是公开的( note.is_private = False

I've implemented this as:我已将其实现为:

@api_view(['GET', 'DELETE', 'PUT'])
def detail_notes(request, pk): 
    try: 
        note = Note.objects.get(pk=pk)
    except Note.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET': 
        response = NoteSerializer(note)
        return Response(response.data)

...

If the method is PUT or DELETE I want to allow access to the note only if the current user is the owner of the note.如果方法是 PUT 或 DELETE,我希望仅当当前用户是便笺的所有者时才允许访问该便笺。 I implemented this permission (according to the docs) as follows:我实现了这个权限(根据文档)如下:

class IsOwnerOrIsPublic(BasePermission):

    def has_object_permission(self, request, view, obj): 

        user = obj.user 
        privacy = obj.is_private

        if request.method in SAFE_METHODS:
            return not privacy # is the note public and is this a read only request ? 

        return request.user == obj.user

However, when I add the @permission_classes([IsOwnerOrIsPublic]) decorator to my view the permission doesn't restrict access to an unauthorized user.但是,当我将@permission_classes([IsOwnerOrIsPublic])装饰器添加到我的视图时,权限不会限制对未经授权的用户的访问。 I'm able to view any note with a pk.我可以用 pk 查看任何笔记。

I tried explicitly calling IsOwnerOrIsPublic.has_object_permissions(), with this code in my view:我尝试使用以下代码显式调用 IsOwnerOrIsPublic.has_object_permissions():

authorized = IsOwnerOrIsPublic.has_object_permission(request, note)
    if not authorized:
        return Response(status=HTTP_401_UNAUTHORIZED)

But I get the error has_object_permission() missing 2 required positional arguments: 'view' and 'obj' (obviously), and I do not know what other arguments to pass in. For example, what is the view argument?但是我得到错误has_object_permission() missing 2 required positional arguments: 'view' and 'obj' (显然),我不知道还有什么其他的 arguments 要传入。例如,什么是 view 参数?

How do I make this permission work on this view?如何使此权限在此视图上起作用? Alternatively, how do I make this constraint work?或者,我如何使这个约束起作用?

Note that my solution is based on generic views which is more simpler to implement.请注意,我的解决方案基于更易于实现的通用视图。 Try the following view class:试试下面的视图 class:

from rest_framework import generics
from django.shortcuts import get_object_or_404
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
...
# generics.RetrieveUpdateDestroyAPIView will allow Get, put, delete
class NoteDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update, or delete note by its author
Retrieve only for readers
"""
# I'll assume you are using token authentication
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated, IsOwnerOrIsPublic,)

serializer_class = NoteSerializer

def get_object(self):
    note = get_object_or_404(Note, pk=self.kwargs['pk'])
    self.check_object_permissions(self.request, note)
    return note

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM