简体   繁体   中英

Flask - Decorator for Basic Auth

I'm trying to create decorator which will redirect to specified path if not logged in.

Decorator:

def secured(path):
    @wraps(path)
    def wrapper(f, *args, **kwargs):
        if 'loggedin' in session:
            if session.get('loggedin'):
                return f(*args, **kwargs)
            else:
                redirect(path)
        else:
            session['loggedin'] = False
            redirect(path)
    return wrapper

Login function:

def val_cred(username, password):
    return username == 'login' and password == 'password'
@app.route('/login', methods=['POST'])
def login():
    auth = request.authorization
    if not auth.username or not auth.password or not val_cred(auth.username, auth.password):
        return 'bad credentials', 401
    session['loggedin'] = True
    return redirect("/hello")

Example of secured path:

@app.route('/hello')
@secured('/')
def hello():
    return 'you are logged in'

Before I created decorator with static path which takes no arguments and it worked well, so I thought it's syntax problem, but Flask states it's something else

Traceback (most recent call last):
  File "C:/daftcode-flask/app.py", line 31, in <module>
    @secured('/')
  File "C:/daftcode-flask/app.py", line 14, in wrapper
    if 'loggedin' in session:
  ...

    RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

How can I make it work properly?

You have an mistake in secured decorator. You forgot to add one more function inside(see: def _secured(f) ):

def secured(path):
    def _secured(f):
        @wraps(path)
        def __secured(*args, **kwargs):
            # Note! I didn't check your functionality
            if 'loggedin' in session:
                if session.get('loggedin'):
                    return f(*args, **kwargs)
                else:
                    redirect(path)
            else:
                session['loggedin'] = False
                redirect(path)
        return __secured
    return _secured

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM