Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 72 ยท Projects

Project: Users and Login

Build a complete Flask account system: registration, hashed passwords, session login, CSRF tokens, flash messages, safe redirects and admin-only pages, all tested.

Almost every real application needs accounts. People register, log in, see pages meant only for them, and a few trusted users can do more than the rest. The pieces are small, but the details (what you store, what you say when a login fails, where you redirect afterwards) decide whether the system is safe.

In this project you will assemble those pieces into one working app: registration with validation, password hashing, session-based login and logout, flash messages, a CSRF token on every form, a login_required and an admin_required decorator, and a safe next redirect. You build it without extension libraries, so every moving part is visible. The follow-up lessons on Flask-Login and roles and permissions show how a library packages the same ideas.

The design

Before writing code, decide the rules the app enforces:

  • Passwords are never stored, only a salted hash (see Password Hashing).
  • The browser holds a session cookie that contains only the user's id. The user row, including the role, is loaded from the database on every request, so a role change takes effect immediately.
  • A failed login always says the same thing, whether the username or the password was wrong. Otherwise attackers can use the form to discover which usernames exist.
  • Every state-changing request (POST) must carry a CSRF token stored in the session.
  • Public pages work for everyone; /profile needs a login; /admin needs the admin role.
flowchart TD
    A["Request arrives"] --> B["before_request:<br/>load g.user from session"]
    B --> C{"Protected view?"}
    C -- no --> H["Run the view"]
    C -- yes --> D{"g.user is None?"}
    D -- yes --> E["Flash message and<br/>redirect to /login?next=..."]
    D -- no --> F{"Role allowed?"}
    F -- no --> G["403 Forbidden"]
    F -- yes --> H

One hook loads the user; decorators decide: 302 to the login page for strangers, 403 for known users without permission.

Notice the two different failures. An anonymous visitor is asked to log in (status 302 to the form), while a logged-in user who lacks the role gets 403 Forbidden. Sending someone to the login page when they are already logged in would only confuse them.

The application

The code below is longer than most examples, so read it in order. The templates sit in a dictionary (a DictLoader, as in Template Inheritance) because the browser sandbox has no templates folder; in a real project each one would be its own file.

Things to spot while reading:

  • HASH_METHOD is a fast setting used only so the demo runs quickly in a browser. The browser Python build also lacks PBKDF2, so the code starts with a clearly labelled, demo-only pure-Python stand-in; a real server needs neither. In production, leave generate_password_hash(password) at its strong default.
  • csrf_token() is registered as a Jinja global. It creates a random token the first time it is needed and keeps it in the session.
  • login calls session.clear() before storing the user id. Starting from a clean session prevents session fixation, where an attacker plants a known session before the victim logs in.
  • When the username does not exist, the code still verifies a password against DUMMY_HASH. That keeps the response time similar, so timing does not leak which usernames exist.
  • is_safe_next accepts only paths on your own site. Without it, /login?next=https://evil.example would be an open redirect.
Python Accounts, roles and CSRF

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Walking through the results

The scenario at the bottom behaves like a person clicking through the site, and each printed line proves one rule:

  • The anonymous request to /profile is redirected to /login?next=/profile, so the visitor ends up back on the page they wanted.
  • Registration returns 400 with the error list when validation fails, and re-renders the form with the username filled in. On success it redirects (Post/Redirect/Get, as in Handling HTML Forms) and a flash message appears on the next page.
  • The hash starts with the algorithm and parameters (pbkdf2:sha256:1000$), followed by a random salt and the digest. The plain password does not appear anywhere.
  • A wrong password for a real user and a login for a non-existent user produce the same status and the same message.
  • The unsafe next value is ignored; the user lands on the home page.
  • After promote, /admin works without logging in again, because the role is read from the database on every request, not copied into the cookie.
  • A POST without the token is rejected with 400, before any view runs.

Why the session holds only an id

The session cookie is signed, not encrypted: anyone can read its contents (see Sessions). So keep it small and non-sensitive. Storing just user_id has another benefit: when you delete a user or change a role, the next request already sees it. If you copied the role into the cookie, demoted admins would stay admins until their cookie expired.

Here is the register-then-login sequence from the point of view of the browser and the server:

sequenceDiagram
    participant B as Browser
    participant F as Flask
    participant D as SQLite
    B->>F: GET /register
    F-->>B: form with CSRF token
    B->>F: POST /register (token, username, password)
    F->>D: INSERT username, password_hash
    F-->>B: 302 to /login (flash: account created)
    B->>F: POST /login (token, credentials)
    F->>D: SELECT user by username
    F-->>B: 302 to next, Set-Cookie: session (user_id)
    B->>F: GET /profile (cookie)
    F->>D: SELECT user by id
    F-->>B: 200 profile page

After login, every request carries the cookie and the app looks the user up again.

What a production version adds

The project is complete as a teaching app, but a public site needs more:

  • Rate limiting on /login so attackers cannot try millions of passwords. See the limiter in Project: A URL Shortener.
  • HTTPS-only cookies: set SESSION_COOKIE_SECURE = True and serve the site over HTTPS.
  • Password reset and email verification, using signed, expiring tokens from itsdangerous.
  • A real secret key loaded from the environment, never committed (see Configuration and Environments).
  • Long-lived sessions and "remember me", which Flask-Login handles for you.
  • A proper migration instead of CREATE TABLE at startup (see Migrations).

Review the list against Web Security Essentials before launching anything real.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the login view show the same message for an unknown username and for a wrong password?

    A generic message avoids user enumeration. The dummy hash check also keeps response times similar.
  2. 2. What is the purpose of calling session.clear() right before storing user_id?

    Starting login from an empty session means a pre-set session identifier cannot be reused after authentication.
  3. 3. A logged-in user without the admin role opens /admin. Which response is correct?

    The user is known but not allowed. Redirecting to the login page would be misleading; 403 states the real problem.
  4. 4. Why is the role looked up in the database on each request instead of being stored in the session cookie?

    The cookie is only signed and could be stale. Looking the user up keeps permissions current.
  5. 5. What does the is_safe_next check protect against?

    Only paths that start with a single slash stay on your site. A full URL or a //host value would send the user away.

Summary

  • Store only salted password hashes; the demo uses a fast hash setting, production should keep Werkzeug's strong default.
  • Keep just the user id in the session, call session.clear() on login, and load the user (and role) from the database in a before_request hook.
  • Use one generic failure message for login, and verify against a dummy hash for unknown users.
  • Decorators separate the two failures: redirect strangers to the login page, return 403 to users without permission.
  • Protect every POST with a CSRF token kept in the session, and accept only local paths in next.
  • Flash messages plus Post/Redirect/Get give clear feedback without resubmitted forms.

Next: Project: A Mini Bookshop, where you combine a database, a session cart and an order flow.