π 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
Welcome back, !
This protected route checks if "user" in session: before rendering. Visitors who aren't logged in get redirected back to /login.
π§ How Authentication Works in 4 Steps
- Zero Extra Packages Needed: When you run
pip install flask, Flask automatically installswerkzeugβwhich gives you built-in password hashing functions. - 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. - Verify & Create a Session Cookie: On login (
/login),check_password_hash()compares the typed password with the saved hash. If it matches, Flask storessession["user"] = usernamein a signed browser cookie. - Protect Private Pages: On
/(your dashboard), check if"user"exists insession. Callingsession.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:
user_id column to tasks so each user only sees their own to-dos.is_admin INTEGER DEFAULT 0 column to unlock an /admin panel.email and bio columns and let logged-in users edit their profile.