Metadata-Version: 2.4
Name: authix-python-sdk
Version: 1.0.0
Summary: Official Python SDK for the Authix authentication service
Home-page: https://getauthix.online
Author: Authix Team
Author-email: support@authix.com
Project-URL: Bug Tracker, https://github.com/authix/python-sdk/issues
Project-URL: Documentation, https://docs.getauthix.online
Project-URL: Source Code, https://github.com/authix/python-sdk
Keywords: authentication security jwt api secureauth login oauth
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: System :: Systems Administration :: Authentication/Directory
Requires-Python: >=3.7
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Requires-Dist: cryptography>=3.4.0
Requires-Dist: flask>=2.0.0
Requires-Dist: python-dotenv>=0.19.0
Requires-Dist: aiohttp>=3.8.0
Provides-Extra: dev
Requires-Dist: pytest>=6.0; extra == "dev"
Requires-Dist: pytest-cov>=2.0; extra == "dev"
Requires-Dist: black>=21.0; extra == "dev"
Requires-Dist: flake8>=3.8; extra == "dev"
Requires-Dist: mypy>=0.800; extra == "dev"
Provides-Extra: docs
Requires-Dist: sphinx>=4.0; extra == "docs"
Requires-Dist: sphinx-rtd-theme>=0.5; extra == "docs"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Authix Python SDK

