Flask-Login check if user is authenticated without decorator

Question:

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?

Asked By: Ospho

||

Answers:

You could refer to the example here.

When the user has logged in, set session['logged_in']=True. At the same time, you can use Flask-login API to do some configurations in case that you want to use its functionality.
When you want to check whether the user has logged in manually rather than use the Flask-login API, then check the value of session['logged_in'].

Answered By: flyer

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.

Answered By: codeape
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.