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
- Signup (create new account)
|
| 6 |
+
- Login (check user credentials)
|
| 7 |
+
- Session (to remember login state)
|
| 8 |
+
- Cookies (to store last visit info)
|
| 9 |
+
- "Remember Me" option (stay logged in even after closing browser)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from flask import Flask, render_template, request, redirect, url_for, session, make_response
|
| 13 |
+
import sqlite3
|
| 14 |
+
from datetime import timedelta
|
| 15 |
+
|
| 16 |
+
# Flask App Setup
|
| 17 |
+
app = Flask(__name__)
|
| 18 |
+
|
| 19 |
+
# Secret key is used to sign session data (must be kept secret in real apps!)
|
| 20 |
+
app.secret_key = "supersecretkey"
|
| 21 |
+
|
| 22 |
+
# Permanent sessions last for 7 days (used when "Remember Me" is checked)
|
| 23 |
+
app.permanent_session_lifetime = timedelta(days=7)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Helper function to connect to SQLite database
|
| 27 |
+
def get_db_connection():
|
| 28 |
+
# Connect to SQLite database (creates file users.db if it doesn’t exist)
|
| 29 |
+
conn = sqlite3.connect("users.db")
|
| 30 |
+
conn.row_factory = sqlite3.Row # Makes rows behave like dictionaries
|
| 31 |
+
return conn
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Initialize database with a "users" table
|
| 35 |
+
def init_db():
|
| 36 |
+
conn = get_db_connection()
|
| 37 |
+
conn.execute("""
|
| 38 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 39 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, -- Auto-increment ID
|
| 40 |
+
username TEXT UNIQUE NOT NULL, -- Unique username
|
| 41 |
+
password TEXT NOT NULL -- Password (plain text for demo, should use hashing!)
|
| 42 |
+
)
|
| 43 |
+
""")
|
| 44 |
+
conn.commit()
|
| 45 |
+
conn.close()
|
| 46 |
+
|
| 47 |
+
# Call database initialization at startup
|
| 48 |
+
init_db()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Home Page (only logged-in users can see this)
|
| 52 |
+
@app.route("/")
|
| 53 |
+
def home():
|
| 54 |
+
# Check if the user is logged in using session
|
| 55 |
+
if "username" in session:
|
| 56 |
+
username = session["username"] # Get logged-in username from session
|
| 57 |
+
|
| 58 |
+
# Get last visit message from cookie (if not found, show default message)
|
| 59 |
+
last_visit = request.cookies.get("last_visit", "First time visiting!")
|
| 60 |
+
|
| 61 |
+
return render_template("home.html", username=username, last_visit=last_visit)
|
| 62 |
+
|
| 63 |
+
# If not logged in, redirect to login page
|
| 64 |
+
return redirect(url_for("login"))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# Signup Page
|
| 68 |
+
@app.route("/signup", methods=["GET", "POST"])
|
| 69 |
+
def signup():
|
| 70 |
+
if request.method == "POST": # When user submits the form
|
| 71 |
+
username = request.form["username"]
|
| 72 |
+
password = request.form["password"]
|
| 73 |
+
|
| 74 |
+
conn = get_db_connection()
|
| 75 |
+
try:
|
| 76 |
+
# Insert new user into database
|
| 77 |
+
conn.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password))
|
| 78 |
+
conn.commit()
|
| 79 |
+
conn.close()
|
| 80 |
+
|
| 81 |
+
# After signup, redirect to login page
|
| 82 |
+
return redirect(url_for("login"))
|
| 83 |
+
|
| 84 |
+
except sqlite3.IntegrityError:
|
| 85 |
+
# This happens if the username already exists
|
| 86 |
+
return "Username already exists! Try another."
|
| 87 |
+
|
| 88 |
+
# If GET request, show signup form
|
| 89 |
+
return render_template("signup.html")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Login Page
|
| 93 |
+
@app.route("/login", methods=["GET", "POST"])
|
| 94 |
+
def login():
|
| 95 |
+
if request.method == "POST": # When user submits login form
|
| 96 |
+
username = request.form["username"]
|
| 97 |
+
password = request.form["password"]
|
| 98 |
+
|
| 99 |
+
# Checkbox value: will be "on" if user ticks "Remember Me"
|
| 100 |
+
remember = request.form.get("remember")
|
| 101 |
+
|
| 102 |
+
# Check if username & password exist in database
|
| 103 |
+
conn = get_db_connection()
|
| 104 |
+
user = conn.execute("SELECT * FROM users WHERE username=? AND password=?",
|
| 105 |
+
(username, password)).fetchone()
|
| 106 |
+
conn.close()
|
| 107 |
+
|
| 108 |
+
if user:
|
| 109 |
+
# ✅ User found → start session
|
| 110 |
+
if remember == "on":
|
| 111 |
+
# Session will survive browser close (7 days)
|
| 112 |
+
session.permanent = True
|
| 113 |
+
else:
|
| 114 |
+
# Session ends when browser closes
|
| 115 |
+
session.permanent = False
|
| 116 |
+
|
| 117 |
+
# Store username inside session
|
| 118 |
+
session["username"] = username
|
| 119 |
+
|
| 120 |
+
# Create response with cookie
|
| 121 |
+
resp = make_response(redirect(url_for("home")))
|
| 122 |
+
|
| 123 |
+
# Save a cookie with "last visit" info
|
| 124 |
+
# If "Remember Me" checked → cookie valid for 7 days
|
| 125 |
+
# Else → cookie lasts only until browser closes
|
| 126 |
+
resp.set_cookie("last_visit", "Welcome back, " + username,
|
| 127 |
+
max_age=(7*24*60*60 if remember == "on" else None))
|
| 128 |
+
|
| 129 |
+
return resp
|
| 130 |
+
else:
|
| 131 |
+
# If username or password is wrong
|
| 132 |
+
return "Invalid username or password. Try again."
|
| 133 |
+
|
| 134 |
+
# If GET request, show login form
|
| 135 |
+
return render_template("login.html")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# Logout Page
|
| 139 |
+
@app.route("/logout")
|
| 140 |
+
def logout():
|
| 141 |
+
# Remove username from session
|
| 142 |
+
session.pop("username", None)
|
| 143 |
+
|
| 144 |
+
# Also delete the "last_visit" cookie
|
| 145 |
+
resp = make_response(redirect(url_for("login")))
|
| 146 |
+
resp.set_cookie("last_visit", "", expires=0)
|
| 147 |
+
return resp
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# Run the App
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
app.run(debug=True, host="0.0.0.0", port=5000)
|