Skip to main content

Zero-knowledge proof authentication SDK for Python

Project description

ZKAuth Python SDK

Zero-knowledge proof authentication for Python applications.

Installation

pip install zkauth-sdk

Quick Start

🔑 First time? Get your API key at: ZKAuth Developer Platform

The SDK connects to the ZKAuth engine automatically - you just need your API key!

Basic Usage

import asyncio
from zkauth import ZKAuthSDK

async def main():
    async with ZKAuthSDK(
        api_key="zka_live_your_api_key_here"
    ) as client:
        # Sign up a new user
        signup_result = await client.sign_up(
            email="user@example.com",
            password="secure-password"
        )
        
        if signup_result.success:
            print(f"User registered: {signup_result.user.email}")
        
        # Sign in
        signin_result = await client.sign_in(
            email="user@example.com",
            password="secure-password"
        )
        
        if signin_result.success:
            print(f"User authenticated: {signin_result.user.email}")
            print(f"Session token: {signin_result.token}")

# Run the async function
asyncio.run(main())

Django Integration

# settings.py
INSTALLED_APPS = [
    # ... other apps
    'zkauth.integrations.django',
]

ZKAUTH_CONFIG = {
    'API_KEY': 'zka_live_your_api_key_here',
    'BASE_URL': 'https://zkauth-engine.vercel.app',
    'ENABLE_DEVICE_FINGERPRINTING': True,
}

# views.py
from django.http import JsonResponse
from zkauth.integrations.django import zkauth_required

@zkauth_required
def protected_view(request):
    user = request.zkauth_user
    return JsonResponse({
        'message': 'Access granted',
        'user': {
            'id': user.id,
            'email': user.email,
            'created_at': user.created_at.isoformat()
        }
    })

# middleware.py
from zkauth.integrations.django_middleware import ZKAuthMiddleware

# Add to MIDDLEWARE in settings.py
MIDDLEWARE = [
    # ... other middleware
    'zkauth.integrations.django_middleware.ZKAuthMiddleware',
]

FastAPI Integration

from fastapi import FastAPI, Depends, HTTPException
from zkauth.integrations.fastapi import ZKAuthMiddleware, get_current_user
from zkauth.models import User

app = FastAPI(title="ZKAuth FastAPI Demo")

# Add ZKAuth middleware
app.add_middleware(
    ZKAuthMiddleware,
    api_key="zka_live_your_api_key_here",
    base_url="https://zkauth-engine.vercel.app"
)

@app.get("/protected")
async def protected_route(user: User = Depends(get_current_user)):
    return {
        "message": "Access granted",
        "user": {
            "id": user.id,
            "email": user.email,
            "created_at": user.created_at
        }
    }

@app.post("/auth/signup")
async def signup(email: str, password: str):
    async with ZKAuthSDK(api_key="zka_live_your_api_key_here") as client:
        result = await client.sign_up(email, password)
        if not result.success:
            raise HTTPException(status_code=400, detail=result.error)
        return {"user": result.user.dict(), "token": result.token}

Advanced Usage

import asyncio
from zkauth import ZKAuthSDK
from zkauth.exceptions import AuthenticationError, ValidationError

async def advanced_example():
    # Initialize with custom configuration
    client = ZKAuthSDK(
        api_key="zka_live_your_api_key_here",
        base_url="https://zkauth-engine.vercel.app",  # Optional: defaults to this
        timeout=60.0,  # Request timeout in seconds
        max_retries=5,  # Number of retry attempts
        enable_device_fingerprinting=True  # Enable device security
    )
    
    try:
        # Health check
        if not await client.health_check():
            print("⚠️ ZKAuth service is not available")
            return
        
        # Register user with metadata
        result = await client.sign_up(
            email="advanced@example.com",
            password="SecureP@ssw0rd123",
            metadata={
                "signup_source": "mobile_app",
                "referral_code": "REF123",
                "user_preferences": {
                    "theme": "dark",
                    "notifications": True
                }
            }
        )
        
        if result.success:
            print(f"✅ User registered: {result.user.email}")
            
            # Get user information
            user_info = await client.get_user_info()
            print(f"User ID: {user_info.id}")
            print(f"Created: {user_info.created_at}")
            
            # Get session information
            session_info = await client.get_session_info()
            print(f"Session expires: {session_info.expires_at}")
            
            # Change password
            password_change = await client.change_password(
                current_password="SecureP@ssw0rd123",
                new_password="NewSecureP@ssw0rd456",
                email="advanced@example.com"
            )
            
            if password_change.success:
                print("✅ Password changed successfully")
        
    except ValidationError as e:
        print(f"❌ Validation error: {e}")
    except AuthenticationError as e:
        print(f"❌ Authentication failed: {e}")
    except Exception as e:
        print(f"❌ Unexpected error: {e}")
    finally:
        await client.close()

