Flask-Login check if user is authenticated without decorator

flask, flask-login, python

Solution

This is very simple in flask:

from flask_login import current_user

@app.route(...)
def main_route():
    if current_user.is_authenticated:
         return render_template("main_for_user.html")
    else:
         return render_template("main_for_anonymous.html")

See the documentation on anonymous users.

Problem

From the Flask-Login docs, it's described how a user of the system can require an authenticated User-model to access a method utilising the decorator syntax: ``` from flask_login import login_required @app.route("/settings") @login_required def settings(): pass ``` Now that's all well and good, but I want to be able to examine if the user is authenticated in a method, something like this: ``` @app.route('/main/', methods=['GET', 'POST']) main_route(): if request.method == 'GET': if user_is_authenticated(): #Do the authentication here #load authenticated /main/ html template etc. pass else: #load unauthenticated /main/ html template etc. pass ... ``` The reason for this, is because it factorises the GET and POST requests rather than duplicating routes for authenticated users and unauthenticated users. How can I do this? Is it possible?

Original source