import hashlib import json import os import gradio as gr # File to store user credentials USERS_FILE = "users.json" def load_users(): """Load users from JSON file""" if os.path.exists(USERS_FILE): with open(USERS_FILE, "r") as f: return json.load(f) return {} def save_users(users): """Save users to JSON file""" with open(USERS_FILE, "w") as f: json.dump(users, f) def hash_password(password): """Hash password using SHA-256""" return hashlib.sha256(password.encode()).hexdigest() def register_user(username, password, confirm_password): """Register a new user""" if not username or not password: return "", "Username and password cannot be empty!", None if password != confirm_password: return "", "Passwords do not match!", None if len(password) < 6: return "", "Password must be at least 6 characters long!", None users = load_users() if username in users: return "", "Username already exists!", None users[username] = hash_password(password) save_users(users) return "", f"✅ Registration successful! You can now login.", None def login_user(username, password, state): """Validate user login""" if not username or not password: return ( "Please enter both username and password!", "", state, gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(open=True), ) users = load_users() if username not in users: return ( "Invalid username or password!", "", state, gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(open=True), ) if users[username] != hash_password(password): return ( "Invalid username or password!", "", state, gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(open=True), ) # Login successful state = {"logged_in": True, "username": username} return ( f"✅ Welcome back, {username}!", "", state, gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(open=False), ) def logout_user(state): """Logout current user""" state = {"logged_in": False, "username": None} return ( "Logged out successfully!", state, gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), ) def protected_content(state): """Content only accessible to logged-in users""" if state.get("logged_in"): return f"You are logged as {state.get('username')}\n" return "Please login to access this content."