Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Advanced Python

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Advanced Python

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:

BrickJob
Flaskmatches the URL and calls the view function
Flask-SQLAlchemytalks to the database (SQLite here)
Jinja2turns data into the HTML page
Flask-Loginremembers who you are from one request to the next
Flask-WTFbuilds the forms and adds a hidden token to each
Werkzeughashes 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

GET / goes from the browser to the URL map, which picks blog.index; index asks Flask-SQLAlchemy for posts; three SQL statements run on SQLite; rows come back as Post objects, Jinja2 renders index.html, and the response is 200 text/html with no cookie. Browser GET / URL map blog.index index() plain def Flask- SQLAlchemy SQLite 3 SQL Jinja2 index.html 200 · text/html · no Set-Cookie a page of posts, the count, then the author
The home page path. Every view in this blog is a plain def; the server runs it and the view waits for the database.

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 session cookie value has three parts joined by dots: the payload with _user_id, _fresh, _id, csrf_token and _flashes; a timestamp; and a 27-character signature made with SECRET_KEY. Anyone can read the payload; nobody can change it without the key. payload (readable) _user_id: 1 _fresh: True _id, csrf_token _flashes: "Welcome back, ..." . timestamp . signature 27 characters made with SECRET_KEY Signed, not encrypted: change one character and the signature no longer matches.
What Flask-Login leaves behind after login: a user id in Flask's signed session, and nothing in the database.

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:

WhoResultPosts
anonymous, GET and POST302 to /auth/login?next=... (stopped by login_required)unchanged
plain test user, GET and POST403 Forbidden (stopped by admin_required)10 before, 10 after
admin, POST with tokenINSERT into post, 302 to /admin/10 to 11
admin, POST without tokenform shown again, 20011 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

StepWho does itWhat you can check
match the URLFlask URL mapflask routes, endpoint = blueprint.function
read dataFlask-SQLAlchemy on SQLite3 SQL statements for the home page
build HTMLJinja2200 text/html
protect formsFlask-WTFno token, no SQL, form shown again
check passwordWerkzeug scrypt hashnew salt every time
remember the userFlask-Login + signed session_user_id in the cookie, load_user per request
allow the writelogin_required, admin_required302 / 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 47 of 48

Previous
Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
Next post
Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client

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.

On this page

  • The bricks on this path
  • One GET, end to end
  • The URL map picks the view
  • Three SQL statements for the home page
  • The login form and its hidden token
  • The password check
  • Hashed, not encrypted
  • A signed session cookie
  • The next request carries the cookie
  • The admin check on the write view
  • The template hides, the backend decides
  • Finding 1: who is the admin?
  • Finding 2: where does next send you?
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.