2012-06-09T06:44:24Z

The Flask Mega-Tutorial, Part V: User Logins

(Great news! There is a new version of this tutorial!)

This is the fifth article in the series in which I document my experience writing web applications in Python using the Flask microframework.

The goal of the tutorial series is to develop a decently featured microblogging application that demonstrating total lack of originality I have decided to call microblog.

NOTE: This article was revised in September 2014 to be in sync with current versions of Python and Flask.

Here is an index of all the articles in the series that have been published to date:

Recap

In the previous chapter of the series we created our database and learned how to populate it with users and posts, but we haven't hooked up any of that into our app yet. And two chapters ago we've seen how to create web forms and left with a fully implemented login form.

In this article we are going to build on what we learned about web forms and databases and write our user login system. At the end of this tutorial our little application will register new users and log them in and out.

To follow this chapter along you need to have the microblog app as we left it at the end of the previous chapter. Please make sure the app is installed and running.

An Update Regarding the State of OpenID

It's been more than three years ago that I wrote this article. Back then OpenID seemed like a nice authentication method that was gaining a lot of traction, but in 2015 there are better alternatives, and OpenID is not as widely deployed as it used to be.

I do not have plans to update this tutorial in the near future, as I have written extensively about other authentication methods elsewhere. When you follow this tutorial keep in mind that Google, which was the most prominent OpenID provider in 2012, has dropped support for this protocol completely. My recommendation is to use a Yahoo account to test OpenID in this tutorial. I have a few personal projects that still use OpenID and I use Yahoo as a provider with good results.

As far as real-world authentication, I do not think it is a good idea to use OpenID, given the lack of support. I have a few resources for you that can help you create a more modern authentication experience:

  • My Flask book covers a traditional username and password implementation, complete with user registration, password reminders and resets.
  • My OAuth Authentication with Flask blog article describes in detail how to implement OAuth authentication, which has much wider support than OpenID. With this method you can implement "Login with Facebook" type functionality. The article demonstrates how to login with Facebook and Twitter. Others, such as Google, LinkedIn, etc. can be implemented easily with the same technique.

Configuration

As in previous chapters, we start by configuring the Flask extensions that we will use. For the login system we will use two extensions, Flask-Login and Flask-OpenID. Flask-Login will handle our users logged in state, while Flask-OpenID will provide authentication. These extensions are configured as follows (file app/__init__.py):

import os
from flask_login import LoginManager
from flask_openid import OpenID
from config import basedir

lm = LoginManager()
lm.init_app(app)
oid = OpenID(app, os.path.join(basedir, 'tmp'))

The Flask-OpenID extension requires a path to a temp folder where files can be stored. For this we provide the location of our tmp folder.

Python 3 Compatiblity

Unfortunately version 1.2.1 of Flask-OpenID (the current official version) does not work well with Python 3. Check what version you have by running the following command:

$ flask/bin/pip freeze

If you have a version newer than 1.2.1 then the problem is likely resolved, but if you have 1.2.1 and are following this tutorial on Python 3 then you have to install the development version from GitHub:

$ flask/bin/pip uninstall flask-openid
$ flask/bin/pip install git+git://github.com/mitsuhiko/flask-openid.git

Note that you need to have git installed for this to work.

Revisiting our User model

The Flask-Login extension expects certain properties and methods to be implemented in our User class. Outside of these there are no requirements for how the class has to be implemented.

Below is our Flask-Login friendly User class (file app/models.py):

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    posts = db.relationship('Post', backref='author', lazy='dynamic')

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        try:
            return unicode(self.id)  # python 2
        except NameError:
            return str(self.id)  # python 3

    def __repr__(self):
        return '<User %r>' % (self.nickname)

The is_authenticated property has a misleading name. In general this method should just return True unless the object represents a user that should not be allowed to authenticate for some reason.

The is_active property should return True for users unless they are inactive, for example because they have been banned.

The is_anonymous property should return True only for fake users that are not supposed to log in to the system.

Finally, the get_id method should return a unique identifier for the user, in unicode format. We use the unique id generated by the database layer for this. Note that due to the differences in unicode handling between Python 2 and 3 we have to provide two alternative versions of this method.

User loader callback

Now we are ready to start implementing the login system using the Flask-Login and Flask-OpenID extensions.

First, we have to write a function that loads a user from the database. This function will be used by Flask-Login (file app/views.py):

