Build Real Apps
From Scratch

Learn. Practice. Ship.

Starter App Build Python Flask SQLite Auth & Sessions

πŸ” Flask + SQLite Login & Signup Auth

Every web app eventually needs user accounts. Learn how to register users, hash passwords safely with Werkzeug, and protect private routes using Flask sessionsβ€”all inside a single 65-line file.

πŸ–₯️ Live Auth Flow Preview

Test creating an account, logging in, and viewing a protected dashboard

⚑ Last Executed SQLite / Session Action:
SELECT id, username, password_hash FROM users WHERE username = ?;

🧠 How Authentication Works in 4 Steps

  1. Zero Extra Packages Needed: When you run pip install flask, Flask automatically installs werkzeugβ€”which gives you built-in password hashing functions.
  2. Never Store Plain Passwords: On signup (/signup), generate_password_hash() scrambles the user's password into a secure cryptographic string before saving it to SQLite.
  3. Verify & Create a Session Cookie: On login (/login), check_password_hash() compares the typed password with the saved hash. If it matches, Flask stores session["user"] = username in a signed browser cookie.
  4. Protect Private Pages: On / (your dashboard), check if "user" exists in session. Calling session.clear() logs the user out cleanly.

Common Beginner Error Fix: If you see RuntimeError: The session is unavailable because no secret key was set, make sure app.secret_key = "your-random-secret" is defined right below app = Flask(__name__).

πŸ“„ Starter Source Code (app.py)

Complete single-file Flask + SQLite auth app with hashed passwords

import sqlite3
from flask import Flask, request, redirect, session, render_template_string
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = "change-this-to-a-random-secret-key"

def get_db():
    conn = sqlite3.connect("users.db")
    conn.row_factory = sqlite3.Row
    return conn

with get_db() as db:
    db.execute("""
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL
        )
    """)

HTML = """
<!doctype html>
<body style="font-family:sans-serif; max-width:400px; margin:50px auto;">
  {% if msg %}<p style="color:crimson;">{{ msg }}</p>{% endif %}

  {% if session.get('user') %}
    <h2>Welcome, {{ session['user'] }}! πŸŽ‰</h2>
    <p>You are viewing a protected dashboard route.</p>
    <a href="/logout">Log Out</a>
  {% else %}
    <h2>Log In</h2>
    <form action="/login" method="POST" style="display:grid; gap:8px; margin-bottom:24px;">
      <input name="username" placeholder="Username" required style="padding:8px;">
      <input name="password" type="password" placeholder="Password" required style="padding:8px;">
      <button type="submit">Log In</button>
    </form>

    <h3>New here? Create an Account</h3>
    <form action="/signup" method="POST" style="display:grid; gap:8px;">
      <input name="username" placeholder="Choose username" required style="padding:8px;">
      <input name="password" type="password" placeholder="Choose password" required style="padding:8px;">
      <button type="submit">Sign Up</button>
    </form>
  {% endif %}
</body>
"""

@app.route("/")
def home():
    return render_template_string(HTML, msg=request.args.get("msg"))

@app.route("/signup", methods=["POST"])
def signup():
    username = request.form["username"].strip()
    pw_hash = generate_password_hash(request.form["password"])
    try:
        with get_db() as db:
            db.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", (username, pw_hash))
        session["user"] = username
        return redirect("/")
    except sqlite3.IntegrityError:
        return redirect("/?msg=Username+already+taken")

@app.route("/login", methods=["POST"])
def login():
    username = request.form["username"].strip()
    user = get_db().execute("SELECT * FROM users WHERE username = ?", (username,)).fetchone()
    if user and check_password_hash(user["password_hash"], request.form["password"]):
        session["user"] = user["username"]
        return redirect("/")
    return redirect("/?msg=Invalid+username+or+password")

@app.route("/logout")
def logout():
    session.clear()
    return redirect("/")

if __name__ == "__main__":
    app.run(debug=True)

πŸš€ Build Your Own App With This Template

Combine this auth starter with your CRUD starter to create multi-user apps:

πŸ”’ Private Task Manager
Add a user_id column to tasks so each user only sees their own to-dos.
πŸ›‘οΈ Admin Role Check
Add an is_admin INTEGER DEFAULT 0 column to unlock an /admin panel.
πŸ‘€ User Profile Page
Add email and bio columns and let logged-in users edit their profile.
← Back to All Projects