Metadata-Version: 2.5
Name: olauth
Version: 1.1.0
Summary: The zero-config, one-liner authentication engine for Python web frameworks.
Author-email: Jakub Drábik <drabik@felicitous.dev>
License-File: LICENSE
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.10
Requires-Dist: bcrypt>=4.0.0
Provides-Extra: dev
Requires-Dist: fastapi>=0.100.0; extra == 'dev'
Requires-Dist: flask>=2.0.0; extra == 'dev'
Requires-Dist: httpx>=0.24.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=2.0.0; extra == 'flask'
Provides-Extra: mysql
Requires-Dist: pymysql>=1.1.0; extra == 'mysql'
Provides-Extra: postgres
Requires-Dist: psycopg2-binary>=2.9.0; extra == 'postgres'
Description-Content-Type: text/markdown

# OL-Auth (v1.1.0)

OL-Auth (short for **One-Line Auth**) is a lightweight, zero-configuration authentication engine for Python web applications. With a single line of code, it provisions your user & session tables, handles password hashing and persistent cookie sessions, protects routes, and serves responsive light/dark **Sign up**, **Log in**, and **Password Reset** pages.

---

## ✨ Features

- **Zero-config local dev, easy cloud scaling:** Defaults to SQLite (WAL mode), and switches to **PostgreSQL** or **MySQL** via a standard connection string (`db=` or `OLAUTH_DATABASE_URL`) with automatic reconnect-on-drop.
- **Flask & FastAPI out of the box:** Auto-detects the framework and mounts `/signup`, `/login`, `/logout`, `/verify`, `/forgot-password`, and `/reset-password`.
- **One-line route protection:** Use `@olauth.login_required` in Flask or `Depends(olauth.login_required)` in FastAPI, and read `olauth.current_user()` anywhere.
- **Production-minded security defaults:**
  - `bcrypt` password hashing (12 rounds, safe handling for >72-byte passwords) and constant-time login checks.
  - Persistent opaque session tokens stored as **SHA-256 digests** in `olauth_sessions`.
  - `HttpOnly`, `SameSite=Lax` cookies (with automatic `Secure` flag over HTTPS).
  - CSRF same-origin `POST` checks (`Origin` / `Sec-Fetch-Site`), open-redirect validation on `?next=`, XSS-escaped templates, and per-IP sliding-window rate limiting.

---

## 📦 Installation

Install directly from PyPI:

```bash
# Core package
pip install olauth

# With web framework extras
pip install "olauth[flask]"
pip install "olauth[fastapi]"

# Optional database drivers for cloud hosting
pip install "olauth[postgres]"
pip install "olauth[mysql]"

# Combine extras as needed (e.g. FastAPI + PostgreSQL)
pip install "olauth[fastapi,postgres]"
```

---

## 💻 Quickstart

### Flask

```python
from flask import Flask
import olauth

app = Flask(__name__)
olauth.init(app)  # Creates olauth.db and mounts /signup, /login, /logout

@app.route("/")
def home():
    user = olauth.current_user()
    if user:
        return f"Welcome back, {user['email']}! <a href='/logout'>Log out</a>"
    return "Hello guest! <a href='/login'>Log in</a>"

@app.route("/dashboard")
@olauth.login_required
def dashboard():
    user = olauth.current_user()
    return f"Protected dashboard for user #{user['id']} ({user['email']})"

if __name__ == "__main__":
    app.run(debug=True)
```

In Flask Jinja templates, `current_user` is also automatically injected into the template context.

### FastAPI

```python
from fastapi import Depends, FastAPI
import olauth

app = FastAPI()
olauth.init(app)

@app.get("/")
def home(user: dict | None = Depends(olauth.current_user)):
    return {"user": user}

@app.get("/dashboard")
def dashboard(user: dict = Depends(olauth.login_required)):
    return {"message": f"Hello {user['email']}", "user_id": user["id"]}
```

- Browser requests (`Accept: text/html`) to protected FastAPI routes redirect (`303`) to `/login?next=...`.
- API/JSON clients receive `401 Unauthorized`.

---

## 🗄️ Databases (SQLite, PostgreSQL, MySQL)

Pass a connection URL to `olauth.init(app, db=...)` or set the `OLAUTH_DATABASE_URL` environment variable:

```python
import os
import olauth

# 1. Zero-config SQLite (default: olauth.db)
olauth.init(app)

# 2. Custom SQLite path
olauth.init(app, db="sqlite:///data/app.db")

# 3. PostgreSQL (requires `pip install "olauth[postgres]"`)
olauth.init(app, db=os.getenv("DATABASE_URL"))  # e.g. postgresql://user:pass@host:5432/db

# 4. MySQL (requires `pip install "olauth[mysql]"`)
olauth.init(app, db="mysql://user:pass@host:3306/db")
```

---

## ✉️ Email Verification (Opt-In 6-Digit Code)

Email verification is **off by default** so hackathons and prototypes stay instant. When you want to verify emails, use the built-in zero-dependency SMTP sender, console mode, or a custom callback:

