Metadata-Version: 2.4
Name: accesshub-sdk
Version: 0.1.0
Summary: Production-ready asynchronous Python SDK for AccessHub access control system and enterprise external integrations.
Author-email: Tulio Amancio <root@tsuriu.com.br>
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/libandpackages/accesshub-sdk
Project-URL: Source, https://gitlab.com/libandpackages/accesshub-sdk
Keywords: accesshub,access-control,security,iot,biometrics,async,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
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: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: respx>=0.21.0; extra == "dev"
Dynamic: license-file

# AccessHub Python SDK (`accesshub-sdk`)

[![Python Version](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

An official, production-ready, asynchronous Python SDK for **AccessHub** access control software and enterprise external integrations.

---

## Features

- **Asynchronous & Fast**: Powered by `httpx` and `asyncio` for non-blocking I/O.
- **Strict Data Validation**: Fully typed models built with **Pydantic v2**.
- **Webhook Receiver & Signature Verification**: Built-in HMAC SHA-256 signature verification and event routing (`WebhookReceiver`).
- **Domain Service Namespaces**:
  - `client.auth`: User authentication, token management, profile context.
  - `client.tenants`: Tenant creation, list, and updates.
  - `client.members`: Access member management (users, visitors, employees) and credential attachments (RFID, PIN, Face).
  - `client.groups`: Access groups and door assignment rules.
  - `client.devices`: Hardware device management, remote door opening (`unlock_door`), telemetry retrieval.
  - `client.access`: Manual access evaluation and custom access log entry.
  - `client.events`: Querying real-time access events with pagination and filters.
- **Typed Error Hierarchy**: Clear, actionable exceptions (`AuthenticationError`, `NotFoundError`, `ForbiddenError`, `ValidationError`, `APIError`, `WebhookSignatureError`).

---

## Installation

```bash
pip install accesshub-sdk
```

Or install locally in editable mode:

```bash
cd SDKs/accesshub-python-sdk
pip install -e .
```

---

## Quickstart

### 1. Basic Client Initialization & Login

```python
import asyncio
from accesshub import AccessHubClient

async def main():
    async with AccessHubClient(base_url="http://localhost:8000") as client:
        # Authenticate and set Bearer token automatically
        token = await client.login(username="admin", password="secure_password")
        print(f"Logged in token: {token[:15]}...")

        # Get current user profile
        user = await client.auth.get_me()
        print(f"User: {user.username} (Role: {user.role})")

if __name__ == "__main__":
    asyncio.run(main())
```

---

### 2. Receiving & Handling Webhooks

AccessHub can dispatch real-time HTTP POST webhooks for events like `member.created`, `access.granted`, or `access.denied`. The SDK provides a `WebhookReceiver` to handle HMAC SHA-256 verification and route events:

```python
import asyncio
from accesshub import WebhookReceiver, WebhookEvent

# Initialize receiver with shared secret
receiver = WebhookReceiver(secret="my-tenant-webhook-secret")

@receiver.on("access.granted")
async def handle_access_granted(event: WebhookEvent):
    print(f"Access granted for member: {event.data.get('member_name')}")

@receiver.on("member.created")
async def handle_member_created(event: WebhookEvent):
    print(f"New member registered: {event.data.get('name')}")

# Process incoming raw HTTP body and headers (e.g., inside FastAPI, Flask, or Aiohttp endpoint)
# event = await receiver.process(raw_body=raw_bytes, headers=request_headers)
```

#### FastAPI Integration Example:

```python
from fastapi import FastAPI, Request
from accesshub import WebhookReceiver

app = FastAPI()
receiver = WebhookReceiver(secret="my-tenant-webhook-secret")

@receiver.on("access.granted")
async def on_access(event):
    print("Door opened:", event.data)

@app.post("/webhook")
async def webhook_endpoint(request: Request):
    raw_body = await request.body()
    headers = dict(request.headers)
    event = await receiver.process(raw_body=raw_body, headers=headers)
    return {"status": "success", "event": event.event}
```

---

### 3. Remote Door Control & Telemetry

```python
import asyncio
from accesshub import AccessHubClient

async def main():
    async with AccessHubClient(base_url="http://localhost:8000", token="YOUR_JWT_TOKEN") as client:
        devices = await client.devices.list()
        
        if devices:
            target = devices[0]
            print(f"Unlocking door on device '{target.name}'...")
            
            # Send 3-second pulse door unlock command
            result = await client.devices.unlock_door(
                device_id=target.id,
                door_index=0,
                pulse_ms=3000
            )
            print(f"Unlock command status: {result}")

if __name__ == "__main__":
    asyncio.run(main())
```

---

## Error Handling

All SDK exceptions inherit from `AccessHubError`:

```python
from accesshub import (
    AccessHubClient,
    AuthenticationError,
    NotFoundError,
    ValidationError,
    WebhookSignatureError,
)

async with AccessHubClient(base_url="http://localhost:8000") as client:
    try:
        member = await client.members.get("non-existent-id")
    except NotFoundError as err:
        print(f"Resource not found (404): {err.message}")
    except AuthenticationError:
        print("Invalid token or credentials.")
    except WebhookSignatureError:
        print("Invalid webhook signature header.")
```

---

## Development & Testing

Run unit & integration tests using `pytest`:

```bash
cd SDKs/accesshub-python-sdk
pytest
```

---

## License

[MIT License](LICENSE) - Copyright (c) 2026 AccessHub / Tsuriu Tech.
