Django Rest Framework authentication - how to implement custom decorator

249 views
Skip to first unread message

Tim Nelson

unread,
Jun 30, 2014, 10:38:08 AM6/30/14
to django-res...@googlegroups.com
I am trying to implement TokenAuthentication using the Rest Framework, but it seems that I can't add my own custom decorators to my ViewSets because they are evaluated BEFORE the authentication.  Consider this:

    from django.utils.decorators import method_decorator
    from django.http.response import HttpResponseForbidden
    
    def require_staff(View):
        def staffOnly(function):
            def wrap(request, *args, **kwargs):
                if request.user.is_active and request.user.is_staff:
                    return function(request, *args, **kwargs)
                else:
                    return HttpResponseForbidden()
            return wrap
    
        View.dispatch = method_decorator(staffOnly)(View.dispatch)
        return View

When I try to implement this, it seems the decorator code fires first, so the authentication is never run.

    @require_staff
    class CustomerViewSet(ModelViewSet):
        model = Customer
    
        filter_class = CustomerFilter
        filter_backends = (DjangoFilterBackend,)

Since request.user is never set, introducing the decorator breaks authentication.

Am I missing something here, or what is the proper way to implement this customization?

Tim Nelson

unread,
Jun 30, 2014, 7:04:47 PM6/30/14
to django-res...@googlegroups.com
It has been said that I should DRF Permissions for this, does that make sense?

Zoltan Szalai

unread,
Jul 1, 2014, 3:55:20 AM7/1/14
to django-res...@googlegroups.com
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages