Skip to main content

Official Python SDK for the Authix authentication service

Project description

Authix Python SDK

PyPI version Python versions License Downloads

Official Python SDK for the Authix authentication service.

Installation

pip install authix

Quick Start

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

# 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

# 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

# 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

# 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

# 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

# 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

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

Method 2: Environment variables

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:

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

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

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:

# 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 file for details.

Support

Examples

Complete Flask Application

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

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:

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

Configuration File

# 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

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

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

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
  2. Review the API endpoints in your SecureAuth server
  3. Test with the provided examples
  4. Check server logs for authentication errors

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

authix_python_sdk-1.0.0.tar.gz (22.5 kB view details)

Uploaded Source

Built Distribution

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

authix_python_sdk-1.0.0-py3-none-any.whl (18.2 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for authix_python_sdk-1.0.0.tar.gz
Algorithm Hash digest
SHA256 a6cd476a923aae3b98ede81d0c60a6c18e6d6ed6719611cb79a7d22ac08b4023
MD5 d4d35ddc83464b71204b5b04ef808646
BLAKE2b-256 6539fe282b7b46bf6b164e104bd90cf4dcc668dfc028345eeda264d789f565d3

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for authix_python_sdk-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 60e5f681b3969cc5613902ac4bc246b257f1c53401c6fd7aa2cb4203f9712d72
MD5 00d754a9e1c1f6b382190fca1171575f
BLAKE2b-256 9082a8ba1ed4cd3a5c07d407c9a67917b5502e6ae454fb707544ac6339ce4bcb

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