0

Django decorator has a function to manage the user, once of it is user_passes_test.

But, in my implementation i found this problem: ERR_TOO_MANY_REDIRECTS, or ‘AnonymousUser’ object is not iterable.

I need to custom the user by instancing from user models, for example:

from django.db import models
from django.contrib.auth.models import User

class Admin(models.Model):
    user = models.ForeignKey(User, related_name='user_admin')

So, in my decorator should be: (file: app_admin/utils/decorator.py)

from app_admin.models import Admin


def admin_check(user):
    """
    Return False if the user if not as admin.
    @user_passes_test(admin_check)
    """
    return Admin.objects.filter(user=user).exists()

But, i found some problem such as above. Why?

I just knew, if the @user_passes_test need required user to logged in. So, how i can do it?

from app_admin.models import Admin

def admin_check(user):
    """
    Return False if the user if not as admin.
    @user_passes_test(admin_check)
    """ 
    if user.is_authenticated():
        return Admin.objects.filter(user=user).exists()
    return False

Yeah, you just need condition to check the user is_authenticated() or yet. If not, the @user_passes_test decorator should redirecting to the login page. default is = /accounts/login/.

In the implementation, for example:

from django.contrib.auth.decorators import user_passes_test
from app_admin.utils.decorator import admin_check

@user_passes_test(admin_check)
def dashboard(request):
    #do_stuff

Hope it usefull…

Updated:

I don’t know why it still has a problem ERR_TOO_MANY_REDIRECTS if logged in as different user (not as admin), so i handle it to create custom wrapper/decorator.

from app_admin.models import Admin
from django.http import HttpResponseRedirect
def admin_required(function):  
    """
    @admin_required
    def dashboard(request):
        #do_stuff
    """
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated() and 
                Admin.objects.filter(user=request.user).exists():
            return function(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/')
    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap

More:

security django python

Your Answer

blog comments powered by Disqus