How can i add login and password in my streamlit app …please help
I am no expert but I don’t believe there is any way you can do this with streamlit.
However you can proxy the data through a different web server (say apache or nginx) and set up authentication on that. The following article may help. It does it for Shiny which is like an R equivalent of Streamlit.
Richard
well i found a minimalistic and easy way around using “pwd = st.sidebar.text_input(“Password:”, value=”", type=“password”) "…and then putting yout file or code or script within it …It gave me very basic security for my app
Here is a code you can use or adapt:
#!/usr/bin/env python
coding: utf-8
%%
## Simple Login App
%%
import streamlit as st
import pandas as pd
Security
#passlib,hashlib,bcrypt,scrypt
import hashlib
def make_hashes(password):
return hashlib.sha256(str.encode(password)).hexdigest()
def check_hashes(password,hashed_text):
if make_hashes(password) == hashed_text:
return hashed_text
return False
DB Management
import sqlite3
conn = sqlite3.connect(‘data.db’)
c = conn.cursor()
DB Functions
def create_usertable():
c.execute(‘CREATE TABLE IF NOT EXISTS userstable(username TEXT,password TEXT)’)
def add_userdata(username,password):
c.execute(‘INSERT INTO userstable(username,password) VALUES (?,?)’,(username,password))
conn.commit()
def login_user(username,password):
c.execute(‘SELECT * FROM userstable WHERE username =? AND password = ?’,(username,password))
data = c.fetchall()
return data
def view_all_users():
c.execute(‘SELECT * FROM userstable’)
data = c.fetchall()
return data
def main():
“”“Simple Login App”""
st.title("Simple Login App")
menu = ["Home","Login","SignUp"]
choice = st.sidebar.selectbox("Menu",menu)
if choice == "Home":
st.subheader("Home")
elif choice == "Login":
st.subheader("Login Section")
username = st.sidebar.text_input("User Name")
password = st.sidebar.text_input("Password",type='password')
if st.sidebar.checkbox("Login"):
# if password == '12345':
create_usertable()
hashed_pswd = make_hashes(password)
result = login_user(username,check_hashes(password,hashed_pswd))
if result:
st.success("Logged In as {}".format(username))
task = st.selectbox("Task",["Add Post","Analytics","Profiles"])
if task == "Add Post":
st.subheader("Add Your Post")
elif task == "Analytics":
st.subheader("Analytics")
elif task == "Profiles":
st.subheader("User Profiles")
user_result = view_all_users()
clean_db = pd.DataFrame(user_result,columns=["Username","Password"])
st.dataframe(clean_db)
else:
st.warning("Incorrect Username/Password")
elif choice == "SignUp":
st.subheader("Create New Account")
new_user = st.text_input("Username",key='1')
new_password = st.text_input("Password",type='password',key='2')
if st.button("Signup"):
create_usertable()
add_userdata(new_user,make_hashes(new_password))
st.success("You have successfully created a valid Account")
st.info("Go to Login Menu to login")
if name == ‘main’:
main()
This is using validation with AD:
import ldap3
class Ldap:
“”“Class for LDAP related connections/operations.”""
def __init__(self, server_uri, ldap_user, ldap_pass):
self.server = ldap3.Server(server_uri, get_info=ldap3.ALL)
self.conn = ldap3.Connection(self.server, user=ldap_user, password=ldap_pass, auto_bind=True)
def who_am_i(self):
return self.conn.extend.standard.who_am_i()
def get_groups(self):
self.conn.search('dc=fill_this_1,dc=fill_this_2', '(objectClass=group)')
return self.conn.entries
def get_groups_with_members(self):
fq_groups = [result.entry_dn for result in ldap.get_groups()]
groups_with_members = {}
for group in fq_groups:
self.conn.search(group, '(objectclass=group)', attributes=['sAMAccountName'])
if 'sAMAccountName' in self.conn.entries[0]:
groups_with_members[group] = self.conn.entries[0]['sAMAccountName'].values
return groups_with_members
def get_members_with_groups(self):
groups_with_members = self.get_groups_with_members()
members_with_groups = {}
for group, members in groups_with_members.items():
for member in members:
if not member in members_with_groups:
members_with_groups[member] = []
members_with_groups[member].append(group)
return members_with_groups
if name == ‘main’:
LDAP_URI = ‘misitio.com:389’
usuario = ‘user@misitio.com’
clave = ‘------’
try:
ldap = Ldap(LDAP_URI, usuario, clave)
if ldap:
print(‘Usuario autenticado. Bienvenido {0}’.format(ldap.who_am_i()))
#print(ldap.get_groups())
except ldap3.core.exceptions.LDAPBindError as bind_error:
print(str(bind_error))
except ldap3.core.exceptions.LDAPPasswordIsMandatoryError as pwd_mandatory_error:
print(str(pwd_mandatory_error))
For more robust “enterprise” login that’s simple to use, you can take a look at my Auth0 login component.