Search⌘ K
AI Features

Solution: Create a Login and Logout Mechanism

Explore how to implement a login and logout system in a Flask web app. Learn to manage user sessions securely, perform authentication checks, and update templates dynamically to reflect user state. This lesson enables you to build functional user access control with proper session tracking and redirection.

We'll cover the following...

We can analyze the complete architectural fix by inspecting our finished code components. We update our application routing controller logic to manage active identity dictionary lookups.

Python 3.14.0
from flask import Flask, render_template, request, session, redirect, url_for
from werkzeug.security import generate_password_hash, check_password_hash
from forms import LoginForm, SignUpForm
app = Flask(__name__)
app.config["SECRET_KEY"] = "dfewfew123213rwdsgert34tgfd1234trgf"
# Store cryptographically salted hashes instead of vulnerable plaintext credentials
users = {
"educative@email.com": "scrypt:32768:8:1$qJTfNtUmDqx9sVYM$4ee10448b9c45da5415ef44ef116e8d8c66c203d6e068876929c6a40771b3b2568306c26905addd58ae9fbda9d6f3f12298ab9f0ef4306f3a37725d26bd30fad",
"admin@email.com": "scrypt:32768:8:1$BZ1NrEDCZ48uMFKp$41156891228c1ed7f0a42ec1d4781e10a45f086c632f3016457fd79efc703a21ebbb66ae1d697b41ce78bd654133ffc14b61d2abad89b1c93abb6db95e52fbb7"
}
cats = [
{"id": 1, "name": "Buddy", "age": 3, "bio": "A friendly ginger cat.", "image": "cat1.jpg"},
{"id": 2, "name": "Luna", "age": 2, "bio": "A playful black cat full of energy.", "image": "cat2.jpg"},
{"id": 3, "name": "Milo", "age": 1, "bio": "A curious kitten who loves to explore.", "image": "cat3.jpg"},
{"id": 4, "name": "Bella", "age": 4, "bio": "A calm cat that enjoys quiet spaces.", "image": "cat4.jpg"}
]
@app.route("/")
def homepage():
return render_template("home.html", title="Paws Rescue Center 🐾", cats=cats)
@app.route("/signup", methods=["POST", "GET"])
def signup():
"""View function for handling the registration form interface."""
form = SignUpForm()
# Intercept submission traffic and run validation rule arrays
if form.validate_on_submit():
# Securely hash the plaintext password from the form before writing to storage
hashed_password = generate_password_hash(form.password.data)
# Store the credential pair by mapping the email string key to the new secure hash token
users[form.email.data] = hashed_password
return render_template("signup.html", form=form, message="Successfully signed up")
return render_template("signup.html", form=form)
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
email = form.email.data
password = form.password.data
if email in users and check_password_hash(users[email], password):
# Store identity parameters directly within the global state dictionary
session["user"] = email
# Force secure client redirection straight to our landing dashboard view
return redirect(url_for("homepage", _scheme="https", _external=True))
return render_template("login.html", form=form, message="Incorrect Email or Password")
return render_template("login.html", form=form)
@app.route("/logout")
def logout():
"""Terminate persistent identity tracking keys and clear view states."""
session.pop("user", None)
form = LoginForm()
# Route back to the authentication screen showing a clear status update banner
return render_template("login.html", form=form, message="You have been logged out successfully.")
@app.route("/about")
def about():
page_title = "About Us"
page_desc = "We are a non-profit organization working as an animal rescue."
return render_template("about.html", title=page_title, description=page_desc)
@app.route("/cat/<int:cat_id>")
def cat_details(cat_id):
cat = None
for c in cats:
if c["id"] == cat_id:
cat = c
break
return render_template("details.html", cat=cat)
  • Line 1: We import our standard framework ...