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:
persistence with relationships
session auth with
Flask-Loginbasic authorization checks (owner‑only deletes).
Upgrade note: because
Postnow referencesUser, it’s easiest to start fresh for this section. In a demo, it’s fine to deleteapp.dband 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_userLogout → clear session with
logout_userPosting → 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.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.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↔Postadds a relationship and enables ownership rulesFlask-Loginhandles session-based authentication@login_requiredprotects routes that need a signed-in userOwner-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:
Add a route
/mineprotected by@login_requiredQuery posts for
current_useronlyRender 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:
Update
templates/login.htmlto show a small error below the form when the flash appearsAdd 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:
Register a user
Try registering again with the same username (different email)
Try registering again with the same email (different username)
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, orAdd a separate GET
/post/<id>/confirm-deletepage
Concepts practiced: safer destructive actions, POST-only deletes, UI guardrails