liveBook · Manning

Flask-Login

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

Flask-Login is a Flask extension that manages user sessions and integrates authentication with protected views.

A login form can check a password, but an application also needs to remember who signed in and keep protected URLs away from other visitors. Flask-Login supplies session management, login and logout tools, “remember me” support, and protection for endpoints that require authentication. The application still uses its own user model and password-checking logic. section 8.2.1

In a blog application, a visitor first requests the login page with GET, then submits an email address and password with POST. The application looks up the user through its model and storage system. If the credentials match, it sends the user to the home page or the page they originally wanted. Passwords are stored as cryptographic hashes using Flask-bcrypt, not as plain text. section 8.2.1

The integration connects Flask-Login to the rest of the application:

  • Create a LoginManager, set its login view, and initialize it with the Flask application. section 8.2.1
  • Provide a user loader that retrieves a User by ID from the database; the User model uses UserMixin. section 8.2.1
  • Keep authentication routes in a blueprint alongside the login form and model-backed credential check. section 8.2.1
from logging import getLogger
from flask import render_template, redirect, url_for, request
from . import auth_bp                                            #1
from ..models import db_session_manager, User                    #2
from .. import login_manager                                     #3
from .forms import LoginForm                                     #4
from flask-login import login_user, logout_user, current_user
from werkzeug.urls import url_parse
 
logger = getLogger(__name__)
 
@login_manager.user_loader                                       #5
def load_user(user_id):                                          #5
    with db_session_manager() as db_session:                     #5
        return db_session.query(User).get(user_id)               #5
 
@auth_bp.route("/login", methods=["GET", "POST"])                #6
def login():
    form = LoginForm()
    if form.validate_on_submit():
        with db_session_manager() as db_session:                 #7
            user = db_session.query(User)
            .filter(User.email == form.email.data)
            .one_or_none()                                     #8
            if user is None or not                               #9
            user.verify_password(form.password.data):          #9
                flash("Invalid email or                          #9
                password", "warning")                          #9
                return redirect(                                 #9
                [url_for("auth_bp.login"))                     #9
            login_user(user,                                     #10
            remember=form.remember_me.data)                    #10
            next = request.args.get("next")                      #10
            if not next or                                       #10
            url_parse(next).netloc != "":                      #10
                next = url_for("intro_bp.home")                  #10
            return redirect(next)                                #10
    return render_template("login.html", form=form)

The authentication-route listing places the user loader beside the login handler, showing where session management meets database lookup and form handling. section 8.2.1

Registration is a related but different workflow: a submitted form creates and saves a user, then sends that person to the login page. Flask-Login fits into the wider authentication and authorization system; it does not replace the database model, form handling, or password hashing. For tighter security, consider measures beyond this login/logout setup, such as two-factor authentication or hosted authentication. section 8.4 section 9.8

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Works through manager setup, user loading, and login workflow, while leaving stronger safeguards such as two-factor authentication beyond the implementation.
Examples
Uses a blog login flow, a database-backed user loader, and a registration flow that redirects new users to login.
What it assumes
Assumes familiarity with Flask routes, forms, and database models while spelling out the GET/POST login and registration flows.
What you can do after
Apply it via Flask-Login to manage user sessions and integrate login, logout, and protected endpoints into a Flask application.
How it connects
Connects authentication and authorization to Flask blueprints, database-backed user models, forms, and password hashing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.