简体   繁体   中英

Flask - How to redirect to login page if the current user is not authenticated?

My load_user function is like:

@login_manager.user_loader
def load_user(user_id):
    u = None
    # user_id is represented as a json-formatted string
    try:
        user = json.loads(user_id)
        u = load_user_from_backend(user.get('user_id'), user.get('password'))
    except:
        return None
    return u

I want the current user to be redirected back to the login page when laod_user return a None value. How do I achieve this? Thanks.

Nothing that an if statement can't handle. Certainly not the best approach to handle user authentication, though.

result = load_user(user_id)
if result is None:
    return redirect(url_for('login'))

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