🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

streamlit-auth-mfa

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

streamlit-auth-mfa

A robust library for authentication with Streamlit, featuring 2FA, permissions, and session management.

6.1.3
Maintainers
1

# Streamlit Auth Library

Logo

Python version Streamlit version SQLAlchemy version bcrypt version Pandas version Numpy version pyotp version qrcode version extra-streamlit-components version python-dotenv version

A robust library for authentication with Streamlit, featuring 2FA, permissions, and session management.

Sample App / App de Exemplo

🌎 Available Languages / Idiomas Disponíveis

Summary / Resumo

Streamlit Auth Library is ideal for applications that require secure authentication and access control. With support for 2FA and user management, it provides a complete solution.

A biblioteca Streamlit Auth é ideal para aplicativos que requerem autenticação segura e controle de acesso. Com suporte para 2FA e gerenciamento de usuários, oferece uma solução completa.

Streamlit Auth Library

Description

The Streamlit Auth Library is a robust authentication and user management library for your Streamlit application. With support for two-factor authentication (2FA), permissions, and session management, it is ideal for applications requiring security and access control.

...

Back to README

PyPI

PyPI - streamlit-auth-mfa

Ready-to-Use Screens

Manage Permissions

Manage Permissions

Manage Users

Manage Users

Manage Sessions

Manage Sessions

Login Form

Login Form

2FA Form

2FA Form

Reset Form

Reset Forms

Register Form

Register Form

User Activation Form

User Activation Form

User Profile

User Profile

Instalação

pip install streamlit-auth-mfa

Configuration

The library uses environment variables and configuration files to customize behavior. Make sure to set up the required files before using the library.

.env

Environment variables should be configured in the .env file:

DEBUG=True
LOG_LEVEL=DEBUG

# Banco de Dados
DB_URI=sqlite:///db.sqlite3

# E-mail
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL=seu_email@gmail.com
EMAIL_PASSWORD=sua_senha

# Configuração de Apps
APP_NAMES_FILE=config/app_names.json

Configuration Files

config/app_names.json Define the names of the applications for which you manage permissions:

{
    "APP_NAMES": ["App1", "App2", "App3"]
}

Features

  • Authentication
    • Username and password: Uses bcrypt for security.
    • Optional 2FA: Adds an extra layer of security with TOTP.
    • Session management: Tracks and controls logins.
    • User Activation: Support for activating user accounts via a link sent by email.
  • User and Permission Management
    • Manage users: Add, edit, or delete users.
    • Manage permissions: Control access by application.
  • Email Integration
    • Send transactional emails, including support for attachments and embedded images.

Usage Example

Simple Authentication

from streamlit_auth.authentication import Authenticate

authenticator = Authenticate(
    secret_key='my_secret_key',
    session_expiry_days=7,
    require_2fa=True
)

user_data = authenticator.login("Login")

if user_data['authentication_status']:
    st.success(f"Welcome, {user_data['name']}!")
    authenticator.logout("Logout")
else:
    st.error("Authentication failed. Please check your credentials.")

Autenticação Completa

import streamlit as st

from streamlit_auth.authentication import (
    Authenticate,
    user_manager_main_page,
    user_profile_page,
)
from streamlit_auth.config import settings

TITLE = "Streamlit Authenticate"

def test_page():
    st.set_page_config(page_title=TITLE, layout='wide')
    
    authenticator = Authenticate(
        secret_key='123',
        session_expiry_days=7,
        require_2fa=True,
        auth_reset_views=True,
        site_name='http://localhost:8501/',
    )
    
    user_data = authenticator.login("Login")

    authentication_status = user_data['authentication_status']
    name = user_data['name']
    username = user_data['username']
    authenticated_2fa = user_data['authenticated_2fa']
    role = user_data['role']

    st.sidebar.write(TITLE)
    
    # Basic Messages
    if not authentication_status:
        st.warning("Please enter your username.")
        authenticator.user_register_form()
        return

    # Logout
    if authentication_status:
        authenticator.logout("Logout")

    # If already authenticated with 2FA, display the application
    if authentication_status and authenticated_2fa:
        
        admin_options = ['Manage']
        user_options = ['User Profile']
        
        st.write('Authenticated')
        
        if role == 'admin':
            user_permissions = user_options + admin_options
            
        else:
            user_permissions = authenticator.get_user_apps_perms(username)
            user_permissions += user_options
        
        selected_option = st.sidebar.selectbox(
            "Select an option:",
            user_permissions,
        )
        
        if role == 'admin' and selected_option == "Manage":
            user_manager_main_page()
        
        if selected_option == "User Profile":
            user_profile_page(user_data)

Management

Use the user_manager_main_page function to display the user permissions management screen. Here is how to implement it:

from streamlit_auth.authentication import user_manager_main_page

# Screen for managing permissions and users
user_manager_main_page()

Run the server with the created file:

streamlit run <arquivo criado>.py

Database Configuration

The library uses SQLAlchemy for database management, allowing you to configure any URI supported by SQLAlchemy. You can set the database URI in the .env file:

DB_URI=<your_database_uri>

Examples of valid URIs:

  • SQLite: sqlite:///db.sqlite3
  • PostgreSQL: postgresql://user:password@localhost/dbname
  • MySQL: mysql+pymysql://user:password@localhost/dbname
  • Microsoft SQL Server: mssql+pyodbc://user:password@dsn

Refer to the SQLAlchemy documentation for more details on supported database URIs.

Database Models

The library provides built-in models for managing users and sessions:

  • TbUsuarioStreamlit - User management.
  • TbSessaoStreamlit - Session tracking.
  • TbPermissaoUsuariosStreamlit - Permission control.

Email Sending

With the SendMail class, you can send emails with support for attachments and images.

from streamlit_auth.enviar_email import SendMail

with SendMail(
    host="smtp.gmail.com",
    port=587,
    email="your_email@gmail.com",
    password="your_password",
) as mailer:
    mailer.destinatarios = ["recipient@gmail.com"]
    mailer.assunto = "Test"
    mailer.enviar_email("Hello, this is a test message!")

License

This library is distributed under the MIT license. See the LICENCE file for more details.

FAQs

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts