Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework object level permission on POST

I want to make sure the request.user can only issue a POST request to create a forum topic in which they are the auther. With PUT and DELETE I'm able to achieve that by using the has_object_permission but with POST I'm not able to do that, I'm guessing because the object hasn't been created yet.

class TopicPermission(IsAuthenticatedOrReadOnly):
    """
    Any user should be able to read topics but only authenticated 
    users should be able to create new topics. An owner or moderator 
    should be able to update a discussion or delete.
    """
    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True

        # Instance must have an attribute named `author` or moderator
        return obj.author == request.user or request.user.forum_moderator

How would I go about verifying request.user == obj.author in POST requests?

like image 280
awwester Avatar asked Apr 25 '15 15:04

awwester


1 Answers

I ended up doing the validation in the viewset instead of the serializer:

class TopicViewSet(viewsets.ModelViewSet):
    permission_classes = (TopicPermission, )
    queryset = Topic.objects.all()
    serializer_class = TopicSerializer

    def create(self, request, *args, **kwargs):
        """
        verify that the POST has the request user as the obj.author
        """
        if request.data["author"] == str(request.user.id):
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=201, headers=headers)
        else:
            return Response(status=403)
like image 94
awwester Avatar answered Oct 14 '22 00:10

awwester