Update app.py
Browse files
app.py
CHANGED
|
@@ -1,44 +1,27 @@
|
|
| 1 |
-
|
| 2 |
-
"""
|
| 3 |
-
Flask Login System with SQLite
|
| 4 |
-
Features:
|
| 5 |
-
- 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 |
-
|
| 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
|
| 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,
|
| 40 |
-
username TEXT UNIQUE NOT NULL,
|
| 41 |
-
password TEXT NOT NULL
|
| 42 |
)
|
| 43 |
""")
|
| 44 |
conn.commit()
|
|
@@ -47,106 +30,72 @@ def init_db():
|
|
| 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"]
|
| 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":
|
| 71 |
username = request.form["username"]
|
| 72 |
password = request.form["password"]
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
conn = get_db_connection()
|
| 75 |
try:
|
| 76 |
-
|
| 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 |
-
|
| 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":
|
| 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 |
-
|
|
|
|
| 103 |
conn = get_db_connection()
|
| 104 |
-
user = conn.execute("SELECT * FROM users WHERE username=?
|
| 105 |
-
(username, password)).fetchone()
|
| 106 |
conn.close()
|
| 107 |
|
| 108 |
-
if user:
|
| 109 |
-
|
| 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 |
-
|
| 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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from flask import Flask, render_template, request, redirect, url_for, session, make_response
|
| 2 |
import sqlite3
|
| 3 |
from datetime import timedelta
|
| 4 |
+
from werkzeug.security import generate_password_hash, check_password_hash
|
| 5 |
|
| 6 |
# Flask App Setup
|
| 7 |
app = Flask(__name__)
|
| 8 |
+
app.secret_key = "supersecretkey" # Secret key (keep it secret in production)
|
| 9 |
+
app.permanent_session_lifetime = timedelta(days=7) # For "Remember Me"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# Helper function to connect to SQLite database
|
| 12 |
def get_db_connection():
|
|
|
|
| 13 |
conn = sqlite3.connect("users.db")
|
| 14 |
+
conn.row_factory = sqlite3.Row
|
| 15 |
return conn
|
| 16 |
|
|
|
|
| 17 |
# Initialize database with a "users" table
|
| 18 |
def init_db():
|
| 19 |
conn = get_db_connection()
|
| 20 |
conn.execute("""
|
| 21 |
CREATE TABLE IF NOT EXISTS users (
|
| 22 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 23 |
+
username TEXT UNIQUE NOT NULL,
|
| 24 |
+
password TEXT NOT NULL
|
| 25 |
)
|
| 26 |
""")
|
| 27 |
conn.commit()
|
|
|
|
| 30 |
# Call database initialization at startup
|
| 31 |
init_db()
|
| 32 |
|
|
|
|
| 33 |
# Home Page (only logged-in users can see this)
|
| 34 |
@app.route("/")
|
| 35 |
def home():
|
|
|
|
| 36 |
if "username" in session:
|
| 37 |
+
username = session["username"]
|
|
|
|
|
|
|
| 38 |
last_visit = request.cookies.get("last_visit", "First time visiting!")
|
|
|
|
| 39 |
return render_template("home.html", username=username, last_visit=last_visit)
|
|
|
|
|
|
|
| 40 |
return redirect(url_for("login"))
|
| 41 |
|
|
|
|
| 42 |
# Signup Page
|
| 43 |
@app.route("/signup", methods=["GET", "POST"])
|
| 44 |
def signup():
|
| 45 |
+
if request.method == "POST":
|
| 46 |
username = request.form["username"]
|
| 47 |
password = request.form["password"]
|
| 48 |
|
| 49 |
+
print("Signup attempt:", username, password)
|
| 50 |
+
|
| 51 |
+
hashed_password = generate_password_hash(password)
|
| 52 |
+
|
| 53 |
conn = get_db_connection()
|
| 54 |
try:
|
| 55 |
+
conn.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hashed_password))
|
|
|
|
| 56 |
conn.commit()
|
| 57 |
conn.close()
|
|
|
|
|
|
|
| 58 |
return redirect(url_for("login"))
|
|
|
|
| 59 |
except sqlite3.IntegrityError:
|
| 60 |
+
return "❌ Username already exists! Try another."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
return render_template("signup.html")
|
| 63 |
|
| 64 |
# Login Page
|
| 65 |
@app.route("/login", methods=["GET", "POST"])
|
| 66 |
def login():
|
| 67 |
+
if request.method == "POST":
|
| 68 |
username = request.form["username"]
|
| 69 |
password = request.form["password"]
|
|
|
|
|
|
|
| 70 |
remember = request.form.get("remember")
|
| 71 |
|
| 72 |
+
print("Login attempt:", username, password, "Remember:", remember)
|
| 73 |
+
|
| 74 |
conn = get_db_connection()
|
| 75 |
+
user = conn.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone()
|
|
|
|
| 76 |
conn.close()
|
| 77 |
|
| 78 |
+
if user and check_password_hash(user["password"], password):
|
| 79 |
+
session.permanent = True if remember == "on" else False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
session["username"] = username
|
| 81 |
|
|
|
|
| 82 |
resp = make_response(redirect(url_for("home")))
|
| 83 |
+
resp.set_cookie("last_visit", "Welcome back, " + username,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
max_age=(7*24*60*60 if remember == "on" else None))
|
|
|
|
| 85 |
return resp
|
| 86 |
else:
|
| 87 |
+
return "❌ Invalid username or password. Try again."
|
|
|
|
| 88 |
|
|
|
|
| 89 |
return render_template("login.html")
|
| 90 |
|
|
|
|
| 91 |
# Logout Page
|
| 92 |
@app.route("/logout")
|
| 93 |
def logout():
|
|
|
|
| 94 |
session.pop("username", None)
|
|
|
|
|
|
|
| 95 |
resp = make_response(redirect(url_for("login")))
|
| 96 |
resp.set_cookie("last_visit", "", expires=0)
|
| 97 |
return resp
|
| 98 |
|
|
|
|
| 99 |
# Run the App
|
| 100 |
if __name__ == "__main__":
|
| 101 |
+
app.run(debug=True, host="0.0.0.0", port=5000)
|