build(app.py): add routing between admin and auth pages

This commit is contained in:
Krrish Dholakia 2023-12-23 16:22:28 +05:30
parent 8c6d11ea07
commit 1bfab87323
3 changed files with 66 additions and 52 deletions

View file

@ -7,34 +7,34 @@ import base64
# Replace your_base_url with the actual URL where the proxy auth app is hosted # Replace your_base_url with the actual URL where the proxy auth app is hosted
your_base_url = 'http://localhost:8501' # Example base URL your_base_url = 'http://localhost:8501' # Example base URL
# Create a configuration placeholder
st.session_state.setdefault('proxy_url', 'http://example.com')
st.session_state.setdefault('allowed_email_subdomain', 'example.com')
st.session_state.setdefault('user_auth_url', 'NOT_GIVEN')
# Function to encode the configuration # Function to encode the configuration
def encode_config(proxy_url, allowed_email_subdomain): def encode_config(proxy_url, allowed_email_subdomain):
combined_string = f"proxy_url={proxy_url}&accepted_email_subdomain={allowed_email_subdomain}" combined_string = f"proxy_url={proxy_url}&accepted_email_subdomain={allowed_email_subdomain}"
return base64.b64encode(combined_string.encode('utf-8')).decode('utf-8') return base64.b64encode(combined_string.encode('utf-8')).decode('utf-8')
# Simple function to update config values # Simple function to update config values
def update_config(): def update_config(proxy_url, allowed_email_subdomain):
st.session_state['proxy_url'] = proxy_url st.session_state['proxy_url'] = proxy_url
st.session_state['allowed_email_subdomain'] = allowed_email_subdomain st.session_state['allowed_email_subdomain'] = allowed_email_subdomain
st.session_state['user_auth_url'] = f"{your_base_url}/{encode_config(proxy_url=proxy_url, allowed_email_subdomain=allowed_email_subdomain)}" st.session_state['user_auth_url'] = f"{your_base_url}/?page={encode_config(proxy_url=proxy_url, allowed_email_subdomain=allowed_email_subdomain)}"
# Display the form for the admin to set the proxy URL and allowed email subdomain def admin_page():
st.header("Admin Configuration") # Display the form for the admin to set the proxy URL and allowed email subdomain
st.header("Admin Configuration")
# Create a configuration placeholder
st.session_state.setdefault('proxy_url', 'http://example.com')
st.session_state.setdefault('allowed_email_subdomain', 'example.com')
st.session_state.setdefault('user_auth_url', 'NOT_GIVEN')
with st.form("config_form", clear_on_submit=False): with st.form("config_form", clear_on_submit=False):
proxy_url = st.text_input("Set Proxy URL", st.session_state['proxy_url']) proxy_url = st.text_input("Set Proxy URL", st.session_state['proxy_url'])
allowed_email_subdomain = st.text_input("Set Allowed Email Subdomain", st.session_state['allowed_email_subdomain']) allowed_email_subdomain = st.text_input("Set Allowed Email Subdomain", st.session_state['allowed_email_subdomain'])
submitted = st.form_submit_button("Save") submitted = st.form_submit_button("Save")
if submitted: if submitted:
update_config() update_config(proxy_url=proxy_url, allowed_email_subdomain=allowed_email_subdomain)
# Display the current configuration # Display the current configuration
st.write(f"Current Proxy URL: {st.session_state['proxy_url']}") st.write(f"Current Proxy URL: {st.session_state['proxy_url']}")
st.write(f"Current Allowed Email Subdomain: {st.session_state['allowed_email_subdomain']}") st.write(f"Current Allowed Email Subdomain: {st.session_state['allowed_email_subdomain']}")
st.write(f"Current User Auth URL: {st.session_state['user_auth_url']}") st.write(f"Current User Auth URL: {st.session_state['user_auth_url']}")

View file

@ -1,35 +1,53 @@
"""
Routes between admin, auth, keys pages
"""
import streamlit as st import streamlit as st
import urllib.parse import base64, binascii
from admin import admin_page
from auth import auth_page
from urllib.parse import urlparse, parse_qs
def generate_key(name, description): # Parse the query params in the URL
# Code to generate and return a key goes here def get_query_params():
return "Generated Key" # Get the query params from Streamlit's `server.request` function
# This functionality is not officially documented and could change in the future versions of Streamlit
query_params = st.experimental_get_query_params()
return query_params
def is_base64(sb):
def main(api_base, url_hash): try:
st.title("Key Request") if isinstance(sb, str):
# Try to encode it to bytes if it's a unicode string
# Create input fields for key name and description sb_bytes = sb.encode('ascii')
name = st.text_input("Key Name") elif isinstance(sb, bytes):
description = st.text_area("Key Description") sb_bytes = sb
# Create a button to request the key
if st.button("Request Key"):
if name and description:
key = generate_key(name, description)
st.success(f"Your key: {key}")
else: else:
st.error("Please enter a valid key name and description.") # If it is not a byte or a string, it is not base64
return False
# Check if decoding is successful.
# The result of the decode is not required, so it is ignored.
_ = base64.urlsafe_b64decode(sb_bytes)
if __name__ == "__main__": # If the decode was successful, the input is likely base64
# Get the proxy URL and hash from the admin return True
proxy_url = st.text_input("Admin Proxy URL") except (binascii.Error, ValueError):
hash_input = st.text_input("URL Hash") # If an error occurs, return False, as the input is not base64
return False
# Generate the public URL with hash # Check the URL path and route to the correct page based on the path
encoded_hash = urllib.parse.quote(hash_input.strip()) if hash_input else "" query_params = get_query_params()
public_url = f"{proxy_url}/{encoded_hash}" page_param = query_params.get('page', [None])[0]
# Run the Streamlit app # Route to the appropriate page based on the URL query param
main(proxy_url, hash_input) if page_param:
try:
# Try to decode the page_param from base64
if is_base64(page_param):
auth_page()
else:
st.error("Unknown page")
except Exception as e:
st.error("Failed to decode the page parameter. Error: " + str(e))
else:
admin_page()

View file

@ -24,7 +24,7 @@ def sign_in_with_otp(email: str):
# Create the Streamlit app # Create the Streamlit app
def main(): def auth_page():
st.title("User Authentication") st.title("User Authentication")
# User email input # User email input
@ -33,7 +33,3 @@ def main():
# Sign in button # Sign in button
if st.button("Sign In"): if st.button("Sign In"):
sign_in_with_otp(email) sign_in_with_otp(email)
if __name__ == "__main__":
main()