Spaces:
Sleeping
Sleeping
import streamlit as st | |
import streamlit_authenticator as stauth | |
# Example credential dictionary for demonstration. | |
# In practice, store hashed passwords in a safe location (e.g., environment variables, secrets manager). | |
# You can generate hashed passwords using stauth.Hasher. | |
CREDENTIALS = { | |
"usernames": { | |
"alice": { | |
"name": "Alice Doe", | |
"password": "$2b$12$abc123exampleHashALICEXXXXXXXXXXXXXXX", | |
"role": "premium" | |
}, | |
"bob": { | |
"name": "Bob Smith", | |
"password": "$2b$12$abc123exampleHashBOBXXXXXXXXXXXXXXXXXX", | |
"role": "free" | |
} | |
} | |
} | |
def login(): | |
""" | |
Creates a login widget for the Streamlit app using streamlit_authenticator. | |
Returns: | |
(username, authentication_status, authenticator_obj) | |
- username: str or None | |
- authentication_status: bool (True if authenticated) | |
- authenticator_obj: an instance of the Authenticate class, so you can call logout, etc. | |
""" | |
authenticator = stauth.Authenticate( | |
credentials=CREDENTIALS, | |
cookie_name="smart_edit_cookie", | |
key="abcdef", | |
cookie_expiry_days=1 | |
) | |
# This call draws the login form in the Streamlit UI. | |
name, authentication_status, username = authenticator.login("Login", "main") | |
return username, authentication_status, authenticator | |
def show_logout_button(authenticator): | |
""" | |
Renders a logout button in the Streamlit UI for authenticated users. | |
""" | |
authenticator.logout("Logout", "main") | |
def is_premium_user(username): | |
""" | |
Checks if the logged-in user has the "premium" role. | |
Returns: | |
True if the user's role is premium, False otherwise. | |
""" | |
# Retrieve the stored role from the credentials dict | |
if username in CREDENTIALS["usernames"]: | |
return CREDENTIALS["usernames"][username].get("role") == "premium" | |
return False | |