How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
One GET through the designed Flask blog, with the three SQL statements it runs, then a login traced step by step: hidden CSRF token, scrypt hash, login_user, a signed session cookie, admin_required, and two findings worth fixing.
What you will learn
- Trace a GET request through the URL map, the view, Flask-SQLAlchemy, SQLite and Jinja2
- Follow a login: the Flask-WTF CSRF token, the scrypt password check and login_user
- Explain what Flask-Login keeps in the signed session cookie and how each request is checked
- Spot two review findings: admin decided by email and an open redirect through next
Before you start
- The Flask blog folder structure
- Flask sessions and url_for
Knowing the files tells you what's there. Knowing the flow tells you what runs, and in which order. That's what you need when you review code an AI tool wrote. We'll use the designed Flask blog exactly as it is (nothing added), trace one ordinary request, then trace a login, and find two things worth fixing on the way.
If you haven't toured the project yet, start with Inside a Flask blog.
The bricks on this path
A request doesn't go through one big machine. It passes from brick to brick, and each brick does one job:
| Brick | Job |
|---|---|
| Flask | matches the URL and calls the view function |
| Flask-SQLAlchemy | talks to the database (SQLite here) |
| Jinja2 | turns data into the HTML page |
| Flask-Login | remembers who you are from one request to the next |
| Flask-WTF | builds the forms and adds a hidden token to each |
| Werkzeug | hashes the passwords |
Versions in the run: flask 3.1.3, werkzeug 3.1.8, flask-login 0.6.3, flask-sqlalchemy 3.1.1, flask-wtf 1.2.1, sqlalchemy 2.0.36.
One GET, end to end
The URL map picks the view
create_app registers the auth, blog and admin blueprints. Listing the URL map with each view's file and line:
/auth/login GET,POST auth.login login (app/routes/auth.py:49)
/auth/logout GET auth.logout logout (app/routes/auth.py:69)
/ GET blog.index index (app/routes/blog.py:18)
/post/<slug> GET,POST blog.post_detail post_detail (app/routes/blog.py:26)
/admin/post/create GET,POST admin.create_post create_post (app/routes/admin.py:53)
The login is one function for both methods: GET shows the form, POST sends it. The URL map is a lookup table. It matches the path and the method, and hands the request to one function.
Three SQL statements for the home page
@bp.route('/')
def index():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.created_at.desc()).paginate(
page=page, per_page=10, error_out=False)
return render_template('index.html', posts=posts)
The run printed the SQL the blog sends (columns shortened here):
SELECT post.id, post.title, ... FROM post ORDER BY post.created_at DESC LIMIT ? OFFSET ?
SELECT count(*) AS count_1 FROM (SELECT post.id, ... FROM post) AS anon_1
SELECT user.id, user.name, ... FROM user WHERE user.id = ?
One page of posts. Then a count, because paginate needs to know how many pages there are. The rows become Post objects, and when the template shows each post's author, Flask-SQLAlchemy runs a third select on user. The page comes back 200, text/html; charset=utf-8, titled Home - Blog, and with no cookie, because nobody has logged in yet.
The login form and its hidden token
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
GET /auth/login comes back 200 with a hidden field called csrf_token, 91 characters long, and the response sets a cookie called session that holds the matching token. That's how the blog knows a form came from its own page and not from some other site.
A POST without the token: validate_on_submit() said no, the form came straight back with 200, nobody was logged in, and not a single SQL statement ran. Flask-WTF turns this on for every form, and all five templates with a form add the hidden token.
The password check
@bp.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('blog.index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid email or password', 'danger')
return redirect(url_for('auth.login'))
login_user(user)
flash(f'Welcome back, {user.name}!', 'success')
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('blog.index'))
return render_template('auth/login.html', form=form)
With the token, the view runs one query: a select on user where the email matches, limit 1. With a wrong password, it flashes Invalid email or password and sends a 302 back to /auth/login. The flash waits in the session under _flashes until the next page shows it.
Hashed, not encrypted
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
Both functions come from Werkzeug. The password itself is never stored, and since it's hashed rather than encrypted, there's nothing to decrypt. The run looked at the seeded test admin's stored hash:
prefix scrypt:32768:8:1$ (scrypt, a slow one-way hash)
length 162
salt 16 chars, digest 128 chars
plain password inside: False
verify right password: True
verify wrong password: False
same password hashed again is different: True
The same password hashed twice gives two results, because the salt is new each time. To check a login, Werkzeug reads the method and salt from the stored hash, hashes what you typed the same way, and compares.
A signed session cookie
After a good password, the view calls login_user(user). From the run:
status 302 -> /
Set-Cookie name session
attributes ['HttpOnly', 'Path=/']
value parts 3 (payload.timestamp.signature)
payload keys ['_flashes', '_fresh', '_id', '_user_id', 'csrf_token']
_user_id 1 _fresh True
signature length 27
remember cookie set: False
The payload is compressed and encoded, so it looks scrambled, but it's signed, not encrypted. Anyone can read it; nobody can change it without the secret key. Nothing was written to the database at login, and there's no remember-me cookie.
One review point here: if .env is missing, SECRET_KEY falls back to a fixed string in config.py, and anyone who knows it could sign their own cookie. The session idea itself is covered in Flask routes, templates and sessions.
The next request carries the cookie
The browser asks for /admin/post/create and sends the cookie along. Flask checks the signature, finds _user_id 1, and Flask-Login calls the user loader in models.py:
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
That's one select on user by id, and the result becomes current_user. It's the admin, so the page comes back 200, Create Post - Admin.
Change one character in the cookie and send it again: the signature doesn't match, Flask throws the session away, and the answer is a 302 to /auth/login?next=%2Fadmin%2Fpost%2Fcreate. No SQL runs at all. The cookie is checked again on every request; that's how you stay logged in from page to page.
The admin check on the write view
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_authenticated:
abort(403)
if not current_user.is_admin(current_app.config['ADMIN_EMAIL']):
abort(403)
return f(*args, **kwargs)
return decorated_function
@bp.route('/post/create', methods=['GET', 'POST'])
@login_required
@admin_required
def create_post():
Two decorators stacked on top. What each visitor got from the run:
| Who | Result | Posts |
|---|---|---|
| anonymous, GET and POST | 302 to /auth/login?next=... (stopped by login_required) | unchanged |
| plain test user, GET and POST | 403 Forbidden (stopped by admin_required) | 10 before, 10 after |
| admin, POST with token | INSERT into post, 302 to /admin/ | 10 to 11 |
| admin, POST without token | form shown again, 200 | 11 stays 11 |
The checks sit in the backend and run before the view can touch the posts.
The template hides, the backend decides
{% if current_user.is_authenticated %}
{% if current_user.is_admin(config['ADMIN_EMAIL']) %}
<li class="nav-item">
<a class="nav-link nav-link-elegant" href="{{ url_for('admin.dashboard') }}">Admin Dashboard</a>
</li>
In base.html line 39, the Admin Dashboard link only shows for the admin. But hiding a link only changes the page; anyone can still type the address. That's why the real check has to be admin_required on the view, and this blog has it there.
Finding 1: who is the admin?
is_admin in models.py line 23 just compares the user's email with ADMIN_EMAIL from the config. On an empty database, registering with that email gave a 302 to the login page and one user in the table. After login, is_admin was True and the Create Post page opened with 200. There's no invite and no check that you own the address. The email match is the whole test.
The fix: make admin a flag on the user, set only from a trusted place (the seed script, or a command run on the server), and have admin_required check that flag.
Finding 2: where does next send you?
After login, the view reads next from the address and redirects there. A login posted to /auth/login?next=http://other.example/ came back as:
status 302 -> http://other.example/
So someone could send a login link that looks like the blog, and after login the user lands on another site. next should only be allowed when it's a path on this blog. Ask your AI agent for both fixes with a prompt in Role, Context, Task and Format, then review the diff it gives you.
Quick recap
| Step | Who does it | What you can check |
|---|---|---|
| match the URL | Flask URL map | flask routes, endpoint = blueprint.function |
| read data | Flask-SQLAlchemy on SQLite | 3 SQL statements for the home page |
| build HTML | Jinja2 | 200 text/html |
| protect forms | Flask-WTF | no token, no SQL, form shown again |
| check password | Werkzeug scrypt hash | new salt every time |
| remember the user | Flask-Login + signed session | _user_id in the cookie, load_user per request |
| allow the write | login_required, admin_required | 302 / 403 / 302 to dashboard |
Try it yourself
Register a new test user, log in, and type /admin/post/create in the address bar. You'll get the 403, even though the page never showed you a link. Then turn these checks into tests in Testing the Flask blog with pytest.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.
Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.
Async Python: async def, await, asyncio.gather and the Blocking Trap
One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
