0

I wrote an API service with Django. I have authorized the user to list only clients via django admin panel. When I enter the django admin panel with the user name I authorize, there is no problem in the authorization.

But when I access the api service, he never sees authority.

Can you help me ?

api/permissions.py

from rest_framework.permissions import BasePermission
class IsOwner(BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated
    message = "you cannot change data that you do not own !"

    def has_object_permission(self, request, view, obj):
        return (obj.user == request.user) or request.user.is_superuser

views.py

class CustomerListAPIView(ListAPIView):
    serializer_class = CustomerCreateSerializer
    permission_classes = [IsOwner]
    filter_backends = [SearchFilter]
    search_fields = ['customerName', 'customerSurname', 'customerIdentityNo']

    def get_queryset(self):
        queryset = Customer.objects.filter(user=self.request.user)
        return queryset

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
         'rest_framework.permissions.DjangoModelPermissions'
    ]
}

friends,

When I run api it does not enter "has_object_permission" at all. It only enters into "has_object_permission" when I log in from the admin panel with a user account. When I run the API, it never gets into "has_object_permission".

Fatih mzm
  • 395
  • 1
  • 7
  • 21

1 Answers1

0
  1. First, check if you got the user in the request, you can do this as I said above by adding print(request.user) in your IsOwner permission above return string.
  2. Test if you got the user in the request when you're making requests to your API (from the browser, I guess ?).
  3. If the function will prin None, then you need to add your JWT token in the Authorization header. Basically, it's how JWT works. You need to add string typically (Some codeword (JWT/Token), defined in your settings + ) in the Authorization header of the request, so the API will identify you as a particular user.
  4. You can do it from different services. For example, I usually use Postman service to test and make a request to my APIs. You can find it here: https://www.getpostman.com/

I wrote this as an answer because comment length wasn't enough.

Igor Belkov
  • 446
  • 3
  • 8