How to hide all pages before login

Hello evryone!

I know that streamlit’s multipage app works in a way such that each file in the pages folder will be a page, and thus be rendered in the application’s sidebar.

I am trying to make a streamlit application such that when the application is visited, only one page is shown in the sidebar, namely the “Sign In” page. When successful sign-in, the application should show the other pages in the sidebar and hide the Sign In page.

To do this, I would need to hide/show pages in the sidebar based on certain conditions (in my case, based on whether the user has successfully signed in then will be show all pages ). However, it looks like whatever is in the pages folder WILL be rendered as a page on the sidebar by default, and there’s no way to customise which pages get rendered when.

Here is the Code of Log In Page

# Setup
import streamlit as st
import pandas as pd
import hashlib

# Convert Pass into hash format
def make_hashes(password):
	return hashlib.sha256(str.encode(password)).hexdigest()

# Check password matches during login
def check_hashes(password,hashed_text):
	if make_hashes(password) == hashed_text:
		return hashed_text
	return False

# DB Management
import sqlite3 
conn = sqlite3.connect('user_data.db')
c = conn.cursor()
# DB Functions for create table
def create_usertable():
	c.execute('CREATE TABLE IF NOT EXISTS userstable(username TEXT,email TEX, password TEXT)')

# Insert the data into table
def add_userdata(username,email,password):
	c.execute('INSERT INTO userstable(username,email,password) VALUES (?,?,?)',(username,email,password))
	conn.commit()

# Password and email fetch
def login_user(email,password):
	c.execute('SELECT * FROM userstable WHERE email =? AND password = ?',(email,password))
	data = c.fetchall()
	return data


def view_all_users():
	c.execute('SELECT * FROM userstable')
	data = c.fetchall()
	return data


# Mian function
def main():
	#"""Login page"""
	st.title("welcome! ")
	menu = ["Login","SignUp"]
	choice = st.selectbox("Select Login or SignUp from dropdown box â–Ÿ",menu,)
	st.markdown(
     "<h10 style='text-align: left; color: #ffffff;'> If you do not have an account, create an accouunt by select SignUp option from above dropdown box.</h10>",
     unsafe_allow_html=True
     )
	if choice == "":
		st.subheader("Login")
	elif choice == 'Login':
		st.write('-------')
		st.subheader('Log in to the App')

		email = st.text_input("User Name",placeholder='email')
		
		password = st.text_input("Password",type='password')
  
		if st.checkbox("Login"):
			# if password == '12345':
			# Hash password creation and store in a table
			create_usertable()
			hashed_pswd = make_hashes(password)

			result = login_user(email,check_hashes(password,hashed_pswd))
			if result:

				st.success("Logged In as {}".format(email))

				
				if st.success:
					st.subheader("User Profiles")
					user_result = view_all_users()
					clean_db = pd.DataFrame(user_result,columns=["Username","Email","Password"])
					st.dataframe(clean_db)
			else:
				st.warning("Incorrect Username/Password")
	elif choice == "SignUp":
		st.write('-----')
		st.subheader("Create New Account")
		new_user = st.text_input("Username",placeholder='name')
		new_user_email = st.text_input('Email id',placeholder='email')
		new_password = st.text_input("Password",type='password')

		if st.button("Signup"):
			if new_user == '':     # if user name empty then show the warnings
				st.warning('Inavlid user name')
			elif new_user_email == '':   # if email empty then show the warnings
				st.warning('Invalid email id')
			elif new_password == '':   # if password empty then show the warnings
				st.warning('Invalid password')
			else:
				create_usertable()
				add_userdata(new_user,new_user_email,make_hashes(new_password))
				st.success("You have successfully created a valid Account")
				st.info("Go up and Login to you account")



if __name__ == '__main__':
	main()



Expected behavior:

Is there a way to achieve conditional rendering of pages on the sidebar, using Streamlit’s?

That is something we have considered adding for the next version of multipage apps, but is not possible except through some hacky tricks like this.

Warning: this method relies on internal APIs and will likely break in the future, but seems to work on streamlit 1.13.0

import json
from pathlib import Path

import streamlit as st
from streamlit.source_util import _on_pages_changed, get_pages

DEFAULT_PAGE = "streamlit_app.py"


def get_all_pages():
    default_pages = get_pages(DEFAULT_PAGE)

    pages_path = Path("pages.json")

    if pages_path.exists():
        saved_default_pages = json.loads(pages_path.read_text())
    else:
        saved_default_pages = default_pages.copy()
        pages_path.write_text(json.dumps(default_pages, indent=4))

    return saved_default_pages


def clear_all_but_first_page():
    current_pages = get_pages(DEFAULT_PAGE)

    if len(current_pages.keys()) == 1:
        return

    get_all_pages()

    # Remove all but the first page
    key, val = list(current_pages.items())[0]
    current_pages.clear()
    current_pages[key] = val

    _on_pages_changed.send()


def show_all_pages():
    current_pages = get_pages(DEFAULT_PAGE)

    saved_pages = get_all_pages()

    missing_keys = set(saved_pages.keys()) - set(current_pages.keys())

    # Replace all the missing pages
    for key in missing_keys:
        current_pages[key] = saved_pages[key]

    _on_pages_changed.send()


clear_all_but_first_page()

st.write("Hello world")

with st.form("Login"):
    username = st.text_input("Username", "streamlit", key="username")
    password = st.text_input("Password", "streamlit", type="password", key="password")
    st.form_submit_button()

if username == "streamlit" and password == "streamlit":
    show_all_pages()
else:
    st.write("Incorrect username or password")
    clear_all_but_first_page()
3 Likes

I used this code in my application but did not work properly few problems occurred.
Problem1 : when i login successfully every pages is displayed in navigation bar include the login page and in order to change page i have to again click on home page, but i want when login successfully it should redirect to Home page directly of my application and login page should closed and one more logout button appear on the bottom of sidebar so by clicking on logout button again i can go back to login page , means when login page open all pages should hide or vice versa.

Problem2 : After login to successfully one more extra login page created but i don’t have 2 login page i want a logout button in the button of sidebar so from there i can again go to the login page.

Problem3 : After running the code all page’s sequence changed i have no idea why page order is changed, i saved all pages like 1_login.py, 2_Home.py, 3_Others.py, 4_About.py , for better understanding i attached an image below check it out!

Solution : For solve first problem i tried to create a function which will only show all pages except login page then after successfully login we can call that function but i did not able to create a function like this.
and for the second and third problems i have no idea what is happening.

Code of Login Page

import json
from pathlib import Path
import hashlib
from numpy import place
import streamlit as st
from streamlit.source_util import _on_pages_changed, get_pages

DEFAULT_PAGE = "1_login_page.py"

    
def clear_all_but_first_page():
    current_pages = get_pages(DEFAULT_PAGE)

    if len(current_pages.keys()) == 1:
        return
    get_all_pages()

    # # Remove all but the first page
    key, val = list(current_pages.items())[0]
    st.write(current_pages[key])
    current_pages.clear()
    current_pages[key] = val

    _on_pages_changed.send()

def get_all_pages():
    default_pages = get_pages(DEFAULT_PAGE)

    pages_path = Path("pages.json")

    if pages_path.exists():
        saved_default_pages = json.loads(pages_path.read_text())
    else:
        saved_default_pages = default_pages.copy()
        pages_path.write_text(json.dumps(default_pages, indent=4))

    return saved_default_pages


def show_all_pages():
    current_pages = get_pages(DEFAULT_PAGE)

    saved_pages = get_all_pages()

    missing_keys = set(saved_pages.keys()) - set(current_pages.keys())

    # Replace all the missing pages
    for key in missing_keys:
        current_pages[key] = saved_pages[key]

    _on_pages_changed.send()


clear_all_but_first_page()





# Convert Pass into hash format
def make_hashes(password):
	return hashlib.sha256(str.encode(password)).hexdigest()

# Check password matches during login
def check_hashes(password,hashed_text):
	if make_hashes(password) == hashed_text:
		return hashed_text
	return False

# DB Management
import sqlite3 
conn = sqlite3.connect('user_data.db')
c = conn.cursor()
# DB Functions for create table
def create_usertable():
	c.execute('CREATE TABLE IF NOT EXISTS userstable(username TEXT,email TEXT, password TEXT)')

# Insert the data into table
def add_userdata(username,email,password):
	c.execute('INSERT INTO userstable(username,email,password) VALUES (?,?,?)',(username,email,password))
	conn.commit()

# Password and email fetch
def login_user(email,password):
	c.execute('SELECT * FROM userstable WHERE email =? AND password = ?',(email,password))
	data = c.fetchall()
	return data


def view_all_users():
	c.execute('SELECT * FROM userstable')
	data = c.fetchall()
	return data



               
# Mian function              
def main():
    st.title('welcome!')
    menu = ['Login','SignUp']
    choice = st.selectbox('Select Login or ignUp from dropdown box',menu)
    
    # default choice login option
    if choice == '':
        st.subheader('Login')
        
    # For login choice    
    elif choice == 'Login':
        st.write('------')
        st.subheader('Login')
        with st.form('Login'):
            email = st.text_input('User name',placeholder='email')
            password = st.text_input('Password',type='password')
            login_button = st.form_submit_button('Login')
            if login_button:
                create_usertable()
                hashed_pswd = make_hashes(password)
                result = login_user(email,check_hashes(password,hashed_pswd))

                if result:
                    st.success('Logged in successfully with {}'.format(email))
                    if st.success:
                        show_all_pages()
                    
                else:
                    st.warning('Incorrect Username/ Password')
    
    # For signup choice
                    
    elif choice == 'SignUp':
        st.write('-------')
        st.subheader('Create New Account')
        with st.form('Create New Account'):
            new_user = st.text_input('Username', placeholder='name')
            new_user_email = st.text_input('Email id',placeholder='email')
            new_password = st.text_input('Password',type='password')
            signup_button =st.form_submit_button('SignUp')
            if signup_button:
                if new_user == '':
                    st.warning('Invalid username')
                elif new_user_email == '':
                    st.warning('Invalid email id')
                elif new_password == '':
                    st.warning('Invalid password')
                else:
                    create_usertable()
                    add_userdata(new_user,new_user_email,make_hashes(new_password))
                    st.success('You have successfully created a valid account!')
                    st.info('Go up and Login to your account!')


if __name__ == '__main__':
    main()

Here’s a more specific version of my code that should work for your use-case.

I kept the functions the same for showing and hiding the pages, but I use a session state key called “logged_in” to keep track of whether it shows or hides all the pages.

Let me know if this works for you.

import json
from pathlib import Path

import streamlit as st
from streamlit.source_util import _on_pages_changed, get_pages

DEFAULT_PAGE = "1_login.py"


def get_all_pages():
    default_pages = get_pages(DEFAULT_PAGE)

    pages_path = Path("pages.json")

    if pages_path.exists():
        saved_default_pages = json.loads(pages_path.read_text())
    else:
        saved_default_pages = default_pages.copy()
        pages_path.write_text(json.dumps(default_pages, indent=4))

    return saved_default_pages


def clear_all_but_first_page():
    current_pages = get_pages(DEFAULT_PAGE)

    if len(current_pages.keys()) == 1:
        return

    get_all_pages()

    # Remove all but the first page
    key, val = list(current_pages.items())[0]
    current_pages.clear()
    current_pages[key] = val

    _on_pages_changed.send()


def show_all_pages():
    current_pages = get_pages(DEFAULT_PAGE)

    saved_pages = get_all_pages()

    missing_keys = set(saved_pages.keys()) - set(current_pages.keys())

    # Replace all the missing pages
    for key in missing_keys:
        current_pages[key] = saved_pages[key]

    _on_pages_changed.send()


clear_all_but_first_page()

import hashlib

import pandas as pd

# Setup
import streamlit as st


# Convert Pass into hash format
def make_hashes(password):
    return hashlib.sha256(str.encode(password)).hexdigest()


# Check password matches during login
def check_hashes(password, hashed_text):
    if make_hashes(password) == hashed_text:
        return hashed_text
    return False


# DB Management
import sqlite3

