How to set login password for my streamlit app

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

1 Like

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()

2 Likes

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))

2 Likes

For more robust ā€œenterpriseā€ login thatā€™s simple to use, you can take a look at my Auth0 login component.

1 Like