Skip to main content

A complete authentication library including TOTP, HOTP, Active Directory, and more.

Project description

AllSafe Authentication Library

GitHub GitHub Stars GitHub Issues GitHub Pull Requests

GitHub Repository: [{github_link}]

https://github.com/daniel-destaw/allsafe-auth.git

AllSafe Authentication is a comprehensive Python library designed to simplify and enhance user authentication and authorization in your applications. It provides a wide range of authentication methods, multi-factor authentication (MFA) capabilities, robust user and role management, and security features. It's designed to be modular and extensible, allowing you to tailor it to your specific security needs. AllSafe aims to be the cornerstone of your application's security, providing a robust, flexible, and easy-to-use solution for managing user identity and access.

Features

AllSafe Authentication offers a wide array of features, categorized as follows:

  • Authentication Methods: The core of the library, providing various ways to verify user identity.
  • Multi-Factor Authentication (MFA): Enhances security by requiring users to provide multiple forms of verification.
  • User and Role Management: Tools for managing users, their roles, and permissions within your application.
  • Security: Features that protect your application and user data.
  • Utilities: Helper functions for common tasks related to authentication and security.

Here's a detailed breakdown of each category:

Authentication Methods:

  • Active Directory: Seamlessly integrate with existing Active Directory deployments for centralized user authentication. This allows users to use their existing network credentials to access your application. AllSafe handles the complexities of the LDAP protocol, making integration straightforward.
  • TOTP (Time-based One-Time Password): Support for time-based OTP generation, as used by popular authenticator apps like Google Authenticator, Authy, and Microsoft Authenticator. TOTP codes change frequently (e.g., every 30 seconds), providing a high level of security.
  • HOTP (HMAC-based One-Time Password): Support for counter-based OTP. HOTP codes are generated based on a counter that increments with each use. While less common than TOTP, HOTP can be useful in specific scenarios.
  • Google Authenticator: Streamlined integration with the Google Authenticator app, allowing users to easily set up and use TOTP authentication. This includes generating QR codes that users can scan with the app.
  • OAuth2 and OpenID Connect: Support for modern authentication and authorization protocols. OAuth2 enables secure delegated access, allowing users to grant applications limited access to their resources without sharing their credentials. OpenID Connect adds an identity layer to OAuth2, providing user identity information.
  • SAML (Security Assertion Markup Language): Support for SAML-based Single Sign-On (SSO). SAML allows users to log in once and access multiple web applications without re-authenticating, improving user experience and simplifying authentication management in enterprise environments.

Multi-Factor Authentication (MFA):

  • MFA Management: Enforce and manage MFA for enhanced security. AllSafe provides tools to require users to set up and use MFA, and to manage their MFA devices.
  • Backup Methods: Support for backup MFA methods like SMS and email. In case a user loses access to their primary authentication device (e.g., their phone), they can use a backup method to regain access to their account.

User and Role Management:

  • User Management: User registration, authentication, and management. AllSafe provides functions for creating, updating, and deleting user accounts, as well as handling user authentication (e.g., verifying passwords).
  • Role-Based Access Control (RBAC): Define and manage user roles and permissions. RBAC allows you to control what actions users are allowed to perform within your application, based on their assigned roles.
  • User/Role data persistence with pluggable resolvers:
    • LDAP: Resolve user and role information from LDAP servers. This allows you to integrate with existing directory services.
    • MySQL: Resolve user and role information from MySQL databases.
    • PostgreSQL: Resolve user and role information from PostgreSQL databases.
    • MongoDB: Resolve user and role information from MongoDB.
  • Resolver Management: Abstraction layer for managing different resolvers. This allows you to easily switch between different data sources for user and role information.

Security:

  • Password Policies: Enforce strong password policies and handle password resets. AllSafe can help you ensure that users choose strong passwords and provides tools for handling password resets in a secure manner.
  • Session Management: Securely manage user sessions. This includes creating, validating, and destroying sessions, as well as protecting against session hijacking.
  • Encryption: Utilities for data encryption. AllSafe provides functions for encrypting sensitive data, such as passwords and personal information.
  • Audit Logging: Log authentication and authorization activities for auditing and monitoring. This allows you to track who accessed what and when, which is essential for security and compliance.

Utilities:

  • QR Code Generation: Generate QR codes for easy TOTP and HOTP setup. Users can scan these QR codes with their authenticator apps to quickly configure their accounts.
  • Configuration Loader: Flexible configuration loading. AllSafe provides a way to load configuration settings from various sources, such as files or environment variables.
  • Input Validators: Validate user input for security. This helps prevent common security vulnerabilities, such as SQL injection and cross-site scripting.

Installation

You can install AllSafe Authentication using pip:

pip install allsafe_auth

Ideally, the secret would be stored securely per user in your database

secret = TOTPAuth.generate_secret()
totp_auth = TOTPAuth(secret=secret)

# Generate QR code data for user to scan with their authenticator app
account_name = "user@example.com"  #  Use the user's email or username
issuer_name = "MyApplication"      #  The name of your application
qr_code_data = QRCodeGenerator.generate_uri(issuer_name, account_name, secret)
print(f"QR Code Data: {qr_code_data}") #  Display this to the user (e.g., in a web page)

In a real application, you would display the QR code to the user

and prompt them to enter the TOTP code from their authenticator app.

For this example, we'll just simulate the user entering a code.