conn = sqlite3.connect("user_data.db")
c = conn.cursor()
# DB Functions for create table
def create_usertable():
    c.execute(
        "CREATE TABLE IF NOT EXISTS userstable(username TEXT,email TEX, password TEXT)"
    )


# Insert the data into table
def add_userdata(username, email, password):
    c.execute(
        "INSERT INTO userstable(username,email,password) VALUES (?,?,?)",
        (username, email, password),
    )
    conn.commit()


# Password and email fetch
def login_user(email, password):
    c.execute(
        "SELECT * FROM userstable WHERE email =? AND password = ?", (email, password)
    )
    data = c.fetchall()
    return data


def view_all_users():
    c.execute("SELECT * FROM userstable")
    data = c.fetchall()
    return data


if "logged_in" not in st.session_state:
    st.session_state["logged_in"] = False

# Mian function
def main():
    # """Login page"""
    st.title("welcome! ")
    menu = ["Login", "SignUp"]
    choice = st.selectbox(
        "Select Login or SignUp from dropdown box â–Ÿ",
        menu,
    )
    st.markdown(
        "<h10 style='text-align: left; color: #ffffff;'> If you do not have an account, create an accouunt by select SignUp option from above dropdown box.</h10>",
        unsafe_allow_html=True,
    )
    if choice == "":
        st.subheader("Login")
    elif choice == "Login":
        st.write("-------")
        st.subheader("Log in to the App")

        email = st.text_input("User Name", placeholder="email")

        password = st.text_input("Password", type="password")

        if st.checkbox("Login"):
            # if password == '12345':
            # Hash password creation and store in a table
            create_usertable()
            hashed_pswd = make_hashes(password)

            result = login_user(email, check_hashes(password, hashed_pswd))
            if result:
                st.session_state["logged_in"] = True

                st.success("Logged In as {}".format(email))

                if st.success:
                    st.subheader("User Profiles")
                    user_result = view_all_users()
                    clean_db = pd.DataFrame(
                        user_result, columns=["Username", "Email", "Password"]
                    )
                    st.dataframe(clean_db)
            else:
                st.warning("Incorrect Username/Password")
    elif choice == "SignUp":
        st.write("-----")
        st.subheader("Create New Account")
        new_user = st.text_input("Username", placeholder="name")
        new_user_email = st.text_input("Email id", placeholder="email")
        new_password = st.text_input("Password", type="password")

        if st.button("Signup"):
            if new_user == "":  # if user name empty then show the warnings
                st.warning("Inavlid user name")
            elif new_user_email == "":  # if email empty then show the warnings
                st.warning("Invalid email id")
            elif new_password == "":  # if password empty then show the warnings
                st.warning("Invalid password")
            else:
                create_usertable()
                add_userdata(new_user, new_user_email, make_hashes(new_password))
                st.success("You have successfully created a valid Account")
                st.info("Go up and Login to you account")

    if st.session_state["logged_in"]:
        show_all_pages()
    else:
        clear_all_but_first_page()


if __name__ == "__main__":
    main()
2 Likes

I’m sorry to say but It did not work for me the problem is after successfully logged in it shows all pages but i want all pages except default log in page , and second problem is it changed the order of pages as i mention earlier.

I believe this will solve both of those issues:

import hashlib
import json
import sqlite3
from pathlib import Path

import pandas as pd

# Setup
import streamlit as st
from streamlit.source_util import _on_pages_changed, get_pages
from streamlit_extras.switch_page_button import switch_page

DEFAULT_PAGE = "1_login.py"
SECOND_PAGE_NAME = "Home"


def get_all_pages():
    default_pages = get_pages(DEFAULT_PAGE)

    pages_path = Path("pages.json")

    if pages_path.exists():
        saved_default_pages = json.loads(pages_path.read_text())
    else:
        saved_default_pages = default_pages.copy()
        pages_path.write_text(json.dumps(default_pages, indent=4))

    return saved_default_pages


def clear_all_but_first_page():
    current_pages = get_pages(DEFAULT_PAGE)

    if len(current_pages.keys()) == 1:
        return

    get_all_pages()

    # Remove all but the first page
    key, val = list(current_pages.items())[0]
    current_pages.clear()
    current_pages[key] = val

    _on_pages_changed.send()


def show_all_pages():
    current_pages = get_pages(DEFAULT_PAGE)

    saved_pages = get_all_pages()

    # Replace all the missing pages
    for key in saved_pages:
        if key not in current_pages:
            current_pages[key] = saved_pages[key]

    _on_pages_changed.send()


def hide_page(name: str):
    current_pages = get_pages(DEFAULT_PAGE)

    for key, val in current_pages.items():
        if val["page_name"] == name:
            del current_pages[key]
            _on_pages_changed.send()
            break


clear_all_but_first_page()


# Convert Pass into hash format
def make_hashes(password):
    return hashlib.sha256(str.encode(password)).hexdigest()


# Check password matches during login
def check_hashes(password, hashed_text):
    if make_hashes(password) == hashed_text:
        return hashed_text
    return False


# DB Management

conn = sqlite3.connect("user_data.db")
c = conn.cursor()


# DB Functions for create table
def create_usertable():
    c.execute(
        "CREATE TABLE IF NOT EXISTS userstable(username TEXT,email TEX, password TEXT)"
    )


# Insert the data into table
def add_userdata(username, email, password):
    c.execute(
        "INSERT INTO userstable(username,email,password) VALUES (?,?,?)",
        (username, email, password),
    )
    conn.commit()


# Password and email fetch
def login_user(email, password):
    c.execute(
        "SELECT * FROM userstable WHERE email =? AND password = ?", (email, password)
    )
    data = c.fetchall()
    return data


def view_all_users():
    c.execute("SELECT * FROM userstable")
    data = c.fetchall()
    return data


if "logged_in" not in st.session_state:
    st.session_state["logged_in"] = False


# Main function
def main():
    # """Login page"""
    st.title("welcome! ")
    menu = ["Login", "SignUp"]
    choice = st.selectbox(
        "Select Login or SignUp from dropdown box â–Ÿ",
        menu,
    )
    st.markdown(
        "<h10 style='text-align: left; color: #ffffff;'> If you do not have an account, create an accouunt by select SignUp option from above dropdown box.</h10>",
        unsafe_allow_html=True,
    )
    if choice == "":
        st.subheader("Login")
    elif choice == "Login":
        st.write("-------")
        st.subheader("Log in to the App")

        email = st.text_input("User Name", placeholder="email")

        password = st.text_input("Password", type="password")

        if st.checkbox("Login"):
            # if password == '12345':
            # Hash password creation and store in a table
            create_usertable()
            hashed_pswd = make_hashes(password)

            result = login_user(email, check_hashes(password, hashed_pswd))
            if result:
                st.session_state["logged_in"] = True

                st.success("Logged In as {}".format(email))

                if st.success:
                    st.subheader("User Profiles")
                    user_result = view_all_users()
                    clean_db = pd.DataFrame(
                        user_result, columns=["Username", "Email", "Password"]
                    )
                    st.dataframe(clean_db)
            else:
                st.warning("Incorrect Username/Password")
    elif choice == "SignUp":
        st.write("-----")
        st.subheader("Create New Account")
        new_user = st.text_input("Username", placeholder="name")
        new_user_email = st.text_input("Email id", placeholder="email")
        new_password = st.text_input("Password", type="password")

        if st.button("Signup"):
            if new_user == "":  # if user name empty then show the warnings
                st.warning("Inavlid user name")
            elif new_user_email == "":  # if email empty then show the warnings
                st.warning("Invalid email id")
            elif new_password == "":  # if password empty then show the warnings
                st.warning("Invalid password")
            else:
                create_usertable()
                add_userdata(new_user, new_user_email, make_hashes(new_password))
                st.success("You have successfully created a valid Account")
                st.info("Go up and Login to you account")

    if st.session_state["logged_in"]:
        show_all_pages()
        hide_page(DEFAULT_PAGE.replace(".py", ""))
        switch_page(SECOND_PAGE_NAME)
    else:
        clear_all_but_first_page()


if __name__ == "__main__":
    main()
3 Likes

Can you please tell me in order to use switch_page_button what i have to install beacus it’s showing an error like this Import “streamlit_extras.switch_page_button” could not be resolved

