python 48 lines · 9 steps

Session-based auth with a Flask Blueprint

A login_required decorator plus login and logout views build a complete session-based authentication flow in Flask.

Explained by highlit
1from functools import wraps
2from flask import Blueprint, session, request, redirect, url_for, flash, render_template
3from werkzeug.security import check_password_hash
4 
5from app.models import User
6 
7auth = Blueprint("auth", __name__)
8 
9 
10def login_required(view):
11 @wraps(view)
12 def wrapped(*args, **kwargs):
13 if "user_id" not in session:
14 flash("Please sign in to continue.", "warning")
15 return redirect(url_for("auth.login", next=request.path))
16 return view(*args, **kwargs)
17 
18 return wrapped
19 
20 
21@auth.route("/login", methods=["GET", "POST"])
22def login():
23 if request.method == "GET":
24 return render_template("auth/login.html")
25 
26 email = request.form["email"].strip().lower()
27 password = request.form["password"]
28 
29 user = User.query.filter_by(email=email).first()
30 if user is None or not check_password_hash(user.password_hash, password):
31 flash("Invalid email or password.", "error")
32 return render_template("auth/login.html", email=email), 401
33 
34 session.clear()
35 session["user_id"] = user.id
36 session.permanent = bool(request.form.get("remember"))
37 
38 next_url = request.args.get("next")
39 if next_url and next_url.startswith("/"):
40 return redirect(next_url)
41 return redirect(url_for("dashboard.index"))
42 
43 
44@auth.route("/logout", methods=["POST"])
45def logout():
46 session.clear()
47 flash("You have been signed out.", "info")
48 return redirect(url_for("auth.login"))
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing only a user id in the signed session keeps authentication state small and server-verifiable.
  2. 2A login_required decorator centralizes access control so individual views stay focused on their work.
  3. 3Validating a redirect target against a leading slash prevents open-redirect attacks after login.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Session-based auth with a Flask Blueprint — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code