简体   繁体   中英

How to catch a request in a DRF viewset?

So I have this:

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [TokenHasReadWriteScope]
    queryset = User.objects.all()
    serializer_class = UserSerializer
    entity_name = 'user'
    perm_type = {
        'POST': 'create',
        'GET': 'read',
        'PATCH': 'update',
        'DELETE': 'delete'
    }

    def check_permissions(self, request):
        user = request.user
        has_permissions = user.has_entity_permissions(
            name=self.entity_name,
            perm_type=self.perm_type[request.method]
        )
        if not has_permissions:
            raise PermissionDenied

    def create(self, request, *args, **kwargs):
        self.check_permissions(request)
        return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        self.check_permissions(request)
        return super().list(request, *args, **kwargs)

   def update(self, request, *args, **kwargs):
        self.check_permissions(request)
        return super().update(request, *args, **kwargs)

I have a custom security server, the purpose is to centralize all the apps of the company, so when we have a new employee, we can give him access to the differents apps with different permissions in every entity and their properties from a single app instead of creating the user and give him permissions in every app.

So basically in the "check_permission" function I check for this, depending in the request method (perm_type associated a request method with a permission (CRUD))

The question: there is a way to catch the request before enters into list, retrive, create, update or delete (Middlewears dont work because i need to know the entity type or endpoint, thats why I set the entity_name variable, but if you have a better idea is welcome)

Why overriding your action method when you already have check_permissions implemented by APIView class? (which ModelViewSet inherits from)

Simply add your peace of code by overriding it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM