12.7. Flask: Users and Authentication#

In this section, we’ll extend the DB-only microblog to support users. You’ll add:

  • self-registration

  • login / logout

  • author attribution on posts (show @username)

  • delete, but only the author can delete their own posts

We’ll keep the same “few files” style from prior pages so the focus stays on the mechanics: models + forms + routes + templates + tests.

You’ll implement a classic auth flow — register → login → post → delete your own — and update the timeline to show the author by username. This sections brings together:

  1. persistence with relationships

  2. session auth with Flask-Login

  3. basic authorization checks (owner‑only deletes).

Upgrade note: because Post now references User, it’s easiest to start fresh for this section. In a demo, it’s fine to delete app.db and re-run. In real apps, you’d use migrations.

Note: This section includes less inline commentary than earlier ones. Be sure to carefully read the code to understand how the pieces fit together.

12.7.1. Project Layout and Dependencies#

Same structure as before, with a few new templates and forms:

flask-microblog-auth/
├─ app.py           # Flask app, config, db, login manager
├─ models.py        # User & Post models
├─ forms.py         # RegisterForm, LoginForm, PostForm, DeleteForm
├─ routes.py        # register/login/logout + posting + delete
├─ templates/
│  ├─ base.html
│  ├─ index.html
│  ├─ login.html
│  ├─ register.html
│  └─ profile.html
├─ tests/
│  ├─ conftest.py
│  ├─ test_auth_flow.py
│  └─ test_posting_and_delete.py
└─ static/
   └─ styles.css

12.7.1.1. Install dependencies#

pip install Flask Flask-SQLAlchemy Flask-WTF Flask-Login email_validator

Why these?

  • Flask-Login: manages the “who is logged in?” state via session cookies (current_user, login_user, @login_required)

  • Flask-WTF: keeps forms + CSRF protection consistent with earlier sections

  • email_validator: used by WTForms’ Email() validator

12.7.2. Step 1: App Setup (app.py)#

app.py creates the app, configures the DB, and initializes Flask-Login.

# app.py
import os
import secrets
import sys
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", secrets.token_hex(16))
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL", "sqlite:///app.db")

# Teaching convenience: allow "from app import app" when running python app.py
sys.modules.setdefault("app", sys.modules[__name__])

db = SQLAlchemy(app)

login_manager = LoginManager(app)
login_manager.login_view = "login"  # where @login_required redirects

# Import after app/extensions exist
import models  # noqa: F401
import routes  # noqa: F401

if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    app.run(debug=True)

12.7.3. Step 2: Models (models.py)#

We add a User model and link Post to the author via user_id.

Two key ideas:

  • Relationship: one user has many posts

  • Password hashing: never store plaintext passwords

# models.py
# models.py
from datetime import datetime, timezone
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from app import db

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), unique=True, index=True, nullable=False)
    email = db.Column(db.String(120), unique=True, index=True, nullable=False)
    password_hash = db.Column(db.String(256), nullable=False)
    posts = db.relationship('Post', backref='author', lazy='dynamic')

    def set_password(self, password: str) -> None:
        self.password_hash = generate_password_hash(password)

    def check_password(self, password: str) -> bool:
        return check_password_hash(self.password_hash, password)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text, nullable=False)
    timestamp = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), index=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

Why hash passwords? Storing plaintext is unsafe. Werkzeug’s helpers provide battle‑tested hashing and verification in one line.

12.7.4. Step 3: Forms (forms.py)#

We’ll add registration and login forms, and keep PostForm from the previous section.

# forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, TextAreaField, BooleanField
from wtforms.fields import EmailField
from wtforms.validators import DataRequired, Email, EqualTo, Length, ValidationError
from models import User

class RegisterForm(FlaskForm):
    username = StringField("Username", validators=[DataRequired(), Length(min=3, max=32)])
    email = EmailField("Email", validators=[DataRequired(), Email(), Length(max=120)])
    password = PasswordField("Password", validators=[DataRequired(), Length(min=6)])
    confirm = PasswordField("Confirm Password", validators=[DataRequired(), EqualTo("password")])
    submit = SubmitField("Create Account")

    def validate_username(self, field):
        if User.query.filter_by(username=field.data).first():
            raise ValidationError("Username is already taken.")

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError("Email is already registered.")

class LoginForm(FlaskForm):
    email = EmailField("Email", validators=[DataRequired(), Email(), Length(max=120)])
    password = PasswordField("Password", validators=[DataRequired()])
    remember = BooleanField("Remember me")
    submit = SubmitField("Sign In")

class PostForm(FlaskForm):
    body = TextAreaField("What's happening?", validators=[DataRequired(), Length(max=280)])
    submit = SubmitField("Post")

class DeleteForm(FlaskForm):
    submit = SubmitField("Delete")

12.7.5. Step 4: Routes (routes.py)#

We’ll implement the full flow:

  • Register → create user row

  • Login → set session with login_user

  • Logout → clear session with logout_user

  • Posting → allowed only when authenticated

  • Delete → allowed only for the author

Auth terminology reminder:

  • Authentication answers: Who is this user? (login, session)

  • Authorization answers: What is this user allowed to do? (owner-only deletes)

This section implements both.

# routes.py
from flask import render_template, redirect, url_for, flash, request, abort
from flask_login import current_user, login_user, logout_user, login_required
from app import app, db, login_manager
from models import User, Post
from forms import RegisterForm, LoginForm, PostForm, DeleteForm

def load_user(user_id: str):
    return db.session.get(User, int(user_id))

@app.route("/", methods=["GET", "POST"])
def index():
    delete_form = DeleteForm()

    if not current_user.is_authenticated:
        # Show timeline to everyone, but only logged-in users can post
        posts = Post.query.order_by(Post.timestamp.desc()).limit(50).all()
        return render_template("index.html", form=None, delete_form=delete_form, posts=posts)

    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.body.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash("Posted!")
        return redirect(url_for("index"))  # PRG

    posts = Post.query.order_by(Post.timestamp.desc()).limit(50).all()
    return render_template("index.html", form=form, delete_form=delete_form, posts=posts)

@app.route("/register", methods=["GET", "POST"])
def register():
    if current_user.is_authenticated:
        return redirect(url_for("index"))

    form = RegisterForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)

        db.session.add(user)
        db.session.commit()

        flash("Account created. Please sign in.")
        return redirect(url_for("login"))

    return render_template("register.html", form=form)

@app.route("/login", methods=["GET", "POST"])
def login():
    if current_user.is_authenticated:
        return redirect(url_for("index"))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()

        if not user or not user.check_password(form.password.data):
            flash("Invalid credentials")
            return render_template("login.html", form=form)

        login_user(user, remember=form.remember.data)
        flash("Welcome back!")

        next_page = request.args.get("next")
        return redirect(next_page or url_for("index"))

    return render_template("login.html", form=form)

@app.get("/logout")
@login_required
def logout():
    logout_user()
    flash("You have been signed out.")
    return redirect(url_for("index"))

@app.post("/post/<int:post_id>/delete")
@login_required
def delete_post(post_id: int):
    form = DeleteForm()
    if not form.validate_on_submit():
        abort(400)

    post = db.session.get(Post, post_id)
    if post is None:
        abort(404)

    # Authorization check, the user can only delete their own posts.
    if post.user_id != current_user.id:
        abort(403)

    db.session.delete(post)
    db.session.commit()
    flash("Post deleted.")
    return redirect(url_for("index"))

@app.get("/u/<username>")
def profile(username: str):
    user = User.query.filter_by(username=username).first_or_404()
    posts = user.posts.order_by(Post.timestamp.desc()).all()
    return render_template("profile.html", user=user, posts=posts)

12.7.6. Step 5: Templates#

12.7.6.1. templates/base.html — shared layout & navigation#

This template defines the shared page skeleton for the entire application. It contains the site header, navigation, flash message area, and footer, and exposes a {% block content %} that child templates fill in.

Because base.html knows about current_user, it can switch navigation links automatically based on authentication state.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{% block title %}Microblog{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}" />
  </head>
  <body>
    <header class="site-header">
      <div class="container" style="display:flex; justify-content:space-between; align-items:center;">
        <h1 style="margin:0;"><a href="/">Microblog</a></h1>
        <nav style="display:flex; gap:12px;">
          {% if current_user.is_authenticated %}
            <a href="{{ url_for('profile', username=current_user.username) }}">@{{ current_user.username }}</a>
            <a href="{{ url_for('logout') }}">Logout</a>
          {% else %}
            <a href="{{ url_for('login') }}">Login</a>
            <a href="{{ url_for('register') }}">Register</a>
          {% endif %}
        </nav>
      </div>
    </header>

    <main class="container">
      {% with messages = get_flashed_messages() %}
        {% if messages %}
          <div class="card" role="status">
            {% for m in messages %}<p>{{ m }}</p>{% endfor %}
          </div>
        {% endif %}
      {% endwith %}
      {% block content %}{% endblock %}
    </main>

    <footer class="site-footer">
      <div class="container"><small>Auth microblog</small></div>
    </footer>
  </body>
</html>

12.7.6.2. templates/index.html#

This template renders the home timeline and conditionally shows the post composition form.

Key behaviors:

  • Logged-in users see the compose form

  • Anonymous users see a prompt to sign in

  • Each post shows its author and timestamp

  • A Delete button appears only for posts owned by the current user

All authorization decisions are enforced server-side; the template only reflects state already determined by the route.

{% extends "base.html" %}
{% block title %}Home — Microblog{% endblock %}
{% block content %}
  {% if form %}
    <section class="card">
      <h2>Compose</h2>
      <form method="post" class="stack">
        {{ form.hidden_tag() }}
        {{ form.body(rows=3, placeholder="What's happening?") }}
        {% if form.body.errors %}
          <small class="error">{{ form.body.errors[0] }}</small>
        {% endif %}
        {{ form.submit(class_="button") }}
      </form>
    </section>
  {% else %}
    <p><a class="button" href="{{ url_for('login') }}">Sign in</a> to post.</p>
  {% endif %}

  <section class="card">
    <h2>Recent Posts</h2>
    {% if posts %}
      <ul class="stack">
        {% for p in posts %}
          <li>
            <strong>
              <a href="{{ url_for('profile', username=p.author.username) }}">@{{ p.author.username }}</a>
            </strong><br />
            {{ p.body }}<br />
            <small>{{ p.timestamp.strftime("%Y-%m-%d %H:%M") }} UTC</small>

            {% if current_user.is_authenticated and p.user_id == current_user.id %}
              <form method="post" action="{{ url_for('delete_post', post_id=p.id) }}" style="display:inline;">
                {{ delete_form.hidden_tag() }}
                <button class="button" style="margin-left:8px; background:#b91c1c; border-color:#991b1b;">
                  Delete
                </button>
              </form>
            {% endif %}
          </li>
        {% endfor %}
      </ul>
    {% else %}
      <p><em>No posts yet.</em></p>
    {% endif %}
  </section>
{% endblock %}

12.7.6.3. templates/login.html#

This template renders the login form and submits credentials to the /login route.

It relies on Flask-Login to establish the user session and supports:

  • Email + password authentication

  • Optional “remember me” cookies

  • Redirecting users back to their original destination after login (via next)

{% extends "base.html" %}
{% block title %}Sign In — Microblog{% endblock %}
{% block content %}
  <section class="card">
    <h2>Sign In</h2>
    <form method="post" class="stack">
      {{ form.hidden_tag() }}
      <label><span>{{ form.email.label }}</span>{{ form.email(placeholder="you@example.com") }}</label>
      <label><span>{{ form.password.label }}</span>{{ form.password() }}</label>
      <label class="checkbox">{{ form.remember() }} <span>{{ form.remember.label }}</span></label>
      {{ form.submit(class_="button") }}
    </form>
  </section>
{% endblock %}

12.7.6.4. templates/register.html#

This template renders the account creation form for new users.

It displays:

  • Field-level validation errors (e.g., duplicate username or email)

  • Password confirmation enforcement

All validation logic lives in RegisterForm; the template is responsible only for presentation.

{% extends "base.html" %}
{% block title %}Register — Microblog{% endblock %}
{% block content %}
  <section class="card">
    <h2>Create Account</h2>
    <form method="post" class="stack">
      {{ form.hidden_tag() }}

      <label><span>{{ form.username.label }}</span>{{ form.username(placeholder="yourname") }}</label>
      {% if form.username.errors %}<small class="error">{{ form.username.errors[0] }}</small>{% endif %}

      <label><span>{{ form.email.label }}</span>{{ form.email(placeholder="you@example.com") }}</label>
      {% if form.email.errors %}<small class="error">{{ form.email.errors[0] }}</small>{% endif %}

      <label><span>{{ form.password.label }}</span>{{ form.password() }}</label>
      <label><span>{{ form.confirm.label }}</span>{{ form.confirm() }}</label>

      {{ form.submit(class_="button") }}
    </form>
  </section>
{% endblock %}

12.7.6.5. templates/profile.html#

This template displays a public profile page for a user and lists their posts in reverse-chronological order.

It demonstrates:

  • URL-based resource lookup (/u/<username>)

  • One-to-many relationships rendered in templates (user.posts)

  • Reusing the same post display logic in multiple contexts

This page does not require authentication — profiles are readable by anyone.

{% extends "base.html" %}
{% block title %}@{{ user.username }} — Microblog{% endblock %}
{% block content %}
  <section class="card">
    <h2>@{{ user.username }}</h2>
    <p>{{ user.email }}</p>
  </section>

  <section class="card">
    <h3>Posts</h3>
    {% if posts %}
      <ul class="stack">
        {% for p in posts %}
          <li>
            {{ p.body }}<br />
            <small>{{ p.timestamp.strftime("%Y-%m-%d %H:%M") }} UTC</small>
          </li>
        {% endfor %}
      </ul>
    {% else %}
      <p><em>No posts yet.</em></p>
    {% endif %}
  </section>
{% endblock %}

12.7.7. Step 6: Testing (Auth + Authorization)#

We’ll reuse the temporary SQLite DB approach from the persistence section.

12.7.7.1. tests/conftest.py - shared fixtures + helpers#

This file defines pytest fixtures that every test can reuse. We configure the app in testing mode, point it at a temporary SQLite database, and disable CSRF so form submissions in tests don’t require extracting a token.

It also provides helper fixtures like register_user() and login_user() so individual tests can focus on behavior (posting, redirecting, authorization) instead of repeating setup code.

# tests/conftest.py
import pytest, importlib, sys, pathlib

ROOT = pathlib.Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

@pytest.fixture()
def app(tmp_path, monkeypatch):
    # Fresh DB per test
    monkeypatch.setenv('DATABASE_URL', f"sqlite:///{tmp_path / 'test.db'}")
    import app as app_module
    app_module = importlib.reload(app_module)

    # Reload dependent modules so routes/models/forms bind to the fresh app instance
    import models as models_module, forms as forms_module, routes as routes_module
    models_module = importlib.reload(models_module)
    forms_module = importlib.reload(forms_module)
    routes_module = importlib.reload(routes_module)
    app = app_module.app
    db = app_module.db

    app.config.update(TESTING=True, WTF_CSRF_ENABLED=False)

    with app.app_context():
        db.create_all()

    yield app

    with app.app_context():
        db.session.remove()

@pytest.fixture()
def client(app):
    return app.test_client()

# Helpers: register + login
@pytest.fixture()
def register_user(client):
    def _go(username='alice', email='alice@example.com', password='secret123'):
        return client.post('/register', data={
            'username': username,
            'email': email,
            'password': password,
            'confirm': password,
        }, follow_redirects=True)
    return _go

@pytest.fixture()
def login_user(client):
    def _go(email='alice@example.com', password='secret123'):
        return client.post('/login', data={'email': email, 'password': password}, follow_redirects=True)
    return _go

12.7.7.2. tests/test_auth_flow.py#

These tests validate the basic authentication workflow:

  1. A new user can register

  2. That user can log in

  3. That user can log out

The goal is to prove that our user model, password hashing, session management (Flask-Login), and flash messages are wired correctly. If any part of the auth pipeline breaks (form validation, user lookup, password check, session cookie), these tests will fail quickly.

def test_register_login_logout(client, register_user, login_user):
    r = register_user()
    assert r.status_code == 200
    assert b"Account created" in r.data

    r = login_user()
    assert r.status_code == 200
    assert b"Welcome back" in r.data

    r = client.get("/logout", follow_redirects=True)
    assert r.status_code == 200
    assert b"signed out" in r.data.lower()

12.7.7.3. tests/test_posting_and_delete.py#

These tests focus on authorization rules, not just authentication:

  • Posting requires login: an unauthenticated POST should redirect to /login

  • Posting works when logged in: a logged-in user can create a post and see it appear

  • Delete is owner-only:

    • The author can delete their own post

    • Another user gets a 403 Forbidden if they try to delete someone else’s post

This is the “security core” of the tutorial: it proves your routes enforce the rule

“Only the author can delete their own content.”

from urllib.parse import urlparse

def test_post_requires_login(client):
    resp = client.post("/", data={"body": "unauth post"}, follow_redirects=False)
    assert resp.status_code == 302
    assert urlparse(resp.headers["Location"]).path == "/login"

def test_post_with_login(client, register_user, login_user):
    register_user()
    login_user()

    r = client.post("/", data={"body": "hello"}, follow_redirects=True)
    assert r.status_code == 200
    assert b"Posted!" in r.data
    assert b"hello" in r.data

def test_delete_own_post(client, register_user, login_user):
    register_user()
    login_user()
    client.post("/", data={"body": "mine"})

    # For this tutorial, we assume a fresh DB where the first post has id=1
    # In real apps, you would query the DB or parse the response instead.
    r = client.post("/post/1/delete", data={"submit": "Delete"}, follow_redirects=True)
    assert r.status_code == 200
    assert b"Post deleted" in r.data
    assert b"mine" not in r.data

def test_cannot_delete_others_post(client, register_user, login_user):
    # Alice creates a post
    register_user(username="alice", email="alice@example.com")
    login_user(email="alice@example.com")
    client.post("/", data={"body": "alice post"})
    client.get("/logout", follow_redirects=True)

    # Bob tries to delete it
    register_user(username="bob", email="bob@example.com")
    login_user(email="bob@example.com")

    r = client.post("/post/1/delete", data={"submit": "Delete"})
    assert r.status_code == 403

12.7.8. Run It#

Start fresh for this section:

rm -f app.db   
python app.py
# or
flask --app app run --debug

Run tests:

pytest -q

12.7.9. Key Takeaways#

  • User ↔ Post adds a relationship and enables ownership rules

  • Flask-Login handles session-based authentication

  • @login_required protects routes that need a signed-in user

  • Owner-only delete is an authorization check (post.user_id == current_user.id)

  • Tests should cover both auth flow and authorization rules

12.7.10. Exercises — Users and Authentication#

12.7.10.1. Exercise 1: Add a “My Posts” Page#

Create a page at /mine that shows only the current user’s posts.

Tasks:

  1. Add a route /mine protected by @login_required

  2. Query posts for current_user only

  3. Render a new template templates/mine.html

Hint:

posts = current_user.posts.order_by(Post.timestamp.desc()).all()

Concepts practiced: @login_required, querying by relationship, new template page


12.7.10.2. Exercise 2: Show Validation Errors on Login#

Right now, login failures flash "Invalid credentials" but don’t show field-level errors.

Tasks:

  1. Update templates/login.html to show a small error below the form when the flash appears

  2. Add a test that submits a wrong password and checks for "Invalid credentials"

Concepts practiced: UX feedback, auth testing, response assertions


12.7.10.3. Exercise 3: Prevent Duplicate Usernames and Emails (Test It)#

The registration form already checks for duplicates. Add tests to prove it.

Tasks:

  1. Register a user

  2. Try registering again with the same username (different email)

  3. Try registering again with the same email (different username)

  4. Assert an error message appears (or just assert class="error")

Concepts practiced: custom WTForms validators, validation testing


12.7.10.4. Exercise 4: Add “Delete Confirmation” (Optional)#

Right now, delete is a single click.

Tasks (pick one):

  • Add a JavaScript confirm() before submitting the delete form, or

  • Add a separate GET /post/<id>/confirm-delete page

Concepts practiced: safer destructive actions, POST-only deletes, UI guardrails