1

I've tried to implement a minimal login sysem in flask, so I defined a decorator that checks if an element from the session has a particular value, if it does, the user can't access the page wrapped by that decorator.

This is the wrapped view function:

@mustBelongToARoom
@app.route('/draw')
def draw():
    return render_template('draw.html')

And this is the decorator

def mustBelongToARoom(f):
    @wraps(f)
    def wrap_f(*args, **kwargs):
        print 'test\n'
        if session['room_name'] is None:
            return render_template(url_for('/'))
        return f(*args, **kwargs)
    return wrap_f

So, basically, if the room_name is None the user can't access the draw page. The problem is that it seems to ignore the code added by the decorator. For example, take this version of the mustBelongToARoom decorator:

   def mustBelongToARoom(f):
        @wraps
        def wrap_f(*args, **kwargs):
            print 'test\n'
            if session['room_name'] is None:
                print '[DEBUG] you are not allowed to acces this page!\n'
                return render_template(url_for('/'))
            return f(*args, **kwargs)
        return wrap_f

I'd expect to see [DEBUG] you are not allowed to acces this page!\n in the console when an user tries to acces the draw page, but it doesn't display it.

cristid9
  • 1,070
  • 1
  • 17
  • 37

1 Answers1

2

Try reversing the order you apply the decorator. The route decorator only added the draw() function and not the one returned by mustBelongToARoom, which includes your authentication scheme.

A good reference for how decorators work: How to make a chain of function decorators?

Community
  • 1
  • 1
metatoaster
  • 17,419
  • 5
  • 55
  • 66