Metadata-Version: 2.4
Name: authforge
Version: 0.1.0
Summary: Production-ready FastAPI authentication & security library
Author-email: AuthForge Maintainers <jpstack15@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Your Name
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/Pihujalan/authentication-system
Project-URL: Documentation, https://github.com/Pihujalan/authentication-system#readme
Project-URL: Repository, https://github.com/Pihujalan/authentication-system
Project-URL: Bug Tracker, https://github.com/Pihujalan/authentication-system/issues
Keywords: auth,authentication,authorization,jwt,rbac,multi-tenant,fastapi
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Framework :: FastAPI
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.109.0
Requires-Dist: sqlalchemy>=2.0.25
Requires-Dist: alembic>=1.13.1
Requires-Dist: python-jose[cryptography]>=3.3.0
Requires-Dist: passlib[bcrypt]>=1.7.4
Requires-Dist: pydantic[email]>=2.5.3
Requires-Dist: pydantic-settings>=2.1.0
Requires-Dist: python-multipart>=0.0.9
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: python-dotenv>=1.0.1
Requires-Dist: pyotp>=2.9.0
Requires-Dist: aiosmtplib>=3.0.1
Requires-Dist: jinja2>=3.1.3
Requires-Dist: asyncpg>=0.29.0
Requires-Dist: aiosqlite>=0.19.0
Requires-Dist: httpx>=0.26.0
Requires-Dist: bcrypt>=4.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: httpx>=0.24.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.5.0; extra == "dev"
Dynamic: license-file

# AuthForge

> Production-grade, multi-tenant authentication and authorization for Python.

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-green.svg)](https://fastapi.tiangolo.com)

---

## Why AuthForge?

Every B2B Python project needs auth. Building it from scratch is:
- Time consuming (weeks of work)
- Easy to get wrong (security mistakes are costly)
- Repetitive (everyone solves the same problems)

AuthForge gives you **enterprise-grade auth in minutes**, not weeks.

```bash
pip install authforge
```

```python
from authforge import Auth

auth = Auth(
    db_url="postgresql+asyncpg://...",
    jwt_secret="your-secret",
    multi_tenant=True,
)

app.include_router(auth.get_router(), prefix="/auth")

@app.get("/leads")
async def get_leads(user=auth.protect("leads:read")):
    return {"tenant": user.tenant_id}
```

That's it. Full auth system running.

---

## Features

- **Multi-tenancy first** — tenant isolation enforced at library level
- **JWT auth** — access + refresh tokens with automatic rotation
- **RBAC** — 6 built-in roles with granular permissions
- **MFA** — TOTP-based (Google Authenticator / Authy)
- **Email Verification** — compulsory verification flow for new users
- **Device Fingerprinting** — identify and manage trusted devices
- **Anomaly Detection** — impossible travel, new device alerts, unusual hour detection
- **Step-Up Auth** — contextual multi-factor re-verification for sensitive actions
- **Invite system** — employees are invited, not self-registered
- **Breach detection** — HaveIBeenPwned check on every password
- **Audit logs** — every action logged automatically with anomaly flags
- **Flexible config** — code, YAML, or environment variables
- **Custom email** — plug in SendGrid, SES, or any provider
- **Hardened Defaults** — CSP/HSTS headers, rate limiting, and encryption-at-rest

---

## 🔒 Security Hardening

AuthForge is built with a **security-first** philosophy. When you use `auth.register_security_middleware(app)`, the following protections are automatically enabled:

- **Encryption-at-Rest**: Sensitive database fields (MFA secrets, user payloads) are encrypted using AES-256 (Fernet).
- **Security Headers**: Automatic injection of `Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, and `X-Content-Type-Options`.
- **Rate Limiting**: Built-in sliding window protection (100 req/min) for all authentication endpoints.
- **Timing Attack Protection**: Constant-time string comparisons for all secrets and tokens.

### Verifying Security
You can verify these features on your local machine by running:
```bash
python examples/verify_security.py
```

---

## Installation

```bash
pip install authforge
```

---

## Quick Start

```python
from fastapi import FastAPI
from authforge import Auth

app  = FastAPI()
auth = Auth(db_url="...", jwt_secret="...")

@app.on_event("startup")
async def startup():
    await auth.init_db()

app.include_router(auth.get_router(), prefix="/auth")
```

---

## Configuration

AuthForge supports three config styles. ENV variables take highest priority.

**Code:**
```python
auth = Auth(db_url="...", jwt_secret="...")
```

**YAML** (`authforge.yaml`):
```yaml
jwt:
  secret: "your-secret"
database:
  url: "postgresql+asyncpg://..."
```

**Environment variables:**
```bash
AUTHFORGE_JWT_SECRET=your-secret
AUTHFORGE_DB_URL=postgresql+asyncpg://...
```

---

## Documentation

Full docs at [authforge.readthedocs.io](https://authforge.readthedocs.io/)

---

### Administrative API
AuthForge provides built-in management endpoints for tenant and user administration (enforced via RBAC):

- `GET /auth/admin/users` — List all users in the current tenant.
- `PATCH /auth/admin/users/{id}/role` — Promote/demote users (respects hierarchy).
- `PATCH /auth/admin/tenants/{id}/status` — Superadmin control for suspending/activating tenants.

### Security Configuration & Deep Dive

AuthForge provides several production-grade security layers. Here is a quick breakdown of **What** they are, **Why** they are used, and if they can be **Customized**:

#### 🕵️ 1. [Anomaly Detection (Risk Scoring)](https://authforge.readthedocs.io/en/latest/security/#anomaly-detection)
*   **What**: Monitors login behavior (IP, Country, Time) and assigns a 0-100 risk score.
*   **Why**: Stops attackers from using stolen credentials if their behavior looks "weird."
*   **Customization**: Enable/Disable via `security.anomaly_detection_enabled`. Custom rules can be injected via the `Auth` constructor.

#### 🔐 2. [Step-Up Authentication](https://authforge.readthedocs.io/en/latest/security/#step-up-authentication)
*   **What**: Forces re-authentication before sensitive actions (e.g., deleting data).
*   **Why**: Prevents "Unlocked Laptop" attacks where an active session is left unattended.
*   **Customization**: Use the `@auth.step_up_required(valid_window_minutes=15)` decorator to set your own security windows.

#### 🔨 3. [Brute-Force Protection](https://authforge.readthedocs.io/en/latest/security/#brute-force-protection)
*   **What**: Automatically locks accounts or destroys tokens after multiple failed attempts.
*   **Why**: Stops automated bots from guessing your users' passwords or recovery links.
*   **Customization**: Change limits via `security.max_login_attempts` (Default: 5).

#### 💻 4. [Device Fingerprinting](https://authforge.readthedocs.io/en/latest/security/#device-fingerprinting)
*   **What**: Identifies a browser and hardware configuration beyond just cookies.
*   **Why**: Backbone of identity trust; allows users to "Trust" their primary devices.
*   **Customization**: Complete audit logs available in `device_fingerprints` database table.

## License
MIT
 © AuthForge Maintainers