# Run the example
asyncio.run(advanced_example())

Features

  • Zero-knowledge proof authentication - Real cryptographic ZK proofs using Groth16 protocol
  • Async/await support - Built for modern Python async applications
  • Django and FastAPI integrations - Ready-made middleware and decorators
  • Type hints with Pydantic models - Full type safety and validation
  • Comprehensive error handling - Structured exceptions for all scenarios
  • Session management - Automatic token handling and refresh
  • Device fingerprinting - Hardware-based security with fallbacks
  • Python 3.8+ support - Compatible with modern Python versions
  • Production ready - Retry logic, timeouts, and robust error handling

API Reference

Core Methods

# Authentication
await client.sign_up(email: str, password: str, metadata: Optional[Dict] = None) -> AuthResult
await client.sign_in(email: str, password: str) -> AuthResult
await client.approve_device(approval_code: str) -> AuthResult

# Session management
await client.get_user_info() -> User
await client.get_session_info() -> SessionInfo
await client.verify_token(token: str) -> bool
await client.refresh_token() -> Optional[str]

# Account management
await client.change_password(current_password: str, new_password: str, email: str) -> AuthResult
await client.sign_out() -> None

# Utility
await client.health_check() -> bool
await client.close() -> None  # Always call this or use async context manager

Configuration

client = ZKAuthSDK(
    api_key: str,                           # Required: Your ZKAuth API key
    base_url: str = "https://zkauth-engine.vercel.app",  # Optional: Custom base URL
    timeout: float = 30.0,                  # Optional: Request timeout in seconds
    max_retries: int = 3,                   # Optional: Number of retry attempts
    enable_device_fingerprinting: bool = True  # Optional: Enable device security
)

Error Handling

All methods return structured error responses:

class AuthResult:
    success: bool
    user: Optional[User] = None
    token: Optional[str] = None
    error: Optional[str] = None
    requires_device_verification: bool = False

Exception Types:

  • ZKAuthError - Base exception for all ZKAuth errors
  • ValidationError - Input validation errors (email format, password strength)
  • AuthenticationError - Authentication failures (wrong credentials, expired tokens)
  • NetworkError - Network connectivity issues
  • APIError - Server-side errors with HTTP status codes

Getting Your API Key

  1. Visit the ZKAuth Developer Platform ← Register here!
  2. Sign up for a developer account
  3. Create a new project
  4. Generate your API keys (test and live)
  5. Use the live key (zka_live_...) for production

Note: The ZKAuth engine runs at https://zkauth-engine.vercel.app (used internally by the SDK), but developers register at the Developer Platform link above.

Development

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=zkauth

# Format code
black zkauth/
isort zkauth/

# Type checking
mypy zkauth/

License

MIT

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

zkauth_sdk-1.2.0.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

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

zkauth_sdk-1.2.0-py3-none-any.whl (14.7 kB view details)

Uploaded Python 3

File details

Details for the file zkauth_sdk-1.2.0.tar.gz.

File metadata

  • Download URL: zkauth_sdk-1.2.0.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.7

File hashes

Hashes for zkauth_sdk-1.2.0.tar.gz
Algorithm Hash digest
SHA256 2761caeaa082c7a43144ad9e5659dffc187322b9c9104a73b1683e7289ae5797
MD5 d606290c958683e89a57206474e0c199
BLAKE2b-256 eb4fae5f30161eeb0fe4fd1c766ff97ef784bf9bcbd3959edb12e66b5d7c0779

See more details on using hashes here.

File details

Details for the file zkauth_sdk-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: zkauth_sdk-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 14.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.7

File hashes

Hashes for zkauth_sdk-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4735a8484d6f0b6df1a10300ddfbecdb0e17ff7e44c79c245d536f4289139cd3
MD5 71ba0e39a5616d7ae50619e20d09afc4
BLAKE2b-256 9c6c31e1a4bac3c37284fd9e158c07bd29e63bbd5a7f6c91e91755c8425cbbc3

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