Search code examples
pythondjangodjango-rest-framework

Django (DRF): How can I apply authentication on this class-based view?


In my Django project I have two User Groups:

  1. Manager
  2. Employee

Now I'm trying to build a class-based view that returns all managers. However, it's only supposed to be accessible to managers. If an employee or an anonymous user attempts to access it, it's supposed to return a 403-HTTP-Status code. I've built the class-based view so far and for simplicity it extends generics.ListAPIView. But I can't find a way to apply the desired authentication.

I have removed the "Can view group" and "Can view user" permissions from the Employee group, so no employee can view the managers. I've tried several permission_classes, but everytime I sent a GET-request containing an employee's token via Insomnia, it returned the managers instead of a 403-Status code. Help is greatly appreciated.

Here's the code of the view:

class ViewManager(generics.ListAPIView):
    permission_classes = [DjangoModelPermissions]
    group = Group.objects.get(name='Manager')
    users = group.user_set.all()
    queryset = users
    serializer_class = ManagerSerializer

Solution

  • To give access permission on a view to a specific group name, the command you could use is:

    def my_view(request):
       if request.user.groups.filter(name='Manager').exists(): 
          print("User is Manager")
    

    You can make a custom permission class:

    from rest_framework import permissions
    from django.contrib.auth.models import Group
    
    class IsManager(permissions.BasePermission):
        def has_permission(self, request, view):
            if not request.user.is_authenticated: # Exclude anonymous users
                return False
            return request.user.groups.filter(name='Manager').exists()
    

    and you could use it like this:

    class ViewManager(generics.ListAPIView):
        permission_classes = [IsManager]
        ...