Skip to main content

Fast and secure authentication library for Python applications

Project description

QuickRedTech-AUTH-

Overview

QuickRedTech-AUTH- is a fast, secure Python authentication library designed for modern backend applications. It combines industry-standard cryptographic practices with an intuitive API for rapid integration.

Key Features

Security:

  • Bcrypt Password Hashing: Computationally secure hashing resistant to brute-force attacks
  • JWT Token Management: Stateless, cryptographically signed tokens with automatic expiration
  • Memory Safe: Wraps proven C-based cryptographic libraries to avoid buffer overflows and timing attacks

Performance:

  • Zero database lookups for token verification (mathematical verification via HMAC-SHA256)
  • Minimal overhead for password operations
  • Lightning-fast API routing with stateless JWT sessions

Installation

1. Install Dependencies

pip install -r requirements.txt

2. Import the Library

from core import QuickRedTechAuth

Quick Start

# Initialize with a strong secret key
auth = QuickRedTechAuth(
    secret_key="your_secret_key_minimum_32_characters_long",
    token_expiry_minutes=60
)

# --- User Registration ---
hashed_password = auth.hash_password("user_secure_password")

# --- User Login ---
if auth.verify_password("user_secure_password", hashed_password):
    token = auth.generate_token(user_id=123, role="admin")
    print(f"Access Token: {token}")

# --- Token Verification ---
try:
    payload = auth.verify_token(token)
    print(f"User ID: {payload['sub']}")
except Exception as e:
    print(f"Invalid token: {e}")

API Reference

QuickRedTechAuth

Constructor

QuickRedTechAuth(secret_key: str, token_expiry_minutes: int = 60)

Parameters:

  • secret_key (str): Cryptographically secure secret key (minimum 32 characters recommended for security)
  • token_expiry_minutes (int): JWT expiration time in minutes (default: 60)

Raises:

  • ValueError: If secret_key is less than 32 characters

hash_password(plain_text_password: str) -> str

Hashes a password using bcrypt.

Parameters:

  • plain_text_password (str): The plaintext password to hash

Returns:

  • str: The bcrypt hashed password (safe for database storage)

Example:

hashed = auth.hash_password("my_password")

verify_password(plain_text_password: str, hashed_password: str) -> bool

Verifies a plaintext password against a stored bcrypt hash.

Parameters:

  • plain_text_password (str): The password to verify
  • hashed_password (str): The stored bcrypt hash

Returns:

  • bool: True if password matches, False otherwise

Example:

is_valid = auth.verify_password("my_password", stored_hash)

generate_token(user_id: str | int, **extra_payload) -> str

Generates a JWT token for the user.

Parameters:

  • user_id (str | int): The unique user identifier
  • **extra_payload: Additional claims (e.g., role="admin", email="user@example.com")

Returns:

  • str: The encoded JWT token

Example:

token = auth.generate_token(user_id=123, role="admin", email="user@example.com")

verify_token(token: str) -> dict

Verifies a JWT token and returns its payload.

Parameters:

  • token (str): The JWT token to verify

Returns:

  • dict: The decoded token payload

Raises:

  • Exception: If token is expired or invalid

Example:

try:
    payload = auth.verify_token(token)
    print(f"User ID: {payload['sub']}")
except Exception as e:
    print(f"Invalid token: {e}")

Token Payload Structure

Tokens contain the following claims:

  • sub (subject): User ID
  • exp (expiration): Token expiration time (Unix timestamp)
  • iat (issued at): Token creation time (Unix timestamp)
  • Additional custom claims from **extra_payload

Example Decoded Token:

{
  "sub": "123",
  "role": "admin",
  "email": "user@example.com",
  "iat": 1713696000,
  "exp": 1713699600
}

