0

When I place the PermissionRequiredMixin as the most left paramenter, my requests get forwarded to the login URL even though the request is coming from an already authenticated user.

class ExampleViewSet(PermissionRequiredMixin, viewsets.ModelViewSet):
    permission_required = ('example.example_view',)

When I place the PermissionRequiredMixin after the ModelViewSet the authenticated user is detected, however, the permission_required is ignored, and every user without the permission is allowed as well. And this answer suggested, that this is caused by the placement of the parameter, which leads to the first problem.

class ExampleViewSet(viewsets.ModelViewSet, PermissionRequiredMixin):
    permission_required = ('example.example_view',)

How do I solve this problem?

Tanne
  • 59
  • 7

1 Answers1

1

It is not a problem. Order of inheritance classes is important. View base class have to set at last position. Mixins by theirs positions can override some function of the django view. The ordering of overriding function by the child class is in part defined by this ordering. First parent in the order will be called at first. In your case, if you put a breakpoint in your PermissionRequiredMixin, you will see that python does not pass in it when you call your page

You can read some links as:

Lucas Grugru
  • 1,664
  • 1
  • 4
  • 18
  • Thank you for explaining the importance of order of inheritance. But this leads to my view not recognizing the logged in user. Do you know how to solve this issue? – Tanne Sep 18 '22 at 11:59
  • Miss some informations for responding about your first problem. Your code is an example code, not real. dificult to help. You are using PermissionRequiredMixin from Django with ModelViewSet from DjangoRestFramework ? THere is a problme at this point if it is the case. DRF use authtoken for authenticating user. – Lucas Grugru Sep 18 '22 at 12:06
  • The Login is handled by the LDAPBackedAuthentication and the permissions are assigned in the django admin page. `user_obj = authenticate(username=request.data['username'], password=request.data['password']) login(request, user_obj, backend='django_auth_ldap.backend.LDAPBackend')` Yes I am using the Mixin from Django and the ModelViewSet from rest_framework.viewsets. – Tanne Sep 18 '22 at 12:13
  • I think you cannot mix the permissionrequiredmixin and viewset from drf. You have to read the drf docs about authetnication and follow them : https://www.django-rest-framework.org/api-guide/authentication/ – Lucas Grugru Sep 18 '22 at 12:28