Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom decorator for class based views in django rest framework

I have few users in my application say A, B and C. Once any type of user authenticates I don't want this user to access all my API's

So for function based views I have implemented a decorator:

from functools import wraps

from rest_framework import status
from rest_framework.response import Response


def permit(user_type):
    class Permission(object):

        def __init__(self, view_func):
            self.view_func = view_func
            wraps(view_func)(self)

        def __call__(self, request, *args, **kwargs):

            if request.user.user_type in user_type:
                return self.view_func(request, *args, **kwargs)
            else:
                return Response(status=status.HTTP_403_FORBIDDEN)

    return Permission

so suppose I want one of my API's to be accesed to A type of Users I do:

@permit(["A"])
def myview(request):
    # return some reponse

This works fine but I am having trouble to convert this for class based views.

I tried to decorate the dispatch method:

@method_decorator(permit_only(["A",]))
def dispatch(self, request, *args, **kwargs):
    return super(UserList, self).dispatch(*args, **kwargs)

But I get an error:

AssertionError(u'.accepted_renderer not set on Response',)
like image 601
dnit13 Avatar asked Oct 31 '22 05:10

dnit13


1 Answers

One of the workarounds I came to for this is to subclass the IsAuthenticated class and pass it to permission_classes in class based views or as a decorator to function based views

class PermA(IsAuthenticated):

    def has_permission(self, request, view):
        resp = super(PermA, self).has_permission(request, view)
        return getattr(request.user, "user_type", None) == "A" and resp
like image 196
dnit13 Avatar answered Nov 15 '22 06:11

dnit13