```python
# 1. Built-in SMTP sender (defaults to Gmail SSL on port 465; or set OLAUTH_SMTP_USER / OLAUTH_SMTP_PASSWORD)
olauth.init(
    app,
    smtp_user="myapp@gmail.com",
    smtp_password="xxxx-xxxx-xxxx-xxxx",  # App Password
)

# 2. Local dev mode: prints the 6-digit code in your terminal with zero credentials
olauth.init(app, verify_email="console")

# 3. Custom sender (Resend, SendGrid, Postmark, etc.)
olauth.init(
    app,
    send_verification_code=lambda email, code: send_my_email(
        to=email,
        subject="Your verification code",
        text=f"Your verification code is: {code}",
    ),
)
```

When enabled:
- `/signup` creates the account unverified, hashes and stores a single-use 6-digit code, sends it, and redirects to `/verify`.
- Unverified users trying to `/login` are sent a fresh code and redirected to `/verify` (`403` for JSON requests).
- Submitting the code on `/verify` activates the account and logs the user in.

---

## 🔑 Password Reset Flow

`olauth` includes a built-in 6-digit password reset flow on `/forgot-password` and `/reset-password` (linked directly from `/login`):

- `GET/POST /forgot-password`: Accepts an `email`, generates a single-use 6-digit code if the account exists (without revealing whether the email is registered), sends it via `send_verification_code` / SMTP (or prints to the terminal if no email sender is configured), and redirects to `/reset-password`.
- `GET/POST /reset-password`: Accepts `email`, `code`, and `password`, enforces `min_password_length`, updates `password_hash`, consumes the code, revokes all existing sessions for that user, and logs the user in (when `auto_login_on_signup=True`).

---

## 🎨 Custom Templates

By default, `olauth` serves its built-in light/dark pages with zero configuration. When you want your own HTML pages instead, pass a `template_dir` directory, individual template file overrides, or both:

```python
# Option 1: Drop any of login.html, signup.html, verify.html,
# forgot_password.html (or forgot.html), reset_password.html (or reset.html)
# into a folder — missing files fall back to built-in pages.
olauth.init(app, template_dir="templates/auth")

# Option 2: Override specific pages individually
olauth.init(
    app,
    login_template="templates/my_login.html",
    signup_template="templates/my_signup.html",
)
```

Custom templates are rendered with Jinja2 when installed (or safe HTML-escaped `{key}` / `{{ key }}` substitution otherwise) and receive these context variables:
`error`, `email_value`, `next_param`, `switch_url`, `login_url`, `signup_url`, `logout_url`, `verify_url`, `forgot_password_url`, `reset_password_url`, `title`, `heading`, `button_text`, `switch_prompt`, and `switch_action`.

---

## ⚙️ Configuration Options

All options have safe defaults and can be customized in `olauth.init(...)`:

| Parameter | Default | Description |
| :--- | :--- | :--- |
| `db` | `None` (`olauth.db`) | SQLite path/URI, `postgresql://...`, or `mysql://...` (falls back to `OLAUTH_DATABASE_URL`). |
| `redirect_to` | `"/"` | Default destination after successful login/signup when `?next=` is absent. |
| `login_url` | `"/login"` | Route for login and destination when unauthenticated browser requests are redirected. |
| `verify_url` | `"/verify"` | Route for entering the 6-digit email verification code. |
| `forgot_password_url` | `"/forgot-password"` | Route for requesting a 6-digit password reset code. |
| `reset_password_url` | `"/reset-password"` | Route for entering the 6-digit reset code and choosing a new password. |
| `cookie_name` | `"olauth_session"` | Name of the `HttpOnly` session cookie. |
| `session_ttl` | `604800` (7 days) | Session lifetime in seconds. |
| `verification_ttl` | `900` (15 min) | Email verification and password reset code lifetime in seconds. |
| `cookie_secure` | `None` (auto) | Force `Secure` cookie flag (`True`/`False`), or auto-detect from HTTPS / `X-Forwarded-Proto`. |
| `auto_login_on_signup` | `True` | Immediately issue a session cookie upon account creation, verification, or password reset. |
| `min_password_length` | `8` | Minimum password length enforced on `/signup` and `/reset-password`. |
| `rate_limit` | `15` | Failed auth attempts per client IP allowed per 60-second sliding window (`0` disables). |
| `verify_email` | `False` | Set to `"console"` for terminal verification codes during local dev. |
| `smtp_user` | `None` | SMTP username/sender address (falls back to `OLAUTH_SMTP_USER`). |
| `smtp_password` | `None` | SMTP password/app password (falls back to `OLAUTH_SMTP_PASSWORD`). |
| `smtp_host` | `"smtp.gmail.com"` | SMTP server hostname for built-in email delivery. |
| `smtp_port` | `465` | SMTP port (`465` uses SSL; other ports use STARTTLS). |
| `send_verification_code` | `None` | Optional custom callback `(email, code) -> None` overriding the built-in sender. |
| `template_dir` | `None` | Directory searched for `login.html`, `signup.html`, `verify.html`, `forgot_password.html`, `reset_password.html`. |
| `login_template` | `None` | Path to a custom HTML template file overriding `/login`. |
| `signup_template` | `None` | Path to a custom HTML template file overriding `/signup`. |
| `verify_template` | `None` | Path to a custom HTML template file overriding `/verify`. |
| `forgot_password_template` | `None` | Path to a custom HTML template file overriding `/forgot-password`. |
| `reset_password_template` | `None` | Path to a custom HTML template file overriding `/reset-password`. |

---

## 🧪 Running Tests

```bash
pip install -e ".[dev]"
pytest
```

---

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
