🐍 Lesson 35: Flask User Authentication – Login, Logout & Sessions
Welcome to Lesson 35! Today we’ll learn how to manage user authentication in Flask apps. This includes login, logout, and session management, which are essential for any real web application.
💡 Key Benefits of Learning User Authentication
- Protect sensitive pages and resources in your app
- Keep user data secure with sessions
- Enable personalized user experiences
- Control and manage access to your web app
📌 Why User Authentication?
- Protect sensitive pages
- Keep user data secure
- Enable personalized experiences
- Control access to your web app
📂 1. Project Structure
project/
│── app.py
│── templates/
│── login.html
│── dashboard.html
📦 2. Setting Up Flask & Session
from flask import Flask, render_template, request, redirect, url_for, session
app = Flask(__name__)
app.secret_key = "your_secret_key" # Needed to use sessions
📄 3. Create Login Form
Create templates/login.html:
Login
📦 4. Handling Login in Flask
# Dummy users dictionary for example
users = {"admin": "1234", "alice": "abcd"}
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
if username in users and users[username] == password:
session["user"] = username
return redirect(url_for("dashboard"))
else:
return "Invalid Credentials!"
return render_template("login.html")
📦 5. Protecting Routes (Dashboard)
@app.route("/dashboard")
def dashboard():
if "user" in session:
return f"Welcome {session['user']}! This is your dashboard."
else:
return redirect(url_for("login"))
📦 6. Logout Functionality
@app.route("/logout")
def logout():
session.pop("user", None)
return redirect(url_for("login"))
🧠 Why Sessions Are Important
- Keep users logged in across pages
- Store temporary user information
- Essential for full-stack apps with accounts
❓ Frequently Asked Questions (FAQ)
1. What is Flask session management?
Flask uses sessions to store data on the server side, making it possible to remember users between requests. Sessions are stored securely in the browser using cookies.
2. How do I secure the user login form?
To secure the login form, always hash passwords before storing them in your app's database. You can use libraries like werkzeug.security to hash and check passwords securely.
3. What is the purpose of session['user']?
In Flask, the session object is used to store information about the current user (e.g., the username). This allows Flask to remember the user across different requests, ensuring they are logged in until they log out or the session expires.
4. Can I use databases for user authentication instead of a dictionary?
Yes! Instead of using a hardcoded dictionary, you can store user credentials in a database (e.g., using SQLAlchemy) and authenticate users dynamically based on the data in the database.
5. What is Flask’s secret_key used for?
The secret_key in Flask is used to sign session cookies, making it difficult for attackers to tamper with the session data. Make sure to set it to a random and secure value in production.
❌ Common Misconceptions About Flask User Authentication
- “Flask is not secure for user authentication.” – Flask can be secure for authentication if you implement proper security measures such as password hashing, HTTPS, and secure session management.
- “You don’t need to handle session expiry.” – While Flask automatically handles session expiry, it’s essential to set a session timeout and implement session renewal to improve security.
- “You don’t need to validate user input in Flask forms.” – Always validate user input to prevent SQL injection, XSS attacks, and ensure data integrity.
🧪 Practice
- Add a “Remember Me” checkbox using sessions.
- Display the logged-in user’s name on all pages.
- Protect multiple routes with session checking.
- Integrate with a database (SQLAlchemy) for real user accounts.
Comments
Post a Comment