Spaces:
Sleeping
Sleeping
import streamlit as st | |
import json | |
import os | |
import random | |
import string | |
if 'username' not in st.session_state: | |
st.session_state.username = '' | |
if 'scratch_pad' not in st.session_state: | |
st.session_state.scratch_pad = '' | |
history_file = 'user_history.json' | |
if not os.path.exists(history_file): | |
with open(history_file, 'w') as file: | |
json.dump({}, file) | |
with open(history_file, 'r') as file: | |
user_history = json.load(file) | |
def save_session(username, password): | |
st.session_state.username = username | |
st.session_state.scratch_pad = st.session_state.scratch_pad | |
user_history[username] = { | |
'password': password, | |
'scratch_pad': st.session_state.scratch_pad | |
} | |
with open(history_file, 'w') as file: | |
json.dump(user_history, file) | |
def register_user(username, password): | |
if username not in user_history: | |
save_session(username, password) | |
st.success("User registered successfully!") | |
else: | |
st.warning("Username already exists. Please choose a different username.") | |
def login_user(username, password): | |
if username in user_history: | |
stored_password = user_history[username]['password'] | |
if password == stored_password: | |
st.session_state.username = username | |
st.session_state.scratch_pad = user_history[username]['scratch_pad'] | |
st.success("Logged in successfully!") | |
return True | |
else: | |
st.error("Incorrect password. Please try again.") | |
else: | |
st.warning("Username not found. Please register first.") | |
return False | |
def reset_password(username): | |
if username in user_history: | |
new_password = ''.join(random.choices(string.ascii_letters + string.digits, k=8)) | |
user_history[username]['password'] = new_password | |
with open(history_file, 'w') as file: | |
json.dump(user_history, file) | |
st.success(f"Password reset successful. Your new password is: {new_password}") | |
else: | |
st.warning("Username not found.") | |
st.title("Welcome to My App") | |
if st.session_state.username: | |
st.subheader(f"Welcome back, {st.session_state.username}!") | |
scratch_pad = st.text_area("Scratch Pad", value=st.session_state.scratch_pad, height=200) | |
if st.button("πΎ Save"): | |
save_session(st.session_state.username, user_history[st.session_state.username]['password']) | |
if st.button("π Reset Password"): | |
reset_password(st.session_state.username) | |
else: | |
username = st.text_input("Username:") | |
password = st.text_input("Password:", type="password") | |
col1, col2 = st.columns(2) | |
with col1: | |
if st.button("π Login"): | |
if login_user(username, password): | |
st.experimental_rerun() | |
with col2: | |
if st.button("π Register"): | |
register_user(username, password) |