Solution
from flask import (
redirect,
session,
url_for
)
from functools import wraps
# ...
def is_authenticated():
username = session.get('username')
return username and len(username.strip()) > 0
def login_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not is_authenticated():
return redirect(url_for('login'))
return f(*args, **kwargs)
return wrapper
# Add the state query function to the jinja context.
app.jinja_env.globals.update(is_authenticated=is_authenticated)
@app.route('/login', methods=['GET', 'POST'])
def login():
# your login code here!
@app.route('/secret')
@login_required
def secret():
return 'You are logged in.'
@app.route('/public')
def public():
if is_authenticated():
return 'User is authenticated'
return 'User is not authenticated'
{% if is_authenticated() %}
User is authenticated.
{% else %}
User is not authenticated.
{% endif %}