I’m looking to authenticate users every time a page is accessed in my application.
I wrote a session handling class for my web app. It’s called like this:
s = Session(request.cookies.get('session_id'))
s.isValid()
>> True #The user is logged in
s.user_id
>> 21 #The ID of the user currently logged in.
u = User(s.user_id)
I’d like to include this logic into a global file that’s called everytime a web page is accessed. This way from within my view handlers I can check if a user is logged in and access basic user information.
As an example, I’d like to do something like this:
@app.route('/profile')
def profile():
if logged:
render_template('edit-profile.html',
first_name=u.first_name)
else:
render_template('profile.html')
Is this possible? Where would the code go (which file?) What would it look like?
You should do something like this…
The login page would set the username field in the session. Then on each page load this code is executed. You can access g.user in all of your views and templates.
http://flask.pocoo.org/docs/api/#flask.Flask.before_request