-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstreamlit_verifier.py
More file actions
481 lines (434 loc) · 15.5 KB
/
streamlit_verifier.py
File metadata and controls
481 lines (434 loc) · 15.5 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
"""
Streamlit OTP Verifier Application
Simple interface for verifying OTPs through the REST API
"""
import streamlit as st
import requests
import time
import config
import pandas as pd
# Page configuration
st.set_page_config(
page_title="OTP Verifier",
page_icon="✅",
layout="centered",
initial_sidebar_state="collapsed"
)
# Custom CSS for centered card layout
st.markdown("""
<style>
.main {
padding-top: 2rem;
}
.stButton>button {
width: 100%;
background-color: #1f77b4;
color: white;
font-size: 18px;
font-weight: bold;
padding: 0.75rem;
border-radius: 8px;
border: none;
cursor: pointer;
transition: background-color 0.3s;
}
.stButton>button:hover {
background-color: #1557a0;
}
.verification-card {
background-color: #ffffff;
padding: 2rem;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin: 2rem auto;
max-width: 500px;
}
.result-success {
background-color: #d4edda;
color: #155724;
padding: 1rem;
border-radius: 8px;
border: 1px solid #c3e6cb;
text-align: center;
font-size: 18px;
font-weight: bold;
margin-top: 1rem;
}
.result-error {
background-color: #f8d7da;
color: #721c24;
padding: 1rem;
border-radius: 8px;
border: 1px solid #f5c6cb;
text-align: center;
font-size: 18px;
font-weight: bold;
margin-top: 1rem;
}
.result-info {
background-color: #d1ecf1;
color: #0c5460;
padding: 1rem;
border-radius: 8px;
border: 1px solid #bee5eb;
text-align: center;
font-size: 16px;
margin-top: 1rem;
}
.header-title {
text-align: center;
color: #1f77b4;
font-size: 36px;
font-weight: bold;
margin-bottom: 0.5rem;
}
.header-subtitle {
text-align: center;
color: #666;
font-size: 16px;
margin-bottom: 2rem;
}
.stTextInput>div>div>input {
font-size: 24px;
text-align: center;
letter-spacing: 8px;
font-family: monospace;
font-weight: bold;
}
.server-status {
text-align: center;
padding: 0.5rem;
border-radius: 20px;
font-size: 14px;
margin-bottom: 1rem;
}
.status-online {
background-color: #d4edda;
color: #155724;
}
.status-offline {
background-color: #f8d7da;
color: #721c24;
}
.instructions {
background-color: #f8f9fa;
padding: 1rem;
border-radius: 8px;
margin-bottom: 1.5rem;
font-size: 14px;
color: #495057;
}
.visual-metric {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 15px;
border-radius: 10px;
color: white;
text-align: center;
margin: 10px 0;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.visual-metric .value {
font-size: 32px;
font-weight: bold;
margin: 10px 0;
}
.visual-metric .label {
font-size: 14px;
opacity: 0.9;
}
</style>
""", unsafe_allow_html=True)
def verify_otp_with_api(otp: str) -> tuple:
"""
Send OTP to FastAPI backend for verification
Returns: (success: bool, message: str)
"""
try:
response = requests.post(
f"{config.api_url}/otp/verify",
json={"otp": otp},
headers={
"X-API-KEY": config.api_key,
"Content-Type": "application/json"
},
timeout=5
)
if response.status_code == 200:
data = response.json()
return data["valid"], data["message"]
elif response.status_code == 401:
return False, "Authentication failed - Invalid API key"
else:
return False, f"Server error: {response.status_code}"
except requests.exceptions.ConnectionError:
return False, "Cannot connect to server. Please ensure the server is running."
except requests.exceptions.Timeout:
return False, "Request timed out. Server might be slow or unresponsive."
except requests.exceptions.RequestException as e:
return False, f"Request failed: {str(e)}"
except Exception as e:
return False, f"Unexpected error: {str(e)}"
def check_server_status() -> bool:
"""Check if the FastAPI server is running"""
try:
response = requests.get(f"{config.api_url}/health", timeout=2)
return response.status_code == 200
except:
return False
def get_current_otp_info() -> dict:
"""Get current OTP information from server (for display)"""
try:
response = requests.get(f"{config.api_url}/otp/current", timeout=2)
if response.status_code == 200:
return response.json()
except:
pass
return None
def main():
"""Main application logic"""
# Header
st.markdown('<h1 class="header-title">✅ OTP Verifier</h1>', unsafe_allow_html=True)
st.markdown('<p class="header-subtitle">Enter your One-Time Password to verify</p>', unsafe_allow_html=True)
# Server status indicator
server_online = check_server_status()
if server_online:
st.markdown(
'<div class="server-status status-online">🟢 Server Online</div>',
unsafe_allow_html=True
)
else:
st.markdown(
'<div class="server-status status-offline">🔴 Server Offline</div>',
unsafe_allow_html=True
)
# Main verification card
st.markdown('<div class="verification-card">', unsafe_allow_html=True)
# Instructions
st.markdown(
"""
<div class="instructions">
📝 <strong>Instructions:</strong><br>
• Enter the 6-digit OTP from the Generator app<br>
• OTPs expire every 30 seconds<br>
• Make sure the server is running
</div>
""",
unsafe_allow_html=True
)
# Create form for better UX
with st.form("otp_verification_form"):
# OTP input field
otp_input = st.text_input(
"Enter 6-digit OTP",
max_chars=6,
placeholder="000000",
help="Enter the 6-digit code from the OTP Generator",
label_visibility="visible"
)
# Center the submit button
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
submit_button = st.form_submit_button(
"🔐 Verify OTP",
use_container_width=True
)
# Handle verification
if submit_button:
if not otp_input:
st.markdown(
'<div class="result-info">ℹ️ Please enter an OTP</div>',
unsafe_allow_html=True
)
elif len(otp_input) != 6 or not otp_input.isdigit():
st.markdown(
'<div class="result-error">❌ Invalid format. Please enter exactly 6 digits</div>',
unsafe_allow_html=True
)
elif not server_online:
st.markdown(
'<div class="result-error">❌ Cannot verify - Server is offline</div>',
unsafe_allow_html=True
)
else:
# Show spinner during verification
with st.spinner('Verifying OTP...'):
time.sleep(0.5) # Small delay for better UX
is_valid, message = verify_otp_with_api(otp_input)
# Display result
if is_valid:
st.balloons() # Celebration effect
st.markdown(
f'<div class="result-success">✅ {message}</div>',
unsafe_allow_html=True
)
st.success("Authentication successful!")
else:
st.markdown(
f'<div class="result-error">❌ {message}</div>',
unsafe_allow_html=True
)
st.markdown('</div>', unsafe_allow_html=True)
# Mathematical Transparency Section
st.markdown("---")
st.markdown('<h2 style="text-align: center; color: #1f77b4;">🧮 Mathematical Transparency</h2>', unsafe_allow_html=True)
with st.expander("📐 Recurrence Formula & Live Variables", expanded=True):
# Display the recurrence formula
st.markdown('<div style="background-color: #f0f2f6; padding: 20px; border-radius: 10px; border-left: 4px solid #1f77b4;">', unsafe_allow_html=True)
st.latex(r"X_{n+1} = (a \cdot X_n^2 + b \cdot t + c) \bmod m")
st.markdown('</div>', unsafe_allow_html=True)
# Display constants
st.markdown("### 📜 Mathematical Constants")
const_cols = st.columns(3)
with const_cols[0]:
st.metric("Multiplier (a)", config.a)
st.metric("Time Multiplier (b)", config.b)
with const_cols[1]:
st.metric("Constant (c)", config.c)
st.metric("Modulus (m)", f"{config.m:,}")
with const_cols[2]:
st.metric("Initial Seed", f"{config.seed:,}")
st.metric("OTP Modulus", f"{config.otp_modulus:,}")
# Live time values
st.markdown("### ⏱️ Live Time Values")
current_time = int(time.time())
time_slice = current_time // config.time_slice_duration
time_in_slice = current_time % config.time_slice_duration
time_remaining = config.time_slice_duration - time_in_slice
time_cols = st.columns(4)
with time_cols[0]:
st.markdown(f'''
<div class="visual-metric">
<div class="label">⏰ Current Time (t)</div>
<div class="value">{current_time}</div>
</div>
''', unsafe_allow_html=True)
with time_cols[1]:
st.markdown(f'''
<div class="visual-metric">
<div class="label">🔢 Time Slice (n)</div>
<div class="value">{time_slice}</div>
</div>
''', unsafe_allow_html=True)
with time_cols[2]:
st.markdown(f'''
<div class="visual-metric">
<div class="label">⏱️ Elapsed</div>
<div class="value">{time_in_slice}s</div>
</div>
''', unsafe_allow_html=True)
with time_cols[3]:
# Color code based on time remaining
color = "#667eea"
if time_remaining <= 10:
color = "#ff4444"
elif time_remaining <= 20:
color = "#ff9900"
st.markdown(f'''
<div class="visual-metric" style="background: linear-gradient(135deg, {color} 0%, {color} 100%);">
<div class="label">⌛ Remaining</div>
<div class="value">{time_remaining}s</div>
</div>
''', unsafe_allow_html=True)
# Progress bar for current time slice
progress = time_in_slice / config.time_slice_duration
st.progress(progress)
# Visual chart for time distribution
st.markdown("#### 📉 Time Distribution")
import pandas as pd
chart_data = pd.DataFrame({
'Status': ['Elapsed', 'Remaining'],
'Seconds': [time_in_slice, time_remaining]
})
st.bar_chart(chart_data.set_index('Status'))
# Sample calculation demonstration
st.markdown("### 📋 Sample Calculation for Current Time Slice")
st.info("💡 This shows how OTP is calculated for the current time slice")
# --- SOLUTION ---
# The sample seed MUST also be time-dependent
sample_seed = config.seed + time_slice
# --- END SOLUTION ---
x_squared = sample_seed ** 2
term1 = config.a * x_squared
term2 = config.b * time_slice
term3 = config.c
sum_before_mod = term1 + term2 + term3
x_next = sum_before_mod % config.m
otp_value = x_next % config.otp_modulus
calc_text = f"""
Step 1: Calculate time-dependent seed
Seed = {config.seed:,} (initial) + {time_slice} (time) = {sample_seed:,}
Step 2: Square the time-dependent seed
X_n² = {sample_seed:,}² = {x_squared:,}
Step 3: Calculate terms
a × X_n² = {config.a} × {x_squared:,} = {term1:,}
b × t = {config.b} × {time_slice} = {term2:,}
c = {config.c}
Step 4: Sum all terms
Sum = {term1:,} + {term2:,} + {term3} = {sum_before_mod:,}
Step 5: Apply modulus m
X_(n+1) = {sum_before_mod:,} mod {config.m:,} = {x_next:,}
Step 6: Generate 6-digit OTP
OTP = {x_next:,} mod {config.otp_modulus:,} = {otp_value:06d}
"""
st.code(calc_text)
st.success(f"🎯 Theoretical OTP for time slice {time_slice}: **{otp_value:06d}**")
# Add more visualization graphs
st.markdown("### 📊 OTP Sequence Visualization")
# Generate OTP history
history_data = []
for i in range(max(0, time_slice - 10), time_slice + 1):
temp_x_squared = config.seed ** 2
temp_x_next = (config.a * temp_x_squared + config.b * i + config.c) % config.m
temp_otp = temp_x_next % config.otp_modulus
history_data.append({'Slice': i, 'OTP': temp_otp})
df_otp_history = pd.DataFrame(history_data)
st.line_chart(df_otp_history.set_index('Slice'))
st.caption("📈 OTP values over recent time slices")
# Calculation components breakdown
st.markdown("#### 🔢 Calculation Components")
components_df = pd.DataFrame({
'Component': ['a × seed²', 'b × time', 'c'],
'Value': [term1, term2, term3]
})
st.bar_chart(components_df.set_index('Component'))
# Additional information section
with st.expander("ℹ️ System Information", expanded=False):
col1, col2 = st.columns(2)
with col1:
st.markdown("### 🔧 Configuration")
st.code(f"API URL: {config.api_url}")
st.code(f"Time Slice: {config.time_slice_duration}s")
st.code(f"OTP Length: {config.otp_digits} digits")
with col2:
st.markdown("### 📊 Current Status")
st.code(f"Time Slice: {time_slice}")
st.code(f"Time Remaining: {time_remaining}s")
# Try to get current OTP info (for debugging)
if server_online:
otp_info = get_current_otp_info()
if otp_info and otp_info.get("otp"):
if otp_info.get("expired"):
st.warning("Current OTP has expired")
else:
st.info("OTP is active")
# Footer
st.markdown("---")
st.markdown(
"""
<div style='text-align: center; color: #888; font-size: 14px;'>
🔒 Secure OTP Verification Portal<br>
Part of the Recurrence-Based Time OTP Authentication System
</div>
""",
unsafe_allow_html=True
)
# Optional: Enable auto-refresh with toggle
with st.sidebar:
st.markdown("## ⚙️ Display Settings")
auto_refresh = st.checkbox("Enable Auto-Refresh", value=False, help="Refresh page every 5 seconds to update time values")
if auto_refresh:
st.info("🔄 Auto-refresh enabled")
time.sleep(5)
st.rerun()
if __name__ == "__main__":
main()