Home > Mobile >  Django rest framework : custom object permissions doesn't work
Django rest framework : custom object permissions doesn't work

Time:11-03

My problem is very simple : I'm trying to create some custom permissions for my django rest API. This is my code (permission.py) :

class UserPermissions(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj == request.user

I just want that the users can only get, delete and update their own account. The problem is that I think my code is not read by Django. I have try to always return false (without any condition) and it does nothing. I have also try to print some debug message at the beginning of the file and it's does nothing.

(My file permissions.py is at the root of my application)$

This is my user view (UserView.py) :

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by("-date_joined")
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]
    swagger_tag = ["User"]

class LoginView(KnoxLoginView):
    """
    API endpoint allowing the user to login and receive a token
    """

    permission_classes = [
        permissions.AllowAny,
    ]

    @swagger_auto_schema(request_body=AuthTokenSerializer)
    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data["user"]
        login(request, user)
        return super(LoginView, self).post(request, format=None)

CodePudding user response:

As @UtkucanBıyıklı says in their comment, you should specify the permission in the ViewSet:

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated, UserPermissions]
    swagger_tag = ['User']
  • Related