Security Best Practices

  1. Secret Key Management

    • Use at least 32 characters for secret_key
    • Store secrets in environment variables, never hardcode them
    • Use different secrets for different environments (dev, staging, prod)
  2. Password Security

    • Never store plaintext passwords
    • Always use hash_password() before storing
    • Always use verify_password() during login
  3. Token Management

    • Set appropriate token_expiry_minutes based on your use case
    • Implement token refresh mechanisms for long-lived sessions
    • Validate tokens on every protected endpoint
  4. HTTPS Only

    • Always transmit tokens over HTTPS
    • Never send tokens in query parameters

Example Integration with Flask

from flask import Flask, request, jsonify
from core import QuickRedTechAuth
import os

app = Flask(__name__)
auth = QuickRedTechAuth(secret_key=os.environ.get('AUTH_SECRET_KEY'))

@app.route('/register', methods=['POST'])
def register():
    data = request.json
    hashed_password = auth.hash_password(data['password'])
    # Save user with hashed_password to database
    return jsonify({"message": "User registered"}), 201

@app.route('/login', methods=['POST'])
def login():
    data = request.json
    # Retrieve user from database
    if auth.verify_password(data['password'], stored_hash):
        token = auth.generate_token(user_id=user_id, role=user_role)
        return jsonify({"access_token": token}), 200
    return jsonify({"error": "Invalid credentials"}), 401

@app.route('/protected', methods=['GET'])
def protected():
    token = request.headers.get('Authorization', '').replace('Bearer ', '')
    try:
        payload = auth.verify_token(token)
        return jsonify({"user_id": payload['sub']}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 401

Running the Demo

To see the library in action, run the example script:

python main.py

This will demonstrate:

  1. User registration (password hashing)
  2. User login (password verification & token generation)
  3. Failed login attempts
  4. Protected API requests (token verification)
  5. Invalid token rejection

Dependencies

  • bcrypt (v4.1.2): Industry-standard password hashing
  • PyJWT (v2.8.0): JSON Web Token encoding/decoding

Architecture

QuickRedTech-AUTH-/
├── __init__.py           # Package initialization
├── core.py              # QuickRedTechAuth class (main implementation)
├── main.py              # Example usage and demo
├── requirements.txt     # Python dependencies
├── README.md            # This file
└── LICENSE              # License information

Why This Approach?

Speed

  • JWT verification uses mathematical HMAC-SHA256 (zero database lookups)
  • Token validation scales horizontally without backend session storage

Security

  • Bcrypt's computational cost makes dictionary/brute-force attacks infeasible
  • HMAC-SHA256 prevents token tampering
  • Automatic expiration limits token exposure window

Reliability

  • Leverages battle-tested cryptographic libraries (OpenSSL, libsodium)
  • Avoids custom cryptography (which is prone to bugs)

License

See the LICENSE file for details.

Support

For issues, questions, or contributions, please visit the repository.


QuickRedTech-AUTH-: Making authentication fast and secure. 🔐⚡

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

quickredauth-1.0.0.tar.gz (16.0 kB view details)

Uploaded Source

Built Distribution

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

quickredauth-1.0.0-py3-none-any.whl (13.7 kB view details)

Uploaded Python 3

File details

Details for the file quickredauth-1.0.0.tar.gz.

File metadata

  • Download URL: quickredauth-1.0.0.tar.gz
  • Upload date:
  • Size: 16.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for quickredauth-1.0.0.tar.gz
Algorithm Hash digest
SHA256 935c40e74e1ade4422af28037f326e3a499c6cb24a439da714d817274268a4de
MD5 3671e1509cb0eb142615d00528232015
BLAKE2b-256 41da83fce0493fcd683731d0631574fcf5604d16e9dbac7428e98ae3296b2ef9

See more details on using hashes here.

File details

Details for the file quickredauth-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: quickredauth-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 13.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for quickredauth-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d595b59fa92407d72db909084cbf432abc5571675da0c7a8042e3442e9acc847
MD5 60a5499d9f8cd895c3ce1b964a705ce4
BLAKE2b-256 dddbc90d2f5071113921183c4f13bd1563bc70fb0c08527a0bd98f8891a304e0

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