Skip to main content

Command Palette

Search for a command to run...

Benefits and examples of the 'Flask-Login' library

Published
3 min read
Benefits and examples of the 'Flask-Login' library

The Flask framework's greatest strength is perhaps its lack of innate tools. Its 'lightweight' nature makes it easy to learn and use, but it also frequently invites the involvement of other libraries and modules. One such library (from the creators of Flask-Bcrypt and with many GitHub contributions from active members of the Pallets Projects team) is 'Flask-Login'. Flask-Login describes itself as: "providing user session management for Flask," and it can work well in combination with Flask-Bcrypt for authenticating users.

Essentially, Flask-Login has built-in classes and methods for handling users logging in, users logging out, remembering a user's session over long periods of time (and even when they close the webpage or app), restricting views to logged-in or logged-out users, and protecting a user's session in various ways. Let's take a look at how it can do this:

Once it has been installed with:

$ pip install flask-login

and the Login Manager class has been imported and instantiated with:

from flask_login import LoginManager
login_manager = LoginManager()
app = Flask(__name__)
login_manager.init_app(app)

we need to provide a 'user_loader' callback so that the correct User object can be retrieved from the ID stored in the session:

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

now, we can take a look at some specifics:

One of the best starting points for understanding how we can use Flask-Login is to take a look at the following required properties and methods of a User class:

  • is_athenticated

  • is_active

  • is_anonymous

  • get_id()

The is_authenticated property, for example, is a boolean that is used to track whether or not a view is available when we want to restrict something to logged-in users only.

We can implement these three properties and the get_id() method automatically by inheriting UserMixin in the class, which is imported from flask_login.

The code above is an example of a User class which simply by inheriting UserMixin, has the is_athenticated, is_active, is_anonymous, get_id() properties and methods, even though you don't see them defined here.

To show the use case of the is_authenticated property, let's look at this example:

@app.route("/myaccount")
@login_required
def myaccount():
    pass

the @login_required decorator is used here to restrict the '/myaccount' view to only users which are logged-in.

Maybe you are wondering, "how do I use Flask-Login to actually Log In a User?" Here is an example of a login function which utilizes Flask-Bcrypt for authentication and a Flask-wtf to gather user input from a Form.

class LoginForm(FlaskForm):
    username = StringField(validators=[
                           InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
    password = PasswordField(validators=[
                             InputRequired(), Length(min=8, max=20)], render_kw={"placeholder": "Password"})

    submit = SubmitField('Login')

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user:
            if bcrypt.check_password_hash(user.password, form.password.data):
                login_user(user)

(example here from this Flask-Login tutorial)

Once a User is logged in, the 'logged-in' user can be accessed with current_user

(example from Flask-Login readthedocs)

There are many other tools Flask-Login gives us to keep track of Users, customize cookies, protect the User sessions and so on, but the last functionality I would like to showcase is one of the User quality-of-life features unique to Flask-Login:

Remembering a user even if they close their browser.

Normally, Flask's native session cookie persists for the lifetime of a browser session, but Flask-Login's 'Remember Me' feature allows the User's session cookie to persist even after browser restarts. And the way we enable this feature is extremely simple: just put remember=true or remember=false as arguments in the login_user call to enable and disable this feature respectively.

login_user(user, remember=true)

That's it. Now the User's session will persist even if they close the browser.

This is just a few examples of the many features Flask-Login comes with. For a more comprehensive list, check out the ReadTheDocs for Flask-Login.