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