user_code = input("Enter the TOTP code from your authenticator app: ")

if totp_auth.verify(user_code):
    print("Authentication successful!")
else:
    print("Authentication failed.")
Quick Example (HOTP)from allsafe_auth.authentication.hotp import HOTP
from allsafe_auth.utils.qr_code_generator import QRCodeGenerator

if __name__ == "__main__":
    # Example secret key (in a real application, this would be unique per user and stored securely)
    secret_key = "JBSWY3DPEHPK3PXP"
    account_name = "user@example.com"
    issuer_name = "MyApplication"
    qr_filename = "hotp_qr_code.png"  # Name of the PNG file to save

    # Initialize the HOTP generator
    try:
        hotp_generator = HOTP(secret_key)
        initial_counter = 1 # Counter starts from 0 or 1
        current_hotp = hotp_generator.generate(counter=initial_counter)  # Counter starts from 1, can be incremented
        print(f"Current HOTP (Counter={initial_counter}): {current_hotp}")
    except ValueError as e:
        print(f"Error initializing HOTP: {e}")
        exit()

    # Generate the URI for Google Authenticator using the secret key for HOTP
    try:
        uri = QRCodeGenerator.generate_uri(issuer_name, account_name, secret_key, type='hotp', counter=initial_counter)

        # Use QRCodeGenerator to save the QR code as a PNG file
        QRCodeGenerator.save_to_file(uri, uri)
        print(f"QR code for HOTP saved as {qr_filename}")
    except Exception as e:
        print(f"Error generating or saving QR code: {e}")
#  In a real application, you would display the QR code and prompt the user for the HOTP code.
#  This is just a simulation for demonstration.
    user_code = input("Enter the HOTP code from your authenticator app: ")
    if hotp_generator.verify(user_code, counter=initial_counter):
        print("HOTP verification successful")
    else:
        print("HOTP verification failed")
Quick Example (HOTP Verification)from allsafe_auth.authentication.hotp import HOTP

if __name__ == "__main__":
    # The same secret key used to generate the HOTP code
    secret_key = "JBSWY3DPEHPK3PXP"

    # Initialize the HOTP verifier with the secret key
    hotp_verifier = HOTP(secret_key)

    # In a real application, you would get the user's HOTP input
    user_hotp = input("Enter the HOTP code from your authenticator app: ")
    counter_value = int(input("Enter the counter value: "))  #  Important:  You MUST track the counter.

    # Verify the HOTP code
    if hotp_verifier.verify(user_hotp, counter=counter_value):
        print("HOTP code is valid.")
    else:
        print("HOTP code is invalid.")
#  IMPORTANT:  For HOTP, you MUST increment and store the counter value 
#  after each successful verification.  This is critical for security.
#  The next verification must use a counter value that is greater 
#  than the one used for the previous verification.
#  For example:
#  next_counter_value = counter_value + 1
#  Store next_counter_value in your database, associated with the user.

Quick Example (TOTP Verification)from allsafe_auth.authentication.totp import TOTP

if __name__ == "__main__":
    # The same secret key used to generate the TOTP code
    secret_key = "JBSWY3DPEHPK3PXP"

    # Initialize the TOTP verifier
    totp_verifier = TOTP(secret_key)

    # Prompt the user to enter the TOTP from their authenticator app
    user_otp = input("Enter the TOTP code from your authenticator app: ")

    # Verify if the user's OTP is valid
    if totp_verifier.verify(user_otp):
        print("OTP verification successful!")
    else:
        print("OTP verification failed!")

# -*- coding: utf-8 -*-

""" AllSafe Authentication Library

A comprehensive Python library designed to simplify and enhance user authentication and authorization in your applications. """

version = "0.1.0" author = "daniel-destaw" license = "MIT" copyright = "Copyright (c) 2025 AllSafe" github_link = "https://github.com/daniel-destaw/allsafe-auth.git"

readme = f"""

AllSafe Authentication Library

GitHub GitHub Stars GitHub Issues GitHub Pull Requests

GitHub Repository: {github_link}

AllSafe Authentication offers a straightforward way to secure your Python applications with various authentication and authorization features. Check out the examples and documentation to get started! Contributions are welcome. Allsafe """

all = ["version", "author", "license", "copyright", "github_link", "readme"]

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

allsafe_authentication-0.0.1.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

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

allsafe_authentication-0.0.1-py3-none-any.whl (19.8 kB view details)

Uploaded Python 3

File details

Details for the file allsafe_authentication-0.0.1.tar.gz.

File metadata

  • Download URL: allsafe_authentication-0.0.1.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.12

File hashes

Hashes for allsafe_authentication-0.0.1.tar.gz
Algorithm Hash digest
SHA256 ce0f1cf8a5d7c727a5df6cec66d4db827e36a0f688d79c64f0bea1d60c9a55a1
MD5 3dc2de758cd051097ddf112e0376d501
BLAKE2b-256 bb56cde7b17fe742ff34f6ba7b92ea787921018758e394f45e561017b1e1a5ce

See more details on using hashes here.

File details

Details for the file allsafe_authentication-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for allsafe_authentication-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5fcba938bb0fd21b8fdef5aaaeae57d08944957c3984879577dcdcb57ea5a165
MD5 52c1d1f0af66e1f1a191668ece51370d
BLAKE2b-256 8d9b72897c1c9e1ebcb919ebb10229e0fb12bb5b4fdb403672388198c27927ae

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