How to return 403 to ViewSet instead of 404

I am working on an API and have this ViewSet:

class ProjectViewSet(viewsets.ModelViewSet):
    # API endpoint that allows projects to be viewed or edited.
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    authentication_classes = used_authentication_classes
    permission_classes = (IsOwner,)

    @detail_route(methods=['get'])
    def functions(self, request, pk=None):
        project = self.get_object()
        if project is None:
            return Response({'detail': 'Missing project id'}, status=404)
        return Response([FunctionSerializer(x).data for x in Function.objects.filter(project=project)])

A permission system is attached to this API. Permissions work fine for a single resource. But when I call api/projects, which should return all the projects that the user has access to, it actually returns all the projects, regardless of whether the user should be able to get a specific project in the list or not.

Therefore, I rewrote the method get_querysetto return only those projects that the user has access to:

def get_queryset(self):
    if self.request.user.is_superuser or self.request.user.is_staff:
        return Project.objects.all()
    else:
        return Project.objects.filter(user=self.request.user.user)

This works, but now the API returns 404 instead of 403 when I request a specific resource that I do not have access to.

, , , , undefined, , . , .

- , 403, , , , ?

+4
1

@Alasdair , 404 , 403, :

def get_queryset(self):
    user = self.request.user
    allow_all = user.is_superuser or user.is_staff
    if self.action == 'list' and not allow_all:
        return Project.objects.filter(user=user)
    return Project.objects.all()
+4

Source: https://habr.com/ru/post/1696270/


All Articles