Metadata-Version: 2.4
Name: vanty-auth
Version: 0.3.1
Summary: Vanty App: identity, sessions, MFA, organizations, RBAC, social, API keys.
Project-URL: Homepage, https://github.com/advantch/vanty-auth
Project-URL: Repository, https://github.com/advantch/vanty-auth
Project-URL: Issues, https://github.com/advantch/vanty-auth/issues
License-Expression: MIT
License-File: LICENSE
Keywords: authentication,authorization,fastapi,mfa,oauth
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.12
Requires-Dist: asgiref>=3.9.1
Requires-Dist: asyncpg>=0.31.0
Requires-Dist: cryptography>=46.0.5
Requires-Dist: email-validator>=2.3.0
Requires-Dist: fastapi>=0.135.1
Requires-Dist: httpx>=0.28.1
Requires-Dist: itsdangerous>=2.2.0
Requires-Dist: pwdlib[argon2]>=0.3.0
Requires-Dist: pydantic-settings>=2.13.1
Requires-Dist: pyjwt>=2.12.1
Requires-Dist: pyotp>=2.9.0
Requires-Dist: python-dotenv>=1.0.1
Requires-Dist: taskiq>=0.11
Requires-Dist: tortoise-orm>=1.1.6
Requires-Dist: vanty-core>=0.3.0
Description-Content-Type: text/markdown

# Vanty Auth

[![Tests](https://github.com/advantch/vanty-auth/actions/workflows/tests.yml/badge.svg)](https://github.com/advantch/vanty-auth/actions/workflows/tests.yml)
[![PyPI](https://img.shields.io/pypi/v/vanty-auth)](https://pypi.org/project/vanty-auth/)
[![Python](https://img.shields.io/pypi/pyversions/vanty-auth)](https://pypi.org/project/vanty-auth/)

Drop-in authentication toolkit for FastAPI with Tortoise ORM. Sessions, MFA, organizations, API keys, social login, and admin management in a single `pip install`.

## Installation

```bash
pip install vanty-auth
# or
uv pip install vanty-auth
```

## Quick start

```python
from contextlib import asynccontextmanager

from fastapi import FastAPI

from vanty_auth import AuthSettings, mount_auth_router

settings = AuthSettings(
    database_url="sqlite://./vanty-auth.db",
    secret_key="change-me",
)

app = FastAPI()
kit = mount_auth_router(app, settings=settings)


@asynccontextmanager
async def lifespan(_: FastAPI):
    await kit.init_orm(generate_schemas=True)
    try:
        yield
    finally:
        await kit.close_orm()


app.router.lifespan_context = lifespan
```

Run with `uvicorn main:app --reload` and visit `/docs` for the interactive API explorer.

## Features

- **Email/password authentication** with argon2 hashing, email verification, and password reset
- **Session management** with JWT access tokens, refresh tokens, and secure cookie sessions
- **Multi-factor authentication** via TOTP with recovery codes
- **Organizations** with invitations, member roles, ownership transfer, and multi-tenancy
- **API key authentication** with scoped permissions
- **Social login** via OAuth2 providers (Google, GitHub, extensible)
- **RBAC** with custom roles and permissions
- **Admin management** endpoints for super-admin operations
- **Security monitoring** with login attempt tracking and IP blocking
- **Provider administration** for managing auth methods per-organization

## Architecture

`AuthApp` is a composition root that wires all services. Access services directly:

```python
kit = mount_auth_router(app, settings=settings)

# Direct service access
await kit.auth_service.signup(request, email=email, password=password)
await kit.organization_service.create_organization(name="Acme", owner_id=user_id)
await kit.mfa_service.enable_totp(user_id=user_id)
await kit.api_key_service.create_key(user_id=user_id, name="ci-token")
```

Available services on `AuthApp`:

| Service | Purpose |
|---|---|
| `auth_service` | Signup, login, password reset, email verification |
| `session_service` | Token refresh, session listing, revocation |
| `mfa_service` | TOTP enrollment, verification, recovery codes |
| `organization_service` | Org CRUD, members, invitations, ownership |
| `api_key_service` | API key creation, revocation, listing |
| `social_service` | OAuth2 flow initiation, callback, account linking |
| `security_service` | Login attempt tracking, IP blocking |
| `provider_admin_service` | Auth provider management per organization |
| `admin_service` | Super-admin user and org management |

## Configuration

All settings are read from environment variables with the `AUTH_` prefix, or passed directly to `AuthSettings`.

| Setting | Default | Description |
|---|---|---|
| `database_url` | `sqlite://./vanty-auth.db` | Tortoise ORM database URL |
| `secret_key` | `change-me` | Secret for JWT signing and encryption |
| `base_url` | `http://localhost:8000` | Public base URL for callbacks |
| `access_token_ttl_seconds` | `900` | JWT access token lifetime |
| `refresh_token_ttl_seconds` | `604800` | Refresh token lifetime (7 days) |
| `session_ttl_seconds` | `604800` | Session cookie lifetime (7 days) |
| `auth_backends` | `["bearer", "api_key", "session"]` | Enabled authentication backends |
| `provider_apps` | `{}` | Social provider credentials |
| `allow_org_creation` | `true` | Whether users can create organizations |
| `max_login_attempts_before_block` | `10` | Failed logins before IP block |

Set via environment: `AUTH_KIT_SECRET_KEY=my-secret AUTH_KIT_DATABASE_URL=postgres://...`

## API surface

### Public routes (`/auth`)

| Method | Path | Description |
|---|---|---|
| `POST` | `/signup` | Register a new account |
| `POST` | `/login` | Authenticate with email/password |
| `POST` | `/logout` | End the current session |
| `POST` | `/refresh` | Refresh access token |
| `POST` | `/forgot-password` | Request password reset email |
| `POST` | `/reset-password` | Complete password reset |
| `GET` | `/verify-email` | Verify email address |
| `GET` | `/me` | Get current user profile |
| `PATCH` | `/me` | Update profile |
| `DELETE` | `/me` | Delete account |
| `GET` | `/sessions` | List active sessions |
| `DELETE` | `/sessions/{id}` | Revoke a session |
| `POST` | `/mfa/totp/setup` | Begin TOTP enrollment |
| `POST` | `/mfa/totp/verify` | Complete TOTP enrollment |
| `POST` | `/mfa/totp/validate` | Validate TOTP during login |
| `POST` | `/mfa/disable` | Disable MFA |
| `GET` | `/mfa/recovery-codes` | Get recovery codes |
| `POST` | `/organizations` | Create organization |
| `GET` | `/organizations/{id}` | Get organization details |
| `PATCH` | `/organizations/{id}` | Update organization |
| `DELETE` | `/organizations/{id}` | Delete organization |
| `GET` | `/organizations/{id}/members` | List members |
| `POST` | `/organizations/{id}/invite` | Invite member |
| `POST` | `/invitations/{id}/accept` | Accept invitation |
| `POST` | `/invitations/{id}/decline` | Decline invitation |
| `DELETE` | `/invitations/{id}` | Revoke invitation |
| `PATCH` | `/organizations/{id}/members/{uid}/role` | Update member role |
| `DELETE` | `/organizations/{id}/members/{uid}` | Remove member |
| `POST` | `/api-keys` | Create API key |
| `GET` | `/api-keys` | List API keys |
| `DELETE` | `/api-keys/{id}` | Revoke API key |
| `GET` | `/social/{provider}/start` | Begin OAuth2 flow |
| `GET` | `/social/{provider}/callback` | OAuth2 callback |
| `GET` | `/providers` | List enabled auth providers |

### Admin routes (`/admin/auth`)

Super-admin endpoints for platform-wide management. Mount separately:

```python
app.include_router(kit.admin_router, prefix="/admin/auth")
```

## Project layout

```text
src/vanty_auth/         Package source
docs/                   Documentation
examples/reference-api/ Reference FastAPI application
examples/reference-web/ Reference frontend (React + Orval)
tests/                  pytest suite (unit + integration)
```

## Development

```bash
git clone https://github.com/advantch/vanty-auth.git
cd vanty-auth
uv sync --dev

# Lint
uv run ruff check

# Test
uv run pytest -q

# Run reference API
cd examples/reference-api && uv run uvicorn main:app --reload

# Run reference frontend
cd examples/reference-web && pnpm install && pnpm run dev
```

Use `uv run pytest --no-cov tests/path/to/test.py` for targeted debugging without the coverage gate.

### Regenerating the frontend client

```bash
cd examples/reference-web
pnpm run generate:api
```

This refreshes the OpenAPI spec from the reference API and re-runs Orval.

## Extending providers

New OAuth providers go under `src/vanty_auth/social/providers/`. Register the provider in the default registry and supply credentials through `AuthSettings.provider_apps` or the `ProviderApp` database table.

## Releasing

Tags trigger the release workflow. The GitHub Actions pipeline builds, creates a GitHub release, and publishes to PyPI automatically.

```bash
git tag v0.2.0
git push origin v0.2.0
```

## License

MIT
