I have an application that has 4 pages , home page , a submission page, a statistics page. I have have two group of users, formers and ogas. I want the ogas to have access to all the pages but i want the formers to only be able to view the submission page. I am using streamlit just for your information. how can this be done
Drop files here
or click to upload
import streamlit as st
from streamlit_extras.switch_page_button import switch_page
import pandas as pd
from pathlib import Path
import os
import sqlite3
from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.orm import Session, declarative_base
import hashlib
# Set page config
st.set_page_config(page_title="Role-Based Access Control Demo", layout="wide")
# Database setup
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String, unique=True, nullable=False)
password_hash = Column(String, nullable=False)
is_oga = Column(Boolean, default=False) # True for "oga", False for "former"
# Create database engine
engine = create_engine("sqlite:///users.db")
# Create tables
Base.metadata.create_all(bind=engine)
# Helper functions
def hash_password(password):
return hashlib.sha256(password.encode()).hexdigest()
def create_default_users():
with Session(engine) as session:
# Check if users already exist
if session.query(User).count() == 0:
# Create default users
users = [
User(username="former1", password_hash=hash_password("password"), is_oga=False),
User(username="former2", password_hash=hash_password("password"), is_oga=False),
User(username="oga1", password_hash=hash_password("password"), is_oga=True),
User(username="oga2", password_hash=hash_password("password"), is_oga=True)
]
for user in users:
session.add(user)
session.commit()
# Create default users when the app starts
create_default_users()
# Initialize session state variables
if "authenticated" not in st.session_state:
st.session_state.authenticated = False
if "username" not in st.session_state:
st.session_state.username = None
if "is_oga" not in st.session_state:
st.session_state.is_oga = False
if "current_page" not in st.session_state:
st.session_state.current_page = "home"
# Create pages directory if it doesn't exist
pages_dir = Path("pages")
if not pages_dir.exists():
pages_dir.mkdir()
# Function to authenticate user
def authenticate(username, password):
with Session(engine) as session:
user = session.query(User).filter_by(username=username).first()
if user and user.password_hash == hash_password(password):
st.session_state.authenticated = True
st.session_state.username = username
st.session_state.is_oga = user.is_oga
return True
return False
# Function to logout
def logout():
st.session_state.authenticated = False
st.session_state.username = None
st.session_state.is_oga = False
st.session_state.current_page = "home"
st.rerun()
# Login form
def show_login_form():
st.title("Login")
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
with st.form("login_form"):
username = st.text_input("Username")
password = st.text_input("Password", type="password")
submit = st.form_submit_button("Login")
if submit:
if authenticate(username, password):
st.success(f"Welcome, {username}!")
st.rerun()
else:
st.error("Invalid username or password")
# Display demo credentials
with st.expander("Demo Credentials"):
st.markdown("""
**Former Users (Limited Access):**
- Username: former1
- Password: password
**Oga Users (Full Access):**
- Username: oga1
- Password: password
""")
# Navbar for navigation
def show_navbar():
col1, col2, col3, col4, col5 = st.columns([1, 1, 1, 1, 1])
with col1:
if st.button("Home", use_container_width=True):
st.session_state.current_page = "home"
st.rerun()
with col2:
if st.button("Submission", use_container_width=True):
st.session_state.current_page = "submission"
st.rerun()
with col3:
if st.button("Statistics", use_container_width=True):
# Check if user has access to statistics page
if st.session_state.is_oga:
st.session_state.current_page = "statistics"
st.rerun()
else:
st.warning("You don't have access to this page")
with col4:
if st.button("Settings", use_container_width=True):
# Check if user has access to settings page
if st.session_state.is_oga:
st.session_state.current_page = "settings"
st.rerun()
else:
st.warning("You don't have access to this page")
with col5:
if st.button("Logout", use_container_width=True):
logout()
# Home page
def show_home_page():
st.title("Home Page")
st.write("Welcome to the home page of our application.")
st.info("This is the home page accessible to all authenticated users.")
st.markdown("""
### Role-Based Access Control
In this application, we have two types of users:
1. **Formers** - Limited access (only submission page)
2. **Ogas** - Full access to all pages
Navigate using the buttons above to explore the application.
""")
# Submission page
def show_submission_page():
st.title("Submission Page")
st.write("This is the submission page where users can submit their forms.")
st.info("This page is accessible to both 'Former' and 'Oga' users.")
with st.form("submission_form"):
st.text_input("Full Name")
st.text_area("Comments")
st.file_uploader("Upload Document", type=["pdf", "docx", "doc"])
st.date_input("Submission Date")
submitted = st.form_submit_button("Submit")
if submitted:
st.success("Form submitted successfully!")
# Statistics page
def show_statistics_page():
st.title("Statistics Page")
st.write("This page shows statistics and analytics.")
st.warning("This page is only accessible to 'Oga' users.")
# Sample data for demonstration
data = {
'Category': ['Form A', 'Form B', 'Form C', 'Form D'],
'Submissions': [42, 28, 63, 17],
'Approval Rate': [75, 82, 45, 93]
}
df = pd.DataFrame(data)
col1, col2 = st.columns(2)
with col1:
st.subheader("Submission Statistics")
st.bar_chart(df.set_index('Category')['Submissions'])
with col2:
st.subheader("Approval Rate (%)")
st.line_chart(df.set_index('Category')['Approval Rate'])
st.dataframe(df, use_container_width=True)
# Settings page
def show_settings_page():
st.title("Settings Page")
st.write("Manage application settings and user permissions.")
st.warning("This page is only accessible to 'Oga' users.")
with Session(engine) as session:
users = session.query(User).all()
user_data = {
'Username': [user.username for user in users],
'Role': ['Oga' if user.is_oga else 'Former' for user in users],
}
df = pd.DataFrame(user_data)
st.subheader("User List")
st.dataframe(df, use_container_width=True)
st.subheader("Add New User")
with st.form("add_user_form"):
new_username = st.text_input("Username")
new_password = st.text_input("Password", type="password")
is_oga = st.checkbox("Is Oga (Admin)")
submitted = st.form_submit_button("Add User")
if submitted:
if not new_username or not new_password:
st.error("Username and password are required.")
else:
# Check if username already exists
existing_user = session.query(User).filter_by(username=new_username).first()
if existing_user:
st.error(f"Username '{new_username}' already exists.")
else:
new_user = User(
username=new_username,
password_hash=hash_password(new_password),
is_oga=is_oga
)
session.add(new_user)
session.commit()
st.success(f"User '{new_username}' added successfully.")
st.rerun()
# Main app logic
def main():
# Show login form if not authenticated
if not st.session_state.authenticated:
show_login_form()
else:
# Show navbar and appropriate page
show_navbar()
# Display user info and role
role = "Oga (Admin)" if st.session_state.is_oga else "Former (Limited)"
st.sidebar.success(f"Logged in as: {st.session_state.username} ({role})")
# Automatic redirection for formers trying to access restricted pages
if not st.session_state.is_oga and st.session_state.current_page not in ["home", "submission"]:
st.session_state.current_page = "submission"
st.warning("You've been redirected to an accessible page.")
# Show the appropriate page based on navigation
if st.session_state.current_page == "home":
show_home_page()
elif st.session_state.current_page == "submission":
show_submission_page()
elif st.session_state.current_page == "statistics":
show_statistics_page()
elif st.session_state.current_page == "settings":
show_settings_page()
if __name__ == "__main__":
main()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?