-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
221 lines (183 loc) · 7.16 KB
/
app.py
File metadata and controls
221 lines (183 loc) · 7.16 KB
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import streamlit as st
import hashlib
import json
import os
import datetime
from dotenv import load_dotenv
from utils_auth import check_credentials, add_user, mark_link_as_used
from logger_config import get_logger
logger = get_logger("app")
load_dotenv()
AUTH_REQUIRED = bool(os.getenv('MURRAY_PASSWORD'))
st.set_page_config(
page_title="Geo Murray", page_icon="utils/Group 105.png", layout="wide"
)
# Add this function after check_credentials and before add_user
def get_user_role(username):
try:
with open("traffic_metrics/users.json", "r") as f:
users = json.load(f)
return users[username]["role"]
except Exception as e:
st.error(f"Error getting user role: {e}")
return "user"
def create_registration_link(role, max_uses=1):
try:
# Generate a unique token
token = hashlib.sha256(os.urandom(32)).hexdigest()[:16]
if os.path.exists("traffic_metrics/registration_links.json"):
with open("traffic_metrics/registration_links.json", "r") as f:
links = json.load(f)
else:
links = {}
links[token] = {
"role": role,
"max_uses": max_uses,
"used_count": 0,
"created_at": str(datetime.datetime.now()),
}
with open("traffic_metrics/registration_links.json", "w") as f:
json.dump(links, f, indent=4)
return token
except Exception as e:
return None, f"Error creating registration link: {str(e)}"
def validate_registration_link(token):
try:
if not os.path.exists("traffic_metrics/registration_links.json"):
return False, None
with open("traffic_metrics/registration_links.json", "r") as f:
links = json.load(f)
if token not in links:
return False, None
link_info = links[token]
if link_info["used_count"] >= link_info["max_uses"]:
return False, None
return True, link_info["role"]
except Exception as e:
return False, None
# Initialize session state for login
if 'authenticated' not in st.session_state:
st.session_state.authenticated = not AUTH_REQUIRED # Auto-authenticate if no auth required
if 'role' not in st.session_state:
st.session_state.role = "user"
if 'username' not in st.session_state:
st.session_state.username = "Guest" if not AUTH_REQUIRED else ""
# Login system - only show if authentication is required
if AUTH_REQUIRED and not st.session_state.authenticated:
st.title("Welcome to Geo Murray")
st.write("Login or register.")
query_params = st.query_params
url_token = query_params.get("token", [""])[0]
if "registration_token" not in st.session_state:
st.session_state.registration_token = url_token
tab1, tab2 = st.tabs(["Login", "Register"])
with tab1:
with st.form("login_form"):
username = st.text_input("Username")
password = st.text_input("Password", type="password")
login = st.form_submit_button("Login")
if login:
is_entropy_email = username.strip().endswith("@entropy.tech")
if is_entropy_email:
st.session_state.authenticated = True
st.session_state.username = username
st.session_state.role = "user"
st.rerun()
elif check_credentials(username, password):
st.session_state.authenticated = True
st.session_state.username = username
st.session_state.role = get_user_role(username)
st.rerun()
else:
st.error("Username or password incorrect")
with tab2:
with st.form("register_form"):
username = st.text_input("Username")
reg_input = st.text_input(
"Registration token or valid email", key="registration_token"
)
new_password = st.text_input("New password", type="password")
confirm_password = st.text_input("Confirm password", type="password")
register = st.form_submit_button("Register")
if register:
is_entropy_email = reg_input.strip().endswith("@entropy.tech")
if not is_entropy_email and not reg_input:
st.error(
"You must enter a valid Registration Token or a valid email in the second field."
)
elif new_password != confirm_password:
st.error("The passwords do not match")
elif len(new_password) < 6:
st.error("The password must be at least 6 characters long")
elif not username:
st.error("You must enter a username.")
else:
if is_entropy_email:
success, message = add_user(
username.strip(), new_password, role="user"
)
else:
success, message = add_user(
username.strip(),
new_password,
registration_token=reg_input.strip(),
)
if success and reg_input:
mark_link_as_used(reg_input.strip())
if success:
st.success(message)
else:
st.error(message)
if st.session_state.authenticated:
logger.info(f"{st.session_state.role} {st.session_state.username} logged in")
pages = []
if st.session_state.role == "admin":
pages = {
"Hello "
+ st.session_state.username: [
st.Page("experimental_design.py", title="Experimental design"),
st.Page("experimental_evaluation.py", title="Experimental evaluation"),
st.Page("dashboard.py", title="Dashboard"),
]
}
else:
pages = {
"Hello "
+ st.session_state.username: [
st.Page("experimental_design.py", title="Experimental design"),
st.Page("experimental_evaluation.py", title="Experimental evaluation"),
]
}
pg = st.navigation(pages)
pg.run()
st.markdown(
"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
html, body, [class*="st-"] {
font-family: 'Inter', sans-serif;
}
h1, h2, h3, h4, h5, h6, .stTextHeader {
font-family: 'Inter', sans-serif !important;
font-weight: 700 !important;
}
button, input, textarea, select {
font-family: 'Inter', sans-serif !important;
}
.stButton>button {
font-size: 16px;
font-weight: 600;
}
.stTextInput>div>div>input,
.stTextArea>div>textarea,
.stSelectbox>div>div>select,
.stMultiselect>div>div>div {
font-family: 'Inter', sans-serif !important;
}
.stSlider {
font-family: 'Inter', sans-serif;
}
</style>
""",
unsafe_allow_html=True,
)