Getting a redirect loop for admin_only decorator

I made this decorator which results in an infinite redirection loop.

The problem is this:

args[0].redirect(users.create_login_url(args[0].request.path))

      

This appears to be a perfectly valid URL. So why doesn't it redirect?

def admin_only(handler, *args):

    def redirect_to_login(*args, **kwargs):
        return args[0].redirect(users.create_login_url(args[0].request.path))

    user = users.get_current_user()
    if user:
        if authorized(user):
            return handler(args[0])
        else:
            logging.warning('An unauthorized user has attempted to enter an authorized page')
            return redirect_to_login
    else:
        return redirect_to_login

      

+1


source to share


4 answers


It seems that you are not defining your decorator correctly.

The decorator is called only once each time you wrap a function with it; from now on, a function is called that will be called by the decorator returned . It seems that you (mistakenly) assume that the decorator function itself will be called every time.

Try something like this:



def redirect_to_login(*args, **kwargs):
    return args[0].redirect(users.create_login_url(args[0].request.path))

def admin_only(handler):
    def wrapped_handler(*args, **kwargs):    
        user = users.get_current_user()
        if user:
            if authorized(user):
                return handler(args[0])
            else:
                logging.warning('An unauthorized user has attempted '
                                'to enter an authorized page')
                return redirect_to_login(*args, **kwargs)
        else:
            return redirect_to_login(*args, **kwargs)

    return wrapped_handler

      

Note that in the above code, the decorator simply defines a new function and returns it, and the new function itself performs the appropriate checks.

+2


source


Are you sure the correct status code is being sent, you can use the Firefox HTTP Headers Add-on to check if a 301 or 303 is sent or not.



0


source


You have to use firebug or live http headers, or somesuch to see exactly what is going on here. My guess: Allowed your () function always returns false (even when the user is logged in), so it redirects to the login page, which (if the user is already logged in) immediately redirects the user back to the page that redirects. .. you get the idea.

0


source


The problem is that I am using

return args[0].redirect(users.create_logout_url(args[0].request.uri))

      

This is to go to the exit page, which is then redirected to the current page. However, my logs show that the current page thinks I am still logged in, even after the registration is complete.

This is weird since I haven't changed anything in the app users API.

0


source







All Articles