Spaces:
Sleeping
Sleeping
File size: 1,503 Bytes
9261648 2e8104f 9261648 2e8104f 9261648 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | # ✅ auth.py (Updated with persistent login tracking)
import sqlite3
import hashlib
import os
import tempfile
# Persistent DB and login state file
DB_PATH = os.path.join(tempfile.gettempdir(), "users.db")
LOGIN_STATE_FILE = os.path.join(tempfile.gettempdir(), "last_login.txt")
def get_connection():
conn = sqlite3.connect(DB_PATH)
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password TEXT
)
""")
return conn
def hash_password(password):
return hashlib.sha256(password.encode()).hexdigest()
def signup_user(username, password):
conn = get_connection()
try:
conn.execute("INSERT INTO users VALUES (?, ?)", (username, hash_password(password)))
conn.commit()
return True
except sqlite3.IntegrityError:
return False
finally:
conn.close()
def login_user(username, password):
conn = get_connection()
hashed = hash_password(password)
result = conn.execute("SELECT * FROM users WHERE username=? AND password=?", (username, hashed)).fetchone()
conn.close()
return result is not None
def save_login(username):
with open(LOGIN_STATE_FILE, "w") as f:
f.write(username)
def load_login():
if os.path.exists(LOGIN_STATE_FILE):
with open(LOGIN_STATE_FILE, "r") as f:
return f.read().strip()
return None
def logout_user():
if os.path.exists(LOGIN_STATE_FILE):
os.remove(LOGIN_STATE_FILE)
|