@lm.user_loader
def load_user(id):
    return User.query.get(int(id))

Note how this function is registered with Flask-Login through the lm.user_loader decorator. Also remember that user ids in Flask-Login are always unicode strings, so a conversion to an integer is necessary before we can send the id to Flask-SQLAlchemy.

The login view function

Next let's update our login view function (file app/views.py):

from flask import render_template, flash, redirect, session, url_for, request, g
from flask_login import login_user, logout_user, current_user, login_required
from app import app, db, lm, oid
from .forms import LoginForm
from .models import User

@app.route('/login', methods=['GET', 'POST'])
@oid.loginhandler
def login():
    if g.user is not None and g.user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        session['remember_me'] = form.remember_me.data
        return oid.try_login(form.openid.data, ask_for=['nickname', 'email'])
    return render_template('login.html', 
                           title='Sign In',
                           form=form,
                           providers=app.config['OPENID_PROVIDERS'])

Notice we have imported several new modules, some of which we will use later.

The changes from our previous version are very small. We have added a new decorator to our view function. The oid.loginhandler tells Flask-OpenID that this is our login view function.

At the top of the function body we check if g.user is set to an authenticated user, and in that case we redirect to the index page. The idea here is that if there is a logged in user already we will not do a second login on top.

The g global is setup by Flask as a place to store and share data during the life of a request. As I'm sure you guessed by now, we will be storing the logged in user here.

The url_for function that we used in the redirect call is defined by Flask as a clean way to obtain the URL for a given view function. If you want to redirect to the index page you may very well use redirect('/index'), but there are very good reasons to let Flask build URLs for you.

The code that runs when we get a data back from the login form is also new. Here we do two things. First we store the value of the remember_me boolean in the flask session, not to be confused with the db.session from Flask-SQLAlchemy. We've seen that the flask.g object stores and shares data though the life of a request. The flask.session provides a much more complex service along those lines. Once data is stored in the session object it will be available during that request and any future requests made by the same client. Data remains in the session until explicitly removed. To be able to do this, Flask keeps a different session container for each client of our application.

The oid.try_login call in the following line is the call that triggers the user authentication through Flask-OpenID. The function takes two arguments, the openid given by the user in the web form and a list of data items that we want from the OpenID provider. Since we defined our User class to include nickname and email, those are the items we are going to ask for.

The OpenID authentication happens asynchronously. Flask-OpenID will call a function that is registered with the oid.after_login decorator if the authentication is successful. If the authentication fails the user will be taken back to the login page.

The Flask-OpenID login callback

Here is our implementation of the after_login function (file app/views.py):

@oid.after_login
def after_login(resp):
    if resp.email is None or resp.email == "":
        flash('Invalid login. Please try again.')
        return redirect(url_for('login'))
    user = User.query.filter_by(email=resp.email).first()
    if user is None:
        nickname = resp.nickname
        if nickname is None or nickname == "":
            nickname = resp.email.split('@')[0]
        user = User(nickname=nickname, email=resp.email)
        db.session.add(user)
        db.session.commit()
    remember_me = False
    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me', None)
    login_user(user, remember = remember_me)
    return redirect(request.args.get('next') or url_for('index'))

The resp argument passed to the after_login function contains information returned by the OpenID provider.

The first if statement is just for validation. We require a valid email, so if an email was not provided we cannot log the user in.

Next, we search our database for the email provided. If the email is not found we consider this a new user, so we add a new user to our database, pretty much as we have learned in the previous chapter. Note that we handle the case of a missing nickname, since some OpenID providers may not have that information.

After that we load the remember_me value from the Flask session, this is the boolean that we stored in the login view function, if it is available.

Then we call Flask-Login's login_user function, to register this is a valid login.

Finally, in the last line we redirect to the next page, or the index page if a next page was not provided in the request.

The concept of the next page is simple. Let's say you navigate to a page that requires you to be logged in, but you aren't just yet. In Flask-Login you can protect views against non logged in users by adding the login_required decorator. If the user tries to access one of the affected URLs then it will be redirected to the login page automatically. Flask-Login will store the original URL as the next page, and it is up to us to return the user to this page once the login process completed.

For this to work Flask-Login needs to know what view logs users in. We can configure this in the app's module initializer (file app/__init__.py):

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'

The g.user global

