Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Login check if user is authenticated without decorator

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?

like image 710
Ospho Avatar asked Dec 06 '13 08:12

Ospho


People also ask

Is Flask login secure?

the login process seems secure. But you didn't check the potential existing user in the signup form, or existing email address. Unless this is managed by the underlying User schema. And you should require a minimal password complexity.


2 Answers

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.

like image 62
codeape Avatar answered Oct 07 '22 18:10

codeape


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'].

like image 40
flyer Avatar answered Oct 07 '22 19:10

flyer