2

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?

2 Answers 2

3

You should do something like this...

@app.before_request
def before_request():
    try:
        g.user = User.query.filter_by(username=session['username']).first()
    except Exception:
        g.user = None

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

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks. I have my views split up into multiple files. Could I put this code in views/__init__.py or something?
Yep. I put code like this in "hooks.py" - see my HelloFlask sample here: github.com/fogleman/HelloFlask
+1... my solution was going to be much, much uglier than that.
I'm a bit confused what code should go where, and how to call it. So in init.py I put the @app.before_request decorator and function, then in my view file, within a function, what do I call? I took a look at your source on github but couldn't piece it together -- an example with multiple files would be really appreciated
In your view modules, just do from flask import g and you can access g.user
|
1

You can also have a look in Flask-Login. Maybe you will find something interesting there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.