✅ Lesson 6.1: User Authentication and Session Handling
🎯 Lesson Objectives
By the end of this lesson, you will be able to:
-
Understand the importance of securing your chatbot with user authentication.
-
Implement login and registration systems using popular Python frameworks.
-
Manage user sessions to track activity and personalize experiences.
-
Secure API routes and protect access to sensitive or paid features.
-
Prepare your app for multi-user scenarios with persistent sessions.
🧠 1. Why Do You Need Authentication?
As your chatbot grows, you’ll want to:
-
Track users individually for personalization
-
Protect premium features or admin tools
-
Store and retrieve memory specific to each user
-
Ensure security for data-sensitive use cases (e.g., legal, medical, education)
Authentication allows you to verify a user’s identity and manage access accordingly.
🔐 2. Authentication vs. Authorization
| Concept | Meaning | Example |
|---|---|---|
| Authentication | Verifying identity (who are you?) | Logging in with username/password |
| Authorization | Granting permissions (what can you do?) | Admins can upload documents, others can’t |
🛠️ 3. Implementing Authentication in Python
We’ll cover two approaches:
✅ Option A: Streamlit with Session State
Great for prototypes and internal apps.
import streamlit as st
# Dummy users
users = {"ronald": "1234", "admin": "adminpass"}
if "logged_in" not in st.session_state:
st.session_state.logged_in = False
if not st.session_state.logged_in:
st.title("Login")
username = st.text_input("Username")
password = st.text_input("Password", type="password")
if st.button("Login"):
if username in users and users[username] == password:
st.session_state.logged_in = True
st.session_state.username = username
st.success("Logged in!")
else:
st.error("Invalid credentials")
else:
st.sidebar.success(f"Welcome {st.session_state.username}!")
st.title("Chat Interface")
# Chat UI goes here
💡 Add role-based access:
if st.session_state.username == "admin":
st.sidebar.button("Go to Admin Panel")
✅ Option B: Flask + Sessions + SQLite (Production-Ready)
Step 1: Install
pip install flask flask-login flask-sqlalchemy
Step 2: Setup Flask App with Auth
from flask import Flask, request, redirect, url_for, render_template, session
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = "secret_key"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
Step 3: Create User Model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
password_hash = db.Column(db.String(128))
Step 4: Register & Login Routes
@app.route('/register', methods=['POST'])
def register():
data = request.json
hashed_pw = generate_password_hash(data['password'])
new_user = User(username=data['username'], password_hash=hashed_pw)
db.session.add(new_user)
db.session.commit()
return {"message": "User created!"}
@app.route('/login', methods=['POST'])
def login():
data = request.json
user = User.query.filter_by(username=data['username']).first()
if user and check_password_hash(user.password_hash, data['password']):
session['user'] = user.username
return {"message": "Logged in!"}
return {"error": "Invalid credentials"}, 401
📦 4. Handling Sessions
Once logged in, you want to:
-
Persist the user’s identity across pages or API calls
-
Attach user context to chat sessions or memory
✅ In Streamlit:
# Already handled via st.session_state
st.session_state["username"]
✅ In Flask:
# Use Flask sessions
if "user" in session:
username = session["user"]
# Load user-specific memory or preferences
🔐 5. Securing Routes
Only allow access to sensitive endpoints if the user is authenticated:
@app.route('/chat', methods=['POST'])
def chat():
if "user" not in session:
return {"error": "Unauthorized"}, 401
# Proceed with chat logic
For admin-only routes:
if session.get("user") != "admin":
return {"error": "Forbidden"}, 403
🛡️ 6. Security Best Practices
| Tip | Why It Matters |
|---|---|
| Use hashed passwords | Prevents password leaks |
| Set a secret key | Required for secure session cookies |
| Use HTTPS in production | Protects credentials from interception |
| Store sessions in DB (prod) | Enables scaling across multiple servers |
| Implement rate limiting | Prevents brute-force login attacks |
🧪 7. Practice Activity
🔧 Assignment:
Create a login system (Streamlit or Flask).
Store users in a dictionary or SQLite DB.
Show different chatbot options depending on the logged-in user (e.g., admin, user).
Protect a route like
/adminor/upload-docsto only allow authorized access.Save the user’s name and session so it can personalize the chatbot greeting.
❓ 8. Comprehension Check
-
What’s the difference between authentication and authorization?
-
How can Streamlit maintain user state?
-
Why is it critical to hash passwords?
-
What are some ways to protect chat endpoints from unauthorized access?
📘 9. Further Resources
71