[![PyPI version](https://badge.fury.io/py/authix.svg)](https://badge.fury.io/py/authix)
[![Python versions](https://img.shields.io/pypi/pyversions/authix.svg)](https://pypi.org/project/authix/)
[![License](https://img.shields.io/pypi/l/authix.svg)](https://pypi.org/project/authix/)
[![Downloads](https://img.shields.io/pypi/dm/authix.svg)](https://pypi.org/project/authix/)

Official Python SDK for the Authix authentication service.

## Installation

```bash
pip install authix
```

## Quick Start

```python
import asyncio
from authix import AuthixAPI

async def main():
    # Initialize with your API key
    api = AuthixAPI(api_key="your_api_key_here")
    
    # Register a new user
    result = await api.auth.register(
        username="testuser",
        password="SecurePass123!",
        license_key="AX-XXXX-XXXX-XXXX",
        hwid="device_hash_here",
        app_id="your_app_id",
        app_name="Your App Name"
    )
    print("Registration result:", result)
    
    # Login user
    login_result = await api.auth.login(
        username="testuser",
        password="SecurePass123!",
        hwid="device_hash_here",
        app_id="your_app_id",
        app_name="Your App Name"
    )
    print("Login result:", login_result)

asyncio.run(main())
```

## API Handlers

### Authentication

```python
# Register user
await api.auth.register(username, password, license_key, hwid, app_id, app_name)

# Login user
await api.auth.login(username, password, hwid, app_id, app_name)

# Logout user
await api.auth.logout(token)

# Refresh token
await api.auth.refresh_token(refresh_token)

# Verify token
await api.auth.verify_token(token)
```

### Applications

```python
# List all apps
apps = await api.apps.get_apps()

# Create new app
app = await api.apps.create_app("My App", description="My description")

# Get app details
details = await api.apps.get_app_details(app_id)

# Reset HWID
await api.apps.reset_hwid(app_id, username, password, license_key)
```

### Licenses

```python
# Create license
license = await api.licenses.create_license(app_id, days=30, max_hwids=3)

# Get licenses
licenses = await api.licenses.get_licenses(app_id)

# Get license details
details = await api.licenses.get_license_details(license_key)

# Delete unused licenses
await api.licenses.delete_unused(app_id)

# Revoke license
await api.licenses.revoke_license(license_key)
```

### Users

```python
# Get users
users = await api.users.get_users(app_id)

# Get user details
details = await api.users.get_user_details(app_id, username)

# Disable user
await api.users.disable_user(app_id, username)

# Enable user
await api.users.enable_user(app_id, username)

# Delete user
await api.users.delete_user(app_id, username)

# Update user password
await api.users.update_user_password(app_id, username, new_password)
```

### Security

```python
# Ban HWID
await api.security.ban_hwid(app_id, hwid)

# Unban HWID
await api.security.unban_hwid(app_id, hwid)

# Ban IP
await api.security.ban_ip(app_id, ip_address)

# Unban IP
await api.security.unban_ip(app_id, ip_address)

# Get banned HWIDs
banned_hwids = await api.security.get_banned_hwids(app_id)

# Get banned IPs
banned_ips = await api.security.get_banned_ips(app_id)
```

### Webhooks

```python
# Create webhook
webhook = await api.webhooks.create_webhook(
    app_id, 
    "https://your-webhook-url.com",
    events=["user.login", "user.register"],
    secret="webhook_secret"
)

# List webhooks
webhooks = await api.webhooks.list_webhooks(app_id)

# Get webhook details
details = await api.webhooks.get_webhook_details(app_id, webhook_id)

# Update webhook
await api.webhooks.update_webhook(app_id, webhook_id, url="new_url", events=["user.login"])

# Delete webhook
await api.webhooks.delete_webhook(app_id, webhook_id)

# Test webhook
await api.webhooks.test_webhook(app_id, webhook_id)
```

## Configuration

You can configure the SDK in multiple ways:

### Method 1: Direct parameters

```python
api = AuthixAPI(
    server_url="https://getauthix.online",
    api_key="your_api_key"
)
```

### Method 2: Environment variables

```python
import os
os.environ["AUTHIX_SERVER"] = "https://getauthix.online"
os.environ["AUTHIX_API_KEY"] = "your_api_key"

api = AuthixAPI()  # Will use environment variables
```

## Error Handling

The SDK raises `RuntimeError` for API errors:

```python
try:
    await api.auth.login("user", "pass", "hwid", "app_id", "app_name")
except RuntimeError as e:
    print(f"Authentication failed: {e}")
```

## Advanced Usage

### Using Custom Client

```python
from authix import APIClient, AuthHandler

client = APIClient(server_url="https://getauthix.online", api_key="your_key")
auth = AuthHandler(client)
result = await auth.register(...)
```

### Individual Handlers

```python
from authix import AppsHandler, APIClient

client = APIClient(api_key="your_key")
apps = AppsHandler(client)
app_list = await apps.get_apps()
```

## CLI Tools

The SDK includes a command-line interface:

```bash
# Set environment variables
export AUTHIX_API_KEY="your_api_key"
export AUTHIX_SERVER="https://getauthix.online"

# Check server health
authix-cli health

# Register user
authix-cli register username password license_key hwid app_id app_name

# Login user
authix-cli login username password hwid app_id app_name

# List applications
authix-cli apps

# Create application
authix-cli create-app "My App" --description "My description"

# Create license
authix-cli create-license app_id --days 30 --max-hwids 3

# Ban HWID
authix-cli ban-hwid app_id hwid

# Create webhook
authix-cli create-webhook app_id https://webhook.com --events user.login user.register --secret secret
```

## License

This project is licensed under the GNU General Public License - see the [LICENSE](LICENSE) file for details.

## Support

- 📖 **Documentation:** [https://docs.getauthix.online](https://docs.getauthix.online)
- 🐛 **Issues:** [GitHub Issues](https://github.com/authix/python-sdk/issues)
- 💬 **Discord:** [Join our Discord](https://discord.gg/authix)
- 📧 **Email:** [support@authix.com](mailto:support@authix.com)
## Examples

### Complete Flask Application

```python
from flask import Flask, request, jsonify, render_template_string
from secureauth_client import SecureAuthClient, SecureAuthFlask, SecureAuthError

app = Flask(__name__)
app.secret_key = 'your-secret-key'

# SecureAuth configuration
app.config['SECUREAUTH_API_KEY'] = 'sak_6266b5a44517a29999cead848062739b81e6d7343f71062eed3001d18b651efa'
app.config['SECUREAUTH_API_SECRET'] = '40d4435182c2fe81a3ce66b47d9a0d50b6847114d78694c08c7309279fdf231df727d4aa38948f5408524e3a6d5fcb2ff81d40283a3fe1861fabaad6a6eaa867'
app.config['SECUREAUTH_BASE_URL'] = 'http://localhost:3002'

# Initialize SecureAuth
secureauth = SecureAuthFlask(app)

# HTML Template
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <title>SecureAuth Python Demo</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .container { max-width: 600px; margin: 0 auto; }
        .form-group { margin: 15px 0; }
        label { display: block; margin-bottom: 5px; }
        input { width: 100%; padding: 8px; }
        button { padding: 10px 20px; background: #007bff; color: white; border: none; }
        .error { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
    <div class="container">
        <h1>SecureAuth Python Demo</h1>
        {% if error %}
        <div class="error">{{ error }}</div>
        {% endif %}
        {% if success %}
        <div class="success">{{ success }}</div>
        {% endif %}
        
        {% if not current_user %}
        <form method="post">
            <div class="form-group">
                <label>Email:</label>
                <input type="email" name="email" value="fwaaryn@gmail.com" required>
            </div>
            <div class="form-group">
                <label>Password:</label>
                <input type="password" name="password" value="2117" required>
            </div>
            <button type="submit">Login</button>
        </form>
        {% else %}
        <h2>Welcome, {{ current_user.username }}!</h2>
        <p>Email: {{ current_user.email }}</p>
        <p>Role: {{ current_user.role }}</p>
        <p>Verified: {{ 'Yes' if current_user.is_verified else 'No' }}</p>
        
        <h3>API Test Results:</h3>
        <pre>{{ api_results }}</pre>
        
        <form method="post" action="/logout">
            <button type="submit">Logout</button>
        </form>
        {% endif %}
    </div>
</body>
</html>
"""

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

@app.route('/', methods=['POST'])
def login():
    email = request.form.get('email')
    password = request.form.get('password')
    
    try:
        # Direct login to SecureAuth server
        import requests
        login_url = f"{app.config['SECUREAUTH_BASE_URL']}/api/v1/auth/login"
        
        response = requests.post(login_url, json={
            'email': email,
            'password': password,
            'deviceFingerprint': request.headers.get('User-Agent', '')
        })
        
        if response.status_code == 200:
            result = response.json()
            # Store token in session
            from flask import session
            session['access_token'] = result['accessToken']
            session['user'] = result['user']
            
            return render_template_string(HTML_TEMPLATE, 
                current_user=result['user'],
                success="Login successful!")
        else:
            error_data = response.json() if response.headers.get('content-type') == 'application/json' else {}
            return render_template_string(HTML_TEMPLATE, 
                error=error_data.get('error', 'Login failed'))
            
    except Exception as e:
        return render_template_string(HTML_TEMPLATE, error=f"Login error: {str(e)}")

@app.route('/dashboard')
@secureauth.require_auth
def dashboard():
    client = SecureAuthClient(
        app.config['SECUREAUTH_API_KEY'],
        app.config['SECUREAUTH_API_SECRET'],
        app.config['SECUREAUTH_BASE_URL']
    )
    
    api_results = {}
    
    try:
        # Test various API endpoints
        api_results['profile'] = client.get_user_info(request.current_user['id'])
        api_results['sessions'] = client.get_user_sessions(request.current_user['id'])
        
        if request.current_user['role'] == 'admin':
            api_results['admin_dashboard'] = client.log_security_event(
                'dashboard_access', 
                'low', 
                {'user': request.current_user['username']}
            )
    except Exception as e:
        api_results['error'] = str(e)
    
    return render_template_string(HTML_TEMPLATE, 
        current_user=request.current_user,
        api_results=str(api_results))

@app.route('/logout', methods=['POST'])
def logout():
    from flask import session
    session.clear()
    return render_template_string(HTML_TEMPLATE, success="Logged out successfully!")

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
```

### FastAPI Integration

```python
from fastapi import FastAPI, Depends, HTTPException, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from secureauth_client import SecureAuthClient, SecureAuthError
from pydantic import BaseModel

app = FastAPI()
security = HTTPBearer()

# Initialize SecureAuth client
secureauth_client = SecureAuthClient(
    api_key="your_api_key",
    api_secret="your_api_secret",
    base_url="http://localhost:3002"
)

class LoginRequest(BaseModel):
    email: str
    password: str

async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    try:
        result = secureauth_client.verify_token(credentials.credentials)
        if not result['success']:
            raise HTTPException(status_code=401, detail="Invalid token")
        return result['user']
    except SecureAuthError as e:
        raise HTTPException(status_code=401, detail=str(e))

@app.post("/login")
async def login(request: LoginRequest):
    try:
        import requests
        response = requests.post("http://localhost:3002/api/v1/auth/login", json={
            "email": request.email,
            "password": request.password,
            "deviceFingerprint": "FastAPI Client"
        })
        
        if response.status_code == 200:
            return response.json()
        else:
            raise HTTPException(status_code=400, detail="Login failed")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/protected")
async def protected(current_user: dict = Depends(get_current_user)):
    return {"message": "Access granted", "user": current_user}

@app.get("/admin")
async def admin_only(current_user: dict = Depends(get_current_user)):
    if current_user.get('role') != 'admin':
        raise HTTPException(status_code=403, detail="Admin access required")
    return {"message": "Admin access granted", "user": current_user}
```

## Configuration

### Environment Variables

Create a `.env` file in your project:

```env
SECUREAUTH_API_KEY=your_api_key_here
SECUREAUTH_API_SECRET=your_api_secret_here
SECUREAUTH_BASE_URL=http://localhost:3002
```

### Configuration File

```python
# config.py
import os
from dotenv import load_dotenv

load_dotenv()

SECUREAUTH_CONFIG = {
    'api_key': os.getenv('SECUREAUTH_API_KEY'),
    'api_secret': os.getenv('SECUREAUTH_API_SECRET'),
    'base_url': os.getenv('SECUREAUTH_BASE_URL', 'http://localhost:3002'),
    'timeout': 30,
    'retry_attempts': 3
}
```

## Error Handling

```python
from secureauth_client import SecureAuthError, SecureAuthClient

try:
    client = SecureAuthClient(api_key, api_secret, base_url)
    result = client.verify_token(token)
except SecureAuthError as e:
    print(f"SecureAuth error: {e}")
    # Handle authentication error
except Exception as e:
    print(f"Unexpected error: {e}")
    # Handle other errors
```

## Security Best Practices

1. **Store credentials securely**: Use environment variables, not hardcoded values
2. **Use HTTPS**: Always use HTTPS in production
3. **Validate tokens**: Always verify tokens on each request
4. **Handle errors gracefully**: Don't expose sensitive information in error messages
5. **Implement rate limiting**: Add client-side rate limiting
6. **Log security events**: Log authentication attempts and failures

## Testing

```python
import unittest
from secureauth_client import SecureAuthClient, SecureAuthError

class TestSecureAuthClient(unittest.TestCase):
    def setUp(self):
        self.client = SecureAuthClient(
            api_key="test_key",
            api_secret="test_secret",
            base_url="http://localhost:3002"
        )
    
    def test_verify_token(self):
        # Test with valid token
        result = self.client.verify_token("valid_token")
        self.assertTrue(result['success'])
    
    def test_verify_invalid_token(self):
        # Test with invalid token
        with self.assertRaises(SecureAuthError):
            self.client.verify_token("invalid_token")

if __name__ == '__main__':
    unittest.main()
```

## Deployment

### Docker

```dockerfile
FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY secureauth_client.py .
COPY your_app.py .

EXPOSE 5000

CMD ["python", "your_app.py"]
```

### Requirements.txt

```
requests>=2.28.0
cryptography>=3.4.0
flask>=2.0.0  # if using Flask
django>=4.0.0   # if using Django
fastapi>=0.68.0 # if using FastAPI
python-dotenv>=0.19.0
```

## Support

For issues and questions:
1. Check the [SecureAuth Documentation](../INTEGRATION_GUIDE.md)
2. Review the API endpoints in your SecureAuth server
3. Test with the provided examples
4. Check server logs for authentication errors
