Metadata-Version: 2.4
Name: quickredauth
Version: 1.0.0
Summary: Fast and secure authentication library for Python applications
Home-page: https://github.com/QRTQuick/QuickRedTech-AUTH-
Author: QRTQuick
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: bcrypt==4.1.2
Requires-Dist: PyJWT==2.8.0
Dynamic: author
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# 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

```bash
pip install -r requirements.txt
```

### 2. Import the Library

```python
from core import QuickRedTechAuth
```

## Quick Start

```python
# 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

```python
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:**
```python
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:**
```python
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:**
```python
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:**
```python
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:**
```json
{
  "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

```python
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:

```bash
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. 🔐⚡
