Metadata-Version: 2.4
Name: fastn-auth
Version: 1.0.0
Summary: Python SDK for Fastn connector authentication
Author: Fastn
License-Expression: MIT
Project-URL: Homepage, https://github.com/fastn-ai/fastn-auth
Project-URL: Documentation, https://github.com/fastn-ai/fastn-auth#readme
Keywords: fastn,auth,oauth,connector,authentication
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: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: aiohttp>=3.8.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"

# fastn-auth (Python)

Python SDK for Fastn connector authentication. Provides a simple async interface for initiating OAuth and credential-based connector authentication flows.

## Installation

```bash
pip install fastn-auth
```

## Quick Start

```python
import asyncio
from fastn_auth import FastnAuth

async def main():
    # Create a client
    client = FastnAuth(
        space_id="your-space-id",
        api_key="your-api-key",
        base_url="https://live.fastn.ai/api",  # optional
    )

    # Initialize an authentication session
    session = await client.initialize(
        connector_id="google-sheets",
        org_id="org-id",      # optional
        tenant_id="tenant-id" # optional
    )

    # Redirect the user to complete OAuth
    print(f"Redirect user to: {session.redirect_url}")

    # Wait for the user to complete authentication
    result = await session.wait_for_completion()

    print("Authentication complete!", result.credentials)

asyncio.run(main())
```

## API Reference

### FastnAuth

The main client class for initializing authentication flows.

#### Constructor

```python
FastnAuth(
    space_id: str,
    api_key: str,
    base_url: str | None = None,
)
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `space_id` | `str` | Yes | The space/workspace ID |
| `api_key` | `str` | Yes | API key for authentication |
| `base_url` | `str` | No | Base URL for the Fastn API (defaults to `https://live.fastn.ai/api`) |

#### Methods

##### `async initialize(...) -> AuthSession`

Initialize a connector authentication flow.

```python
async def initialize(
    self,
    connector_id: str,
    org_id: str | None = None,
    tenant_id: str | None = None,
    connection_id: str | None = None,
) -> AuthSession
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `connector_id` | `str` | Yes | The connector ID (e.g., "google-sheets", "salesforce") |
| `org_id` | `str` | No | Organization ID |
| `tenant_id` | `str` | No | Tenant ID |
| `connection_id` | `str` | No | Connection instance ID (defaults to "default") |

### AuthSession

Represents an active authentication session.

#### Properties

| Property | Type | Description |
|----------|------|-------------|
| `id` | `str` | Unique identifier for this session |
| `state_key` | `str` | State key for the OAuth flow |
| `redirect_url` | `str` | URL to redirect the user to for OAuth authorization |

#### Methods

##### `async wait_for_completion(options: PollOptions | None = None) -> AuthResult`

Poll for the authentication status and wait for completion.

```python
@dataclass
class PollOptions:
    interval: float = 2.0   # Polling interval in seconds
    timeout: float = 300.0  # Maximum wait time in seconds (5 minutes)
```

Returns an `AuthResult` object:

```python
@dataclass
class AuthResult:
    status: AuthStatus
    credentials: Credentials | None = None
    error_message: str | None = None
```

##### `async get_status() -> StatusResponse`

Get the current status of the authentication session.

### Error Handling

The SDK provides custom exception classes for different failure scenarios:

```python
from fastn_auth import (
    FastnAuthError,
    TimeoutError,
    AuthenticationError,
    NetworkError,
    InvalidResponseError,
)

try:
    result = await session.wait_for_completion()
except TimeoutError:
    print("Authentication timed out")
except AuthenticationError as e:
    print(f"Authentication failed: {e.message}")
except NetworkError as e:
    print(f"Network error: {e.message}, status: {e.status_code}")
```

## Status Lifecycle

| Status | Description |
|--------|-------------|
| `INACTIVE` | OAuth initiated, awaiting user authorization |
| `ACTIVE` | Connector successfully activated |
| `FAILED` | Activation failed |

## Requirements

- Python 3.9 or higher
- aiohttp >= 3.8.0

## License

MIT
