RedXAuthCodes 1.0.2
A comprehensive authentication and verification API platform providing secure, scalable identity management
License: MIT
Requires Python: >=3.9
Keywords: authentication, verification, email, notification, security, subscription

# RedXAuthCodes

A powerful and secure authentication code generation and verification system with built-in email integration and subscription management.

## Features

- Secure verification code generation with checksum validation
- Email integration for code delivery
- Subscription management system with expiration handling
- PostgreSQL database backend (works with any PostgreSQL database, including free ones)
- Rate limiting and security features
- RedXSecurePayments integration support
- Comprehensive logging and error handling
- Interactive tutorial for new users

## Installation

Basic installation:
```bash
pip install RedXAuthCodes
```

With RedXSecurePayments integration:
```bash
pip install "RedXAuthCodes[redx]"
```

## Quick Start Tutorial

Get started quickly with our interactive tutorial:

```bash
# After installation, run:
python -m RedXAuthCodes.tutorial.cli

# Or use the convenience script:
python tutorial.py
```

The tutorial will guide you through:
1. Generating verification codes
2. Sending email verifications
3. Managing subscriptions
4. Payment integration

Perfect for new users to learn the basics!

## Database Setup Options

1. **Free Replit Database** (Recommended for development):
   - Automatically created when hosting on Replit
   - No additional configuration needed
   - Perfect for development and testing

2. **External PostgreSQL Database**:
   - Use any PostgreSQL provider (e.g., Railway, Supabase, AWS RDS)
   - Many providers offer free tiers
   - Configure via DATABASE_URL environment variable

## Environment Setup

Required environment variables:
```bash
# Database Configuration (Use ONE of these options)
# Option 1: Use individual connection parameters
PGHOST=your-db-host
PGPORT=5432
PGUSER=your-db-user
PGPASSWORD=your-db-password
PGDATABASE=your-db-name

# Option 2: Use connection URL
DATABASE_URL=postgresql://user:password@host:port/dbname

# Email Configuration
SENDER_EMAIL=your-sender@email.com
EMAIL_APP_PASSWORD=your-email-app-password

# For RedXSecurePayments Integration (optional)
STRIPE_SECRET_KEY=your-stripe-secret-key
```

## Basic Usage (Standalone)

### 1. Code Generation and Verification

```python
from RedXAuthCodes import RedXCode, EmailService

# Initialize services
code_generator = RedXCode()
email_service = EmailService()

# Generate a verification code
code_result = code_generator.Generate(
    email="user@example.com",
    length=8,  # Code length (default: 8)
    expiry_minutes=15  # Code expiration time (default: 15)
)

if code_result:
    code, created_at, expires_at = code_result
    print(f"Generated Code: {code}")
    print(f"Created at: {created_at}")
    print(f"Expires at: {expires_at}")

    # Send verification code via email
    email_service.send_verification_code(
        recipient_email="user@example.com",
        code=code
    )

# Verify a code
is_valid = code_generator.IsValid(code)
if is_valid:
    # Activate the code
    success = code_generator.Initiate(code)
```

### 2. Subscription Management

```python
from RedXAuthCodes import SubscriptionService

subscription_service = SubscriptionService()

# Create a new subscription
subscription = subscription_service.create_subscription(
    email="user@example.com",
    plan_type="Premium",
    duration_days=30,
    custom_message="Welcome to Premium!"
)

# Check subscription status
status = subscription_service.check_subscription("user@example.com")
if status.get('active'):
    print("Subscription is active")
    print(f"Expires at: {status['expiration_time']}")

# Cancel subscription
cancelled = subscription_service.resign_subscription("user@example.com")
```

## Integration with RedXSecurePayments

Example of complete purchase flow with payment processing:

```python
import RedXSecurePayments
from RedXAuthCodes import RedXCode, EmailService, SubscriptionService

def process_purchase(email: str, package_type: str = "complete"):
    # Initialize services
    code_generator = RedXCode()
    email_service = EmailService()
    subscription_service = SubscriptionService()

    # Set package price
    prices = {
        "auth_code": 5.00,
        "subscription": 10.00,
        "complete": 15.00
    }
    amount = prices.get(package_type, 15.00)

    # Step 1: Process payment
    payment_result = RedXSecurePayments.RedXSecureBuy(
        bank_name="Auth Package",
        currency_type="usd",
        currency_amount=amount,
        enable_multiple_payments=False,
        enable_custom_amount=False,
        enable_payment_history=True
    )

    if not payment_result['success']:
        return {"success": False, "error": "Payment failed"}

    # Step 2: Verify payment completion
    status = RedXSecurePayments.get_payment_status(
        payment_result['session_id']
    )

    if not status['success'] or status['status'] != 'completed':
        return {"success": False, "error": "Payment verification failed"}

    result = {"success": True}

    # Step 3: Generate verification code if needed
    if package_type in ["auth_code", "complete"]:
        code_result = code_generator.Generate(
            email=email,
            length=8,
            expiry_minutes=15
        )

        if code_result:
            code, created_at, expires_at = code_result
            result.update({
                "code": code,
                "code_expires": expires_at
            })

            # Send verification email
            email_service.send_verification_code(email, code)

    # Step 4: Create subscription if needed
    if package_type in ["subscription", "complete"]:
        subscription = subscription_service.create_subscription(
            email=email,
            plan_type="Premium",
            duration_days=30,
            custom_message="Thank you for subscribing!"
        )

        if subscription:
            result["subscription"] = subscription

    return result

# Example usage
result = process_purchase("user@example.com", "complete")
if result["success"]:
    print(f"Code: {result.get('code')}")
    print(f"Code expires: {result.get('code_expires')}")
    if 'subscription' in result:
        print(f"Subscription active until: {result['subscription']['expiration_time']}")
```

## API Reference

### RedXCode

- `Generate(email: str, length: int = 8, expiry_minutes: int = 15)` 
  - Generates a secure verification code
  - Returns tuple (code, created_at, expires_at) or None

- `IsValid(code: str) -> bool`
  - Checks if a code is valid and not expired

- `Initiate(code: str) -> bool`
  - Activates a verification code
  - Returns True if successful

- `RemoveData(email: str) -> bool`
  - Removes all codes for an email address

### EmailService

- `send_verification_code(recipient_email: str, code: str) -> bool`
  - Sends verification code via email

- `RedXSubEmail(recipient_email: str, expiration_time: str, custom_message: str = "") -> bool`
  - Sends subscription confirmation email

### SubscriptionService

- `create_subscription(email: str, plan_type: str, duration_days: int, custom_message: str = "") -> Dict`
  - Creates a new subscription
  - Returns subscription details or error message

- `check_subscription(email: str) -> Dict`
  - Checks subscription status
  - Returns subscription details or {"active": False}

- `resign_subscription(email: str) -> bool`
  - Cancels active subscription

## Security Features

- Secure code generation with checksums
- Automatic code expiration handling
- Rate limiting on API endpoints
- Email verification
- Secure database storage with PostgreSQL
- Payment verification integration
- Subscription expiration management

## Best Practices

1. Always verify payment completion before generating codes or creating subscriptions
2. Use environment variables for sensitive data
3. Implement proper error handling
4. Monitor rate limits
5. Regular cleanup of expired codes
6. Keep subscriptions updated
7. Use secure email configuration

## Support

For issues and feature requests, please visit our GitHub repository: https://github.com/redxdev/redxauthcodes

## License

MIT License - See LICENSE file for details