BharatPlay / src /auth.py
jayanth-2005's picture
Update src/auth.py
9261648 verified
Raw History Blame Contribute Delete
1.5 kB
# ✅ 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)