Hi @rafikul-m , just do pip install streamlit_extras

@willhuang after run this pip install streamlit_extras in PowerShell this happened :disappointed:

Oops do pip install streamlit-extras

pip install streamlit-extras also showing same errors.

@blackary without using streamlit_extras components any other possible way to do the same things ? i tried to install streamlit-extras but did not work.:disappointed:

You can reproduce the switch_page function by looking at the streamlit extras gallery https://extras.streamlitapp.com/Switch%20page%20function

def switch_page(page_name: str):
    from streamlit import _RerunData, _RerunException
    from streamlit.source_util import get_pages

    def standardize_name(name: str) -> str:
        return name.lower().replace("_", " ")

    page_name = standardize_name(page_name)

    pages = get_pages("streamlit_app.py")  # OR whatever your main page is called

    for page_hash, config in pages.items():
        if standardize_name(config["page_name"]) == page_name:
            raise _RerunException(
                _RerunData(
                    page_script_hash=page_hash,
                    page_name=page_name,
                )
            )

    page_names = [standardize_name(config["page_name"]) for config in pages.values()]

    raise ValueError(f"Could not find page {page_name}. Must be one of {page_names}")
1 Like

Hi @rafikul-m, could you please let me know what needs to go to the pages.json file. I think it’s not working for me because of that. Thanks in advance.

Hello @Gyuzala No need of any changes in pages.json file. When you run the code for the first time. It will create a pages.json file and if you change the name of any page’s then only you have to delete the pages.json file and again have to run the all code.

Try this code once instead of the above one and change the name of DEFAULE_PAGE & SECOND_PAGE_NAME according to the page name you used.

# import module
import json
import sqlite3
import hashlib
import requests
import streamlit as st
from pathlib import Path
from streamlit_lottie import st_lottie
from streamlit_extras.switch_page_button import switch_page
from streamlit.source_util import _on_pages_changed, get_pages


DEFAULT_PAGE = "1_🔐_Login.py"
SECOND_PAGE_NAME = "Home"

# all pages request
def get_all_pages():
    default_pages = get_pages(DEFAULT_PAGE)

    pages_path = Path("pages.json")

    if pages_path.exists():
        saved_default_pages = json.loads(pages_path.read_text())
    else:
        saved_default_pages = default_pages.copy()
        pages_path.write_text(json.dumps(default_pages, indent=4))

    return saved_default_pages

# clear all page but not login page
def clear_all_but_first_page():
    current_pages = get_pages(DEFAULT_PAGE)

    if len(current_pages.keys()) == 1:
        return

    get_all_pages()

    # Remove all but the first page
    key, val = list(current_pages.items())[0]
    current_pages.clear()
    current_pages[key] = val

    _on_pages_changed.send()

# show all pages
def show_all_pages():
    current_pages = get_pages(DEFAULT_PAGE)

    saved_pages = get_all_pages()

    # Replace all the missing pages
    for key in saved_pages:
        if key not in current_pages:
            current_pages[key] = saved_pages[key]

    _on_pages_changed.send()

# Hide default page
def hide_page(name: str):
    current_pages = get_pages(DEFAULT_PAGE)

    for key, val in current_pages.items():
        if val["page_name"] == name:
            del current_pages[key]
            _on_pages_changed.send()
            break

# calling only default(login) page  
clear_all_but_first_page()


# Convert Pass into hash format
def make_hashes(password):
    return hashlib.sha256(str.encode(password)).hexdigest()


# Check password matches during login
def check_hashes(password, hashed_text):
    if make_hashes(password) == hashed_text:
        return hashed_text
    return False

# DB Management
conn = sqlite3.connect("user_data.db")
c = conn.cursor()

# DB Functions for create table
def create_usertable():
    c.execute(
        "CREATE TABLE IF NOT EXISTS userstable(username TEXT,email TEXT, password TEXT)"
    )

# Insert the data into table
def add_userdata(username, email, password):
    c.execute(
        "INSERT INTO userstable(username,email,password) VALUES (?,?,?)",
        (username, email, password),
    )
    conn.commit()

