-
Notifications
You must be signed in to change notification settings - Fork 0
/
S_02_user_registration_streamlit.py
152 lines (120 loc) · 5.76 KB
/
S_02_user_registration_streamlit.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# Streamlit-based User Registration with Database Integration
import streamlit as st
import bcrypt
import sqlite3
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from config import db_path, SCOPES, credentials_path
from functions import view_db, clear_db
# Function to hash password securely (already in your original code)
def hash_password(password):
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed
# Function to prepare user data for registration
def prepare_user_data_for_registration(username, email, password, habit, level, refresh_token):
user_data = {
'username': username,
'email': email,
'password_hash': hash_password(password), # Assuming password hashing is needed
'habit': habit,
'level': level,
'refresh_token': refresh_token
}
return user_data
# Function to save user data to the database (integrating your original code logic)
def save_user_data_to_database(user_data):
# Connect to the database
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA foreign_keys = ON") # Enforces foreign key constraint => ensures all other table link to a valid id in users
cursor = conn.cursor()
try:
cursor.execute("""
INSERT INTO users (username, email, password_hash, habit, level, refresh_token)
VALUES (:username, :email, :password_hash, :habit, :level, :refresh_token)
""", user_data)
# selects the data out of the user_data dict
conn.commit()
print("User registered successfully.")
# Fetch the last inserted user ID
cursor.execute("SELECT last_insert_rowid()")
user_id = cursor.fetchone()[0]
# Save the user ID to currentUser.py
save_user_id_to_file(user_id)
except sqlite3.IntegrityError:
print("An error occurred. No users were registered. Database was not modified.")
conn.rollback() # Rolls back all made entries into the database
finally:
conn.close()
def save_user_id_to_file(user_id):
with open('currentUser.py', 'w') as f:
f.write(f"user_id = {user_id}")
def user_registration():
print('Wohoo made it to notebook S_02.')
# Streamlit form for user input
st.image("data/hey_bit_logo_small.png", caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="JPEG")
st.title(":grey[Welcome to Hey_Bit!]")
st.subheader(":grey[Your calendar integrated AI habit app]")
st.write("")
# Collect user input
username = st.text_input("Username", key="user")
email = st.text_input("Email", key="email")
password = st.text_input("Password", type="password")
# Habit selection with a placeholder option
habit_options = ["Please select a habit", "Fitness", "Piano", "Gestalt", "Lifting", "Stop Smoking", "Start Smoking", "Smoke and Drink"]
habit = st.selectbox("Habit", habit_options)
# habit = st.selectbox("Habit", ["Fitness", "Piano", "Gestalt", "Lifting", "Stop Smoking", "Start smoking", "Smoke and drink"])
# level = st.slider("Level", 1, 3, 2)
# Habit descriptions
habit_descriptions = {
"Fitness": "Engaging in regular physical activities to improve your health.",
"Piano": "Practicing and improving your skills in playing the piano.",
#"Gestalt": "Exploring Gestalt principles for personal and professional growth.",
"Lifting": "Building strength and endurance through weightlifting.",
"Stop Smoking": "Taking steps to quit smoking and improve your well-being.",
#"Start Smoking": "Starting a smoking habit to become cooler.",
"Smoke and Drink": "Combining smoking and drinking to become even cooler."
}
# Display the habit description
if habit != "Please select a habit" and habit in habit_descriptions:
st.write(f"**Selecting this habit will provide a plan that supports you in developing a habit of:**")
st.write(f"{habit_descriptions[habit]}")
st.write("")
# Mapping of levels to labels
level_mapping = {
1: "Beginner",
2: "Intermediate",
3: "Advanced"
}
# Reverse the mapping to access numeric values based on the label
label_mapping = {v: k for k, v in level_mapping.items()}
# Create the slider with text labels
selected_label = st.select_slider(
"Please select your current level:",
options=list(level_mapping.values()), # Options are the text labels
value="Intermediate" # Default value
)
st.write("")
# Get the numeric value corresponding to the selected label
selected_level = label_mapping[selected_label]
level = selected_level
user_data = {}
# Button to submit the form
if st.button("Submit"):
if username and email and password and habit != "Please select a habit" and level:
flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES)
creds = flow.run_local_server(port=0)
refresh_token = creds.refresh_token
# Prepare user data for registration
user_data = prepare_user_data_for_registration(username, email, password, habit, level, refresh_token)
# Save the user data to the database
save_user_data_to_database(user_data)
st.success("User registration data saved successfully!")
st.write(user_data) # Display the user data for confirmation
else:
st.error("Please fill out all fields")
if user_data != {}:
return user_data
# This will run the Streamlit app when the script is executed
if __name__ == "__main__":
user_registration()