Skip to main content

A secure authentication module to validate user credentials and insert user credentails in Mongodb with streamlit.

Project description

Streamlit Authenticator Mongo

A secure authentication module to validate user credentials stored in a Mongo database in a Streamlit application.

Installation

Streamlit-Authenticator-Mongo is distributed via PyPI:

pip install streamlit-authenticator-mongo

Example

Using Streamlit-Authenticator-Mongo is as simple as importing the module and calling it to verify your predefined users' credentials.

import streamlit as st
import streamlit_authenticator_mongo as stauth

1. Hashing passwords

  • Initially create a YAML configuration file and enter the number of days to expiry for a JWT cookie that will be stored on the client's browser to enable passwordless reauthentication. If you do not require reauthentication, you may set the number of days to expiry to 0.
cookie:
  expiry_days: 30
  key: some_signature_key # Must be string
  name: some_cookie_name
  • Then Initalize a mongodb client and get the collection using the Mongo Client API.
    client = MongoClient(uri)
    db = client["database"]
    collection = db["collection"]
  • Create a Mongodb document and insert to the database as follow. Ensure the password is hashed with the hashing module
    doc = {
        'username':'Johnny',
        'password': stauth.Hasher(['dog']).generate()[0]
        'email': 'johnwick@wicked.com',
        'name': 'John Wick'
    }
    collection.insert_one(doc)

2. Creating a login widget

  • Subsequently import the configuration file and the collection object into your script and create an authentication object.
import yaml
from yaml.loader import SafeLoader
from dbscript import collection

with open('../config.yaml') as file:
    config = yaml.load(file, Loader=SafeLoader)

authenticator = stauth.Authenticate(
    collection,
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],

)
  • Then finally render the login module as follows. Here you will need to provide a name for the login form, and specify where the form should be located i.e. main body or sidebar (will default to main body).
authenticator.login('Login', 'main')

3. Authenticating users

  • You can then retrieve the name, authentication status, and username from Streamlit's session state using st.session_state["name"], st.session_state["authentication_status"], and st.session_state["username"] to allow a verified user to proceed to any restricted content.
  • In addition, you may include an optional logout button at any location on your main body or sidebar (will default to main body). The optional key parameter for the logout widget should be used with multipage applications to prevent Streamlit from throwing duplicate key errors.
if st.session_state["authentication_status"]:
    authenticator.logout('Logout', 'main', key='unique_key')
    st.write(f'Welcome *{st.session_state["name"]}*')
    st.title('Some content')
elif st.session_state["authentication_status"] is False:
    st.error('Username/password is incorrect')
elif st.session_state["authentication_status"] is None:
    st.warning('Please enter your username and password')

  • Or prompt an unverified user to enter a correct username and password.

  • Please note that logging out will revert the authentication status to None and will delete the associated reauthentication cookie as well.

4. Creating a password reset widget

  • You may use the reset_password widget to allow a logged in user to modify their password as shown below.
if st.session_state["authentication_status"]:
    try:
        if authenticator.reset_password(st.session_state["username"], 'Reset password'):
            st.success('Password modified successfully')
    except Exception as e:
        st.error(e)

5. Creating a new user registration widget

  • You may use the register_user widget to allow to allow anyone to sign up. After a successful validation, the new user entry is added to the database. The user can then go an login with the new account
try:
    if authenticator.register_user('Register user'):
        st.success('User registered successfully')
except Exception as e:
    st.error(e)

6. Creating a forgot password widget

  • You may use the forgot_password widget to allow a user to generate a new random password. This password will be automatically hashed and saved in the database. The widget will return the username, email, and new random password of the user which should then be transferred to them securely.
try:
    username_of_forgotten_password, email_of_forgotten_password, new_random_password = authenticator.forgot_password('Forgot password')
    if username_of_forgotten_password:
        st.success('New password to be sent securely')
        # Random password should be transferred to user securely
    else:
        st.error('Username not found')
except Exception as e:
    st.error(e)

7. Creating a forgot username widget

  • You may use the forgot_username widget to allow a user to retrieve their forgotten username. The widget will return the username and email of the user which should then be transferred to them securely.
try:
    username_of_forgotten_username, email_of_forgotten_username = authenticator.forgot_username('Forgot username')
    if username_of_forgotten_username:
        st.success('Username to be sent securely')
        # Username should be transferred to user securely
    else:
        st.error('Email not found')
except Exception as e:
    st.error(e)

Credits

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

streamlit-authenticator-mongo-0.1.5.tar.gz (15.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

streamlit_authenticator_mongo-0.1.5-py3-none-any.whl (15.3 kB view details)

Uploaded Python 3

File details

Details for the file streamlit-authenticator-mongo-0.1.5.tar.gz.

File metadata

File hashes

Hashes for streamlit-authenticator-mongo-0.1.5.tar.gz
Algorithm Hash digest
SHA256 c6c602e86a2bddd4afa702d988afa4071252f19b823945dfc437659e29405663
MD5 401d66d9bc6bca8d954face069b4073c
BLAKE2b-256 b4302ec5ffb557e4b01aabc7d7ad2bca6395800d488c3faa96f1b76ab3727cf8

See more details on using hashes here.

File details

Details for the file streamlit_authenticator_mongo-0.1.5-py3-none-any.whl.

File metadata

File hashes

Hashes for streamlit_authenticator_mongo-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 ea0df0ccd02af5c148f523e2a8cc9493e429eb9adb97052d0f8fc5a997f77fa7
MD5 c3e5cdd87fabc0b0f62a723d712b5c8b
BLAKE2b-256 7ce05eb8ea3b5adc6d4a8415a038371408a9fc899ad2a5dbd250d4212b30dddd

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page