# Password and email fetch
def login_user(email, password):
    c.execute(
        "SELECT * FROM userstable WHERE email =? AND password = ?", (email, password)
    )
    data = c.fetchall()
    return data

# View all user data
def view_all_users():
    c.execute("SELECT * FROM userstable")
    data = c.fetchall()
    return data

# session state 
if "logged_in" not in st.session_state:
    st.session_state["logged_in"] = False
    



st.markdown("<h2 style='text-align: center; color: #C059C0;'> Welcome!</h2>", unsafe_allow_html=True)
st.write('-----')

# Main function
def main():
    # """Login page"""
    menu = ["Login", "SignUp"]
    choice = st.selectbox(
        "Select one option â–Ÿ",
        menu,
    )
    # Default choice
    if choice == "":
        st.subheader("Login")
    # if chice login
    elif choice == "Login":
        st.write("-------")
        # st.subheader("Log in")
        with st.form('Login'):
            email = st.text_input("Email Id", placeholder="email")
            password = st.text_input("Password", type="password")
            login_button = st.form_submit_button('Login')
            
            if login_button:
                # if password == '12345':
                # Hash password creation and store in a table
                create_usertable()
                hashed_pswd = make_hashes(password)
                result = login_user(email, check_hashes(password, hashed_pswd))
                
                if result:
                    st.session_state["logged_in"] = True
                    st.success("Logged In Sucessfully")
                else:
                    st.warning("Incorrect Email Id/Password")
    
    elif choice == "SignUp":
        st.write("-----")
        st.subheader("Create New Account")
        with st.form('Create New Account'):
            new_user = st.text_input("Username", placeholder="name")
            new_user_email = st.text_input("Email id", placeholder="email")
            new_password = st.text_input("Password", type="password")
            signup_button = st.form_submit_button('SignUp')
            
            if signup_button:
                
                if new_user == "":  # if user name empty then show the warnings
                    st.warning("Inavlid user name")
                elif new_user_email == "":  # if email empty then show the warnings
                    st.warning("Invalid email id")
                elif new_password == "":  # if password empty then show the warnings
                    st.warning("Invalid password")
                else:
                    create_usertable()
                    add_userdata(new_user, new_user_email, make_hashes(new_password))
                    st.success("You have successfully created a valid Account!")
                    st.info("Go up and Login to you account.")
    # session state checking
    if st.session_state["logged_in"]:
        show_all_pages()  # call all page
        hide_page(DEFAULT_PAGE.replace(".py", ""))  # hide first page
        switch_page(SECOND_PAGE_NAME)   # switch to second page
    else:
        clear_all_but_first_page()  # clear all page but show first page


if __name__ == "__main__":
    main()

Note : If it does not work for you please share the error messages and all page’s names.

1 Like

Thank you, all worked!

1 Like

And if we want a logout button and the app to redirect us to login can we build an adaptation?

@GerardoObeid Yeah! You may need to create a logout button; after successfully logging in to the first page, a logout button will appear, and you must write code to redirect to the default login page if that button is pressed. As an example, check the code below.

# clear all page but not login page
def clear_all_but_first_page():
    current_pages = get_pages(DEFAULT_PAGE)

    if len(current_pages.keys()) == 1:
        return

    get_all_pages()

    # Remove all but the first page
    key, val = list(current_pages.items())[0]
    current_pages.clear()
    current_pages[key] = val

    _on_pages_changed.send()

Hopefully, it will solve your problem.

What should pages.json looks like here?
I created as followed:

{
     "page_0": {
        "page_name": "Home",
        "script_path": "Hello.py",
        "icon": "\uD83D\uDCCA"

    },
    "page_1": {
        "page_name": "page1",
        "script_path": "pages/page1.py",
        "icon": "\uD83D\uDCCA"

    },
    "page_2": {
        "page_name": "page2",
        "script_path": "pages/page2.py",
        "icon": "\uD83D\uDCCA"

    }
}

I am doing login&register and the pages can be seen after but when I click pages in side bar, it runs forever and nothings opens.
following error comes to terminal:
KeyError: 'page_script_hash'

  1. How did you run this app? Do you have main.py to run ‘streamlit run main.py’? If yes, what is the content in main.py @blackary