'List of chooses depending on user permissions

I'm building simple app on streamlit. I'm struggling with making list of chooses depending on user permissions.

utils.py Dict with pages:

pages = {
    "Start": start_page,
    "Test kabli": cable_test_page,
    "ARP": arp_page,
    "FGRestart": fg_restart_page,
    "MACTable": mac_table_page,
    "PingGateWAN": ping_gate_wan_page,
    "PInterface": psyhical_interface_page,
    "RoutingTable": routing_table_page,
    "TestŁączaWWAN(LTE)": wan_lte_test_page,
    "WanMAC": wan_mac_page,
    "TestŁączaWAN": wan_test_page,
    "ResetPortów": reset_poe_page,
    "RestartSwitcha": switch_restart_page,

}

Function for selecting items from a list

def select_page(ssh):

page = st.selectbox("Select item", tuple(pages.keys()))
pages[page](ssh)

Permissions to each item in a list are made like this:

    permissions = {
'cable_diag': ["user1","user2","user3"],
'ping':[ "user1","user2","user3"],
'arp': ["user1","user2","user3"],
'fgrestart':["user1","user2","user3"],
'mactable':["user1","user2","user3"],
'Pinterface':["user1","user2","user3"],
'poe':["user1","user2","user3"],
'routingtable':["user1","user3"],
'srestart':["user1","user2","user3"],
'lte':["user2","user3"],
'wanmac':["user1","user2","user3"],
'wan':["user2","user3"],}
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if st.session_state["username"] in permissions[module_name]:
                print('Accessed')
                return func(*args, **kwargs)
            else:
                st.text('ACCESS DENIED')
        return wrapper
    return decorator  

All file with page have assigned role like this: @has_role('page_name')

It's working but i want that if user1 don't have permissions to site 'wan' i also want that he will not be able to see this page in the list. I really don't have idea how to solve it

Full utils.py

import streamlit as st
import pandas as pd
import paramiko
from permissions import permissions
from modules.streamlit.pages.cable_test import cable_test_page
from modules.streamlit.pages.arp import arp_page
from modules.streamlit.pages.fg_restart import fg_restart_page
from modules.streamlit.pages.mac_table import mac_table_page
from modules.streamlit.pages.ping_gate_wan import ping_gate_wan_page
from modules.streamlit.pages.psyhical_interface import psyhical_interface_page
from modules.streamlit.pages.routing_table import routing_table_page
from modules.streamlit.pages.switch_restart import switch_restart_page
from modules.streamlit.pages.wan_lte_test import wan_lte_test_page
from modules.streamlit.pages.wan_mac import wan_mac_page
from modules.streamlit.pages.wan_test import wan_test_page
from modules.streamlit.pages.reset_poe import reset_poe_page
from modules.streamlit.pages.start import start_page
from modules.streamlit.pages.test import test_page

pages = {
    "Start": start_page,
    "Test kabli": cable_test_page,
    "ARP": arp_page,
    "FGRestart": fg_restart_page,
    "MACTable": mac_table_page,
    "PingGateWAN": ping_gate_wan_page,
    "PInterface": psyhical_interface_page,
    "RoutingTable": routing_table_page,
    "TestŁączaWWAN(LTE)": wan_lte_test_page,
    "WanMAC": wan_mac_page,
    "TestŁączaWAN": wan_test_page,
    "ResetPortów": reset_poe_page,
    "RestartSwitcha": switch_restart_page,

}
custom_options = {"sideBar": False, "enableCellTextSelection": True}
@st.cache
def load_markets_xls():
    df = pd.read_excel("path",
                       index_col=None, engine="openpyxl")

    return df


def choose_market(df):
    shop_number = st.text_input('Number', '')
    if shop_number:
        df = df[df["Host_Name"].notna()]
        df['Host_Name'] = df['Host_Name'].astype(int).astype(str)
        try:
            single_row = df.loc[df['Host_Name'] == shop_number].to_dict('records')[0]
            ip = single_row['ip']
            return ip
        except IndexError:
            st.text("No found ")



def connect_to_market(ssh,market_ip):
    print(market_ip)
    try:
        ssh.connect(hostname=str(market_ip), port=22, username='user',
        password='password', allow_agent=False, timeout=None, compress=False)
        st.text('Connected!')
        return True
    except Exception as e:
        st.text('----- ')
        return False

def select_page(ssh):
   page = st.selectbox("Choose", tuple(pages.keys()))
   pages[page](ssh)

Full permissions.py:

from functools import wraps
import streamlit as st
import pandas as pd
import paramiko

permissions = {
'cable_diag': ["user1","user2","user3"],
'ping':[ "user1","user2","user3"],
'arp': ["user1","user2","user3"],
'fgrestart':["user1","user2","user3"],
'mactable':["user1","user2","user3"],
'Pinterface':["user1","user2","user3"],
'poe':["user1","user2","user3"],
'routingtable':["user1","user3"],
'srestart':["user1","user2","user3"],
'lte':["user2","user3"],
'wanmac':["user1","user2","user3"],
'wan':["user2","user3"],}

def has_role(module_name):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if st.session_state["username"] in permissions[module_name]:
                print('jest dostep')
                return func(*args, **kwargs)
            else:
                st.text('ACCESS DENIED!')
        return wrapper
    return decorator```

app.py:

import streamlit as st
import pandas as pd
import paramiko
import streamlit_authenticator as stauth
from utils import load_markets_xls, choose_market, connect_to_market, select_page
from cred import hashed_passwords , names, usernames
from PIL import Image
import base64
ssh = paramiko.SSHClient()
# ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
hide_menu_style = """
    <style>
    #MainMenu {visibility: hidden;}
    </style>
    """
custom_options = {"sideBar": False, "enableCellTextSelection": True}
def main():
    st.set_page_config(page_title='Market Tests', layout="wide")
    st.markdown(hide_menu_style, unsafe_allow_html=True)

    authenticator = stauth.Authenticate(names,usernames,hashed_passwords, 'cookie','some_key', cookie_expiry_days=0)
    col1, col2, col3 = st.columns(3)
    with col1:
        st.write(' ')

    with col2:
        image = Image.open('path') 
        st.image(image)

    with col3:
        st.write(' ')

    name, authentication_status, username = authenticator.login('Panel Logowania','main')
    if authentication_status:
        authenticator.logout('Logout', 'main')
        data_load_state = st.text('Loading data...')
        df = load_markets_xls()
        data_load_state.text('Markets loaded!')

        market_ip = choose_market(df)

        if (market_ip):
            if connect_to_market(ssh, market_ip):
                select_page(ssh)
    elif authentication_status == False:
        st.error('Username/password is incorrect')
    elif authentication_status == None:
        st.warning('Please enter your username and password')





def refresh_data():
    st.legacy_caching.clear_cache()
    raise st.script_runner.RerunException(st.script_request_queue.RerunData(None))

if __name__ == "__main__":
    main()

sample page:

import streamlit as st
from permissions import has_role
custom_options = {
        "enableCellTextSelection": True,
        "sideBar":True
    }
@has_role('arp')
def arp_page(ssh):
    st.title('ARP')
    stdin, stdout, stderr = ssh.exec_command("get system arp")
    for line in iter(stdout.readline, ""):
        st.text(line)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source