If you were paying attention, you will remember that in the login view function we check g.user to determine if a user is already logged in. To implement this we will use the before_request event from Flask. Any functions that are decorated with before_request will run before the view function each time a request is received. So this is the right place to setup our g.user variable (file app/views.py):

@app.before_request
def before_request():
    g.user = current_user

This is all it takes. The current_user global is set by Flask-Login, so we just put a copy in the g object to have better access to it. With this, all requests will have access to the logged in user, even inside templates.

The index view

In a previous chapter we left our index view function using fake objects, because at the time we did not have users or posts in our system. Well, we have users now, so let's hook that up:

@app.route('/')
@app.route('/index')
@login_required
def index():
    user = g.user
    posts = [
        { 
            'author': {'nickname': 'John'}, 
            'body': 'Beautiful day in Portland!' 
        },
        { 
            'author': {'nickname': 'Susan'}, 
            'body': 'The Avengers movie was so cool!' 
        }
    ]
    return render_template('index.html',
                           title='Home',
                           user=user,
                           posts=posts)

There are only two changes to this function. First, we have added the login_required decorator. This will ensure that this page is only seen by logged in users.

The other change is that we pass g.user down to the template, instead of the fake object we used in the past.

This is a good time to run the application.

When you navigate to http://localhost:5000 you will instead get the login page. Keep in mind that to login with OpenID you have to use the OpenID URL from your provider. You can use one of the OpenID provider links below the URL text field to generate the correct URL for you.

As part of the login process you will be redirected to your provider's web site, where you will authenticate and authorize the sharing of some information with our application (just the email and nickname that we requested, no passwords or other personal information will be exposed).

Once the login is complete you will be taken to the index page, this time as a logged in user.

Feel free to try the remember_me checkbox. With this option enabled you can close and reopen your web browser and will continue to be logged in.

Logging out

We have implemented the log in, now it's time to add the log out.

The view function for logging out is extremely simple (file app/views.py):

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

But we are also missing a link to logout in the template. We are going to put this link in the top navigation bar which is in the base layout (file app/templates/base.html):

<html>
  <head>
    {% if title %}
    <title>{{ title }} - microblog</title>
    {% else %}
    <title>microblog</title>
    {% endif %}
  </head>
  <body>
    <div>Microblog:
        <a href="{{ url_for('index') }}">Home</a>
        {% if g.user.is_authenticated %}
        | <a href="{{ url_for('logout') }}">Logout</a>
        {% endif %}
    </div>
    <hr>
    {% with messages = get_flashed_messages() %}
    {% if messages %}
    <ul>
    {% for message in messages %}
        <li>{{ message }} </li>
    {% endfor %}
    </ul>
    {% endif %}
    {% endwith %}
    {% block content %}{% endblock %}
  </body>
</html>

Note how easy it is to do this. We just needed to check if we have a valid user set in g.user and if we do we just add the logout link. We have also used the opportunity to use url_for in our template.

Final words

We now have a fully functioning user login system. In the next chapter we will be creating the user profile page and will be displaying user avatars on them.

In the meantime, here is the updated application code including all the changes in this article:

Download microblog-0.5.zip.

See you next time!

Miguel

217 comments

  • #51 Blz said 2013-05-07T12:02:21Z

    I would like to ask if you plan to add a post about authenticate with LDAP instead of OpenID?

  • #52 Miguel Grinberg said 2013-05-07T15:57:35Z

    @Blz: No, I was not planning to support LDAP, but that would be a simple change. You would still use Flask-Login for this, but you will drop Flask-OpenID. The login view will need to be reimplemented using the LDAP module (see http://www.grotan.com/ldap/python-ldap-samples.html for an example usage).

  • #53 Matt said 2013-05-09T17:28:43Z

    Hello, Miguel.

    Everything was working fine in past tutorials. I have normally logged in using google open id, however since I erased my app.db file (and created the db again) I'm not able to log in with openids anymore. Tests run flawlessly, but I'm getting this error on console when trying to log in with from the website:

    Error attempting to use stored discovery information: >

    Any clues?

  • #54 Miguel Grinberg said 2013-05-09T18:09:38Z

    @Matt: I have never seen this error, but the "OpenIDServiceEndpoint" setting appears to be wrong, in your error message the URL ends with "/ud" while I believe it should end with "/id". You may also want to delete the directories and files that OpenID writes to the microblog/tmp directory before you attempt to login again.

  • #55 Lukas said 2013-05-20T20:08:42Z

    If anybody still has a problem with imports, moving lines: (views.py) "from app import app, db, lm, oid" on the bottom of all imports and line (init.py) "from app import views, models" to the bottom of the file helped me to get everything running.

  • #56 john&susan said 2013-05-29T06:05:36Z

    in the init.py it should be: lm.init_app(app) instead of: lm.setup_app(app)

    but in your zip everything's fine thanks for this vast and detailed tutorial ;)

  • #57 Alvin said 2013-06-09T16:42:26Z

    This app ran well at the first few times. But I don't know why suddenly it has OpenID endless loop login problem. Any idea about OpenID loop login? Thanks

  • #58 Miguel Grinberg said 2013-06-09T23:09:10Z

    @Alvin: sorry but you are not giving me enough information. Enless loop where? Is the browser getting in an endless loop or the server? Did you try removing the Flask-Login cookie?

    Hopefully you can figure out how to reproduce this problem and then I'll be able to debug it.

  • #59 Fellow_user said 2013-06-13T07:18:08Z

    Hi Miguel, Thanks for the tutorial. Can you give me some tips on how to make a login page without using open ID? I need to validate the username and password from an existing MYSQL DB.. Thanks..

  • #60 Miguel Grinberg said 2013-06-14T02:27:12Z

    @Fellow: you can use Flask-Login to validate against your own DB. Just ignore the OpenID part and in your login view function just verify that the username and password are correct and call Flask-Login's login_user function if your verification succeeds. The process is much simpler than with OpenID because there is no need to have a callback.

  • #61 Sander Leemet said 2013-06-27T21:59:22Z

    I have a problem with authentication with OpenID. No user is created in the database and terminal shows this message:

    Generated checkid_setup request to https://www.google.com/accounts/o8/ud with assocication 1.AMlYA9Vuo-_HK9trb3ev2sf1hb4hEsEMW_6_C7DsjiTQymUAP0WTgH1pwxs1RQ 127.0.0.1 - - [27/Jun/2013 17:37:24] "POST /login?next=%2F HTTP/1.1" 302 - Error attempting to use stored discovery information: > Attempting discovery to verify endpoint Performing discovery on https://www.google.com/accounts/o8/id?id=AItOawmbCRf5MNfzLNVM_RE2Ludp52QTkt2TNuA Received id_res response from https://www.google.com/accounts/o8/ud using association 1.AMlYA9Vuo-_HK9trb3ev2sf1hb4hEsEMW_6_C7DsjiTQymUAP0WTgH1pwxs1RQ 127.0.0.1 - - [27/Jun/2013 17:37:25] "GET /login?next=/&openid_complete=yes&janrain_nonce=2013-06-27T14%3A37%3A24Zc7UgOi&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&openid.response_nonce=2013-06-27T21%3A56%3A39ZwtJkOCy1j8uzig&openid.return_to=http%3A%2F%2Flocalhost%3A5000%2Flogin%3Fnext%3D%2F%26openid_complete%3Dyes%26janrain_nonce%3D2013-06-27T14%253A37%253A24Zc7UgOi&openid.assoc_handle=1.AMlYA9Vuo-_HK9trb3ev2sf1hb4hEsEMW_6_C7DsjiTQymUAP0WTgH1pwxs1RQ&openid.signed=op_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle%2Cns.ext1%2Cext1.mode%2Cext1.type.ext0%2Cext1.value.ext0%2Cext1.type.ext1%2Cext1.value.ext1&openid.sig=oHB2LfBTNRwuH1CH03JbChlF3wQ%3D&openid.identity=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOawmbCRf5MNfzLNVM_RE2Ludp52QTkt2TNuA&openid.claimed_id=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOawmbCRf5MNfzLNVM_RE2Ludp52QTkt2TNuA&openid.ns.ext1=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0&openid.ext1.mode=fetch_response&openid.ext1.type.ext0=http%3A%2F%2Fschema.openid.net%2Fcontact%2Femail&openid.ext1.value.ext0=sander.leemet%40gmail.com&openid.ext1.type.ext1=http%3A%2F%2Faxschema.org%2Fcontact%2Femail&openid.ext1.value.ext1=sander.leemet%40gmail.com HTTP/1.1" 302 - 127.0.0.1 - - [27/Jun/2013 17:37:25] "GET /login?next=/ HTTP/1.1" 200 -

    I almost googled myself to death with no luck... Any way you are able to help?

    Great tutorial BTW!

    Sander Leemet
  • #62 Miguel Grinberg said 2013-06-28T04:03:01Z

    @Sander: are you sure it isn't working? There are no fatal errors in your log, so from that it appears that the openid part worked. Does your "after_login" callback run?

  • #63 Sander Leemet said 2013-07-01T20:08:14Z

    'after_login' does not run. It just redirects to login page and I can't access any view with the '@login_required' decorator.

    It reaches the line 'return oid.try_login(form.openid.data, ask_for = ['nickname', 'email'])', but I'm guessing this fails somehow.

  • #64 Miguel Grinberg said 2013-07-02T07:10:22Z

    @Sander: from your log it appears that try_login worked. If you are working with your own copy of the project you may want to download the official files and try that. Also, note that a couple of things broke with the recent release of Flask 0.10, I have now updated the setup script to stay with Flask 0.9.

  • #65 Sander Leemet said 2013-07-02T09:48:13Z

    Downgraded my Flask to v0.9, everything works perfectly now.

    Thank you! :)

    -Sander

  • #66 Marek Zelinka said 2013-07-04T17:29:59Z

    Hi Miguel, I have a problem:

    When I add:

    1

    import os from flask.ext.login import LoginManager from flask.ext.openid import OpenID from config import basedir

    lm = LoginManager() lm.init_app(app) oid = OpenID(app, os.path.join(basedir, 'tmp'))

    to app/init.py,

    and add:

    2

    from app import app, db, lm, oid

    to config.py, then when I start the app, it gives me an error:

    ImportError: cannot import name lm.

    but when I add #1 to app/views.py, it runs ok..

    Can you tell me where the problem is?

    Thanks, Marek.

  • #67 Miguel Grinberg said 2013-07-04T17:41:38Z

    @Marek: You have circular references. Do not import any application modules into config.py, that file is supposed to just have configuration settings.

  • #68 Marek Zelinka said 2013-07-05T10:02:58Z

    @Miguel: ou, sorry thats a typo, I mean add #2 to app/views.py, but it still gives me the same error, help!

  • #69 Marek Zelinka said 2013-07-05T10:16:38Z

    @Miguel: Ok, I've fixed the error now.. You should mention that this code:

    import os from flask.ext.login import LoginManager from flask.ext.openid import OpenID from config import basedir

    lm = LoginManager() lm.init_app(app) oid = OpenID(app, os.path.join(basedir, 'tmp'))

    need's to go before:

    from app import views, models

  • #70 drew said 2013-08-02T07:53:28Z

    Tiny heads up MyOpenID has no @. Our code

    nickname = resp.email.split('@')[0] AttributeError: 'NoneType' object has no attribute 'split'

    Assumes it does. easily fixed though

  • #71 Miguel Grinberg said 2013-08-03T01:53:02Z

    @drew: if resp.email is None then why did it get that far? There is a check at the start of the after_login function that rejects invalid emails.

  • #72 Lou said 2013-09-01T20:08:49Z

    I'm running on Mint 13 Maya. I also while adding the view get NameError 'lm' is not defined. Error occurs in last line of init.py when importing views. Also is raised if I try to db_migrate.py. Did an --upgrade on flask-login. Still stuck at this point. Any Advise??

  • #73 Miguel Grinberg said 2013-09-01T22:39:27Z

    @Lou: do you have a line that reads "lm = LoginManager() earlier in the init.py file? That's likely missing for you.

  • #74 Andrew Doyle said 2013-09-08T19:02:02Z

    Hi Miguel, thank you for your details tutorial here. If you have a moment, I was wondering if you could help me with an error:

    File "/home/asdoylejr/microblog/app/init.py", line 18, in oid = OpenId(app, os.path.join(basedir, 'tmp')) NameError: name 'OpenId' is not defined

    I've made sure that my code matches your code exactly but I cannot figure out why I am getting this error, so I'm unable to progress through your tutorial.

    Thanks again!

  • #75 Miguel Grinberg said 2013-09-08T19:08:45Z

    @Andrew: try OpenID instead of OpenId. (last D should be uppercase).