Metadata-Version: 2.4
Name: fastpluggy-auth-user
Version: 0.6.19
Summary: User Authentication plugin for Fastpluggy
Author: FastPluggy Team
License-Expression: MIT
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: FastPluggy<1,>=0.4.98
Requires-Dist: authlib
Requires-Dist: bcrypt
Requires-Dist: httpx
Requires-Dist: click
Requires-Dist: passlib
Requires-Dist: pyotp
Requires-Dist: python-multipart
Requires-Dist: qrcode[svg]
Provides-Extra: tests
Requires-Dist: pytest>=7.0; extra == "tests"
Requires-Dist: pytest-cov>=4.0; extra == "tests"
Requires-Dist: pytest-asyncio>=0.21; extra == "tests"
Provides-Extra: e2e
Requires-Dist: fastpluggy-cli; extra == "e2e"
Requires-Dist: uvicorn[standard]; extra == "e2e"
Dynamic: license-file

# Auth User Plugin

![Auth User](https://img.shields.io/badge/FastPluggy-Auth%20User-blue)
[![Release](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/auth_user/-/badges/release.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/auth_user/-/releases)
[![Pipeline Status](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/auth_user/badges/main/pipeline.svg?key_text=CI)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/auth_user/-/pipelines?ignore_skipped=true)
[![Coverage](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/auth_user/badges/main/coverage.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/auth_user/-/pipelines)

The Auth User plugin provides comprehensive user authentication and management functionality for FastPluggy applications.

## 📊 Current Status

**✅ PRODUCTION READY:**
- Session-cookie login/logout with "remember me", `?next=` redirect preservation, and rate limiting + account lockout
- TOTP two-factor authentication (QR setup, backup codes, admin override)
- Personal access tokens (Bearer + pip/twine HTTP Basic)
- Self-service **and** admin-initiated password reset (mail-agnostic, event-driven)
- Self-service + admin-wide session management (device/IP/last-seen, revoke)
- Admin user CRUD, auth-settings and security (login-attempts / lockouts) UIs
- Pluggable auth backends: **session**, **basic**, **proxy** (forward-auth SSO), **oidc** (OpenID Connect client)
- Composable route mounting and a configurable/overridable login (custom user model, login-by-email, own hash scheme)
- EventBus integration — login, logout, password change, 2FA, lockout, SSO provisioning, password-reset events

**📋 ROADMAP:** See [Implementation Roadmap](docs/roadmap.md) for the development history and future plans.

## Features

- **User Authentication**: Secure username/password authentication with BCrypt hashing
- **Auth backends**: Session (cookies + Bearer tokens + HTTP Basic), Basic-only, Proxy (forward-auth SSO), and OIDC (OpenID Connect client) — see [Auth backends](#auth-backends)
- **Two-Factor Authentication**: Optional TOTP (authenticator app) with QR-code setup, SHA-256-hashed backup codes, per-session attempt limiting, and admin override. The authenticator app lists the account under core's `app_name` setting, which also titles the sign-in and password-reset pages
- **Brute-force protection**: Per-user and per-IP login rate limiting plus account lockout after repeated failures, with an admin login-attempts / lockouts UI
- **Password Reset**: Optional self-service "forgot my password" flow — the plugin mints single-use, expiring tokens and emits an event; a host listener delivers the link (no mail dependency in the plugin). The same token machinery is reachable for **admin-initiated** resets via the `authentication` capability (see [Password reset](#password-reset))
- **Personal Access Tokens**: Long-lived API tokens for CI/CD, pip and twine (Bearer + HTTP Basic `__token__`)
- **Admin Interface**: Complete user management with list, add, edit, delete, plus auth-settings and security UIs
- **Session Management**: Configurable session handling; self-service and admin-wide session listing with device/IP/last-seen and revoke
- **Composable mounting**: Turn any route group off (`enable_*`) so a host app can own its own `/login`, `/register`, etc. without route shadowing
- **User Profiles**: Protected profile pages for authenticated users
- **Menu Integration**: Automatic menu items for profile and logout
- **EventBus Integration**: Emits login, logout, password-change, TOTP, lockout, SSO-provisioning and password-reset events for host listeners
- **Database Integration**: SQLAlchemy models with FastPluggy core

## Models

### FastPluggyBaseUser
The main user model with the following fields:
- `username`: Unique username (String, 255 chars)
- `hashed_password`: Securely hashed password (String, 255 chars)
- `is_admin`: Boolean flag indicating admin privileges (default: False)
- `last_login_source`: Door of the last sign-in, `password` (local login form), `oidc` or `proxy` (nullable: unknown for older rows). The proxy backend creates no `Session` row, so this is where its users show how they came in. Shown in the admin user list.

### Session
Session management model for user authentication:
- `session_id`: Unique session identifier (String, 255 chars)
- `session_data`: JSON data stored in the session
- `session_lifetime`: Session expiration timestamp
- `session_time`: Session creation timestamp
- `ip`: Client IP captured at login (nullable; only set when `collect_login_ip` is enabled)
- `user_agent`: Raw User-Agent captured at login (nullable)
- `last_seen_at`: Last activity timestamp, refreshed (throttled) on authenticated requests (nullable)
- `auth_source`: Door the session was signed in with, `password` or `oidc` (nullable: unknown for older rows). Shown as "Signed in with" on `/profile/sessions/` and `/admin/users/sessions/`.

### Token (`api_tokens`)
Personal access tokens — see [Personal Access Tokens](#personal-access-tokens). Stores `name`, `token_hash` (SHA-256), optional `expires_at`, `last_used_at`.

### TwoFactorSecret (`totp_secrets`)
Per-user TOTP secret + SHA-256-hashed backup codes, created only when `enable_totp` is on.

### PasswordResetToken (`password_reset_tokens`)
Single-use, expiring password-reset tokens — SHA-256-hashed (raw value never stored), with `user_id`, `expires_at`, `used_at`. Created only when `enable_password_reset` is on. See [Password reset](#password-reset).

### LoginAttempt (`login_attempts`) & AccountLockout (`account_lockouts`)
Back the login rate-limiting and account-lockout machinery — **always created** regardless of which routes are mounted. Surfaced in the admin security UI (`/admin/security/attempts`, `/admin/security/lockouts`). Each attempt carries `auth_source` (`password` for the login form, `oidc` for an OIDC callback, including an identity that failed to map), shown in the "Via" column.

API tokens and HTTP Basic authenticate each request on its own: they write no session, attempt or last sign-in, so they never appear as a source.

## Session management

Both authenticated users and admins can review and revoke sessions:

- **Self-service** — `GET /profile/sessions/` lists the current user's active
  sessions with device (heuristic User-Agent parse), IP, relative last-seen,
  created/expires. Revoke a single session or "revoke all other sessions".
  The IP column is **hidden entirely** when `collect_login_ip` is disabled.
- **Admin-wide** — `GET /admin/users/sessions/` (requires the `fp_admin` role)
  lists every active session across all users with a username filter, and can
  revoke any individual session or all of a given user's sessions.

`last_seen_at` is refreshed inside the authentication path but **throttled** to
at most one write per `session_last_seen_throttle` seconds, and is wrapped so a
tracking failure can never break authentication. Set `session_track_metadata`
to `false` to disable User-Agent capture and last-seen tracking entirely.

## Configuration

The plugin uses `AuthUserConfig` class with the following settings:

```python
from fastpluggy.core.config import BaseDatabaseSettings
from typing import Optional, Literal

class AuthUserConfig(BaseDatabaseSettings):
    # Set to None to enable UI-based setup on first install
    # If None, admin user creation will be handled via setup UI
    default_admin_username: Optional[str] = None
    default_admin_password: Optional[str] = None

    # Auth backend: "session" (cookies + tokens + login redirect) or "basic" (HTTP Basic popup)
    auth_backend: Literal["session", "basic"] = "session"

    # --- Login form / credential overrides (see "Overriding the login" below) ---
    login_template: str = 'auth_user/login.html.j2'
    session_identity_attribute: Literal["username", "email"] = "username"
    identity_form_field: str = "username"    # POST field name the handler reads the identifier from
    remember_form_field: str = "remember"    # POST field name of the "remember me" checkbox
    session_password_attribute: str = "hashed_password"

    collect_login_ip: bool = True
    allow_api_tokens: bool = True  # set to False to disable personal access tokens globally

    # Per-session metadata (device / IP / last-seen on the sessions pages)
    session_track_metadata: bool = True   # capture user-agent + refresh last_seen_at
    session_last_seen_throttle: int = 60  # min seconds between last_seen_at writes

    # Session lifetimes (seconds)
    session_lifetime: int = 3600              # 1 hour
    session_lifetime_remember: int = 2592000  # 30 days ("remember me")

    # Case-insensitive identity match (e.g. email login on Postgres)
    session_identity_case_insensitive: bool = False

    # --- Composable route mounting (see "Composable route mounting" below) ---
    enable_login_routes: bool = True
    enable_setup_routes: bool = True
    enable_registration: bool = True
    enable_totp: bool = True
    enable_api_tokens: bool = True
    enable_session_admin: bool = True
    enable_user_admin: bool = True
    enable_password_reset: bool = False   # OFF by default — inert without a delivery listener

    # --- Password reset (see "Password reset" below) ---
    forgot_password_template: str = 'auth_user/forgot_password.html.j2'
    reset_password_template: str = 'auth_user/reset_password.html.j2'
    password_reset_token_ttl: int = 3600  # token lifetime in seconds (1 hour)

    # --- TOTP two-factor ---
    totp_max_attempts: int = 5            # max failed 2FA attempts per pending session

    # --- Login rate limiting + account lockout ---
    login_rate_limit_per_user: int = 5    # max attempts per username per window
    login_rate_limit_per_ip: int = 20     # max attempts per IP per window
    login_rate_limit_window: int = 60     # window size in seconds
    login_lockout_threshold: int = 15     # total failed attempts before account lockout
    login_lockout_duration: int = 900     # lockout duration in seconds (0 = manual unlock only)
```

> Proxy/OIDC backend keys (`proxy_*`, `oidc_*`) are documented in
> [docs/sso-backends.md](docs/sso-backends.md).

| Setting | Default | Effect |
|---------|---------|--------|
| `login_template` | `auth_user/login.html.j2` | Jinja template rendered for the login form (GET + every POST re-render). Point it at your own template to reuse a host app's login page. |
| `session_identity_attribute` | `username` | User **column** the submitted identifier is matched against in the `session` backend. Set to `email` to log users in by email. |
| `session_identity_case_insensitive` | `False` | Match the identifier case-insensitively (`lower(column) == lower(input)`). Set `True` for email login on Postgres where a stored mixed-case address must match whatever case the user types (#189). |
| `identity_form_field` | `username` | Name of the POST **form field** the `/login` handler reads the identifier from. Set to `email` when your reused template posts `name="email"`, so the handler reads it instead of a missing `username` field (which would 422). |
| `remember_form_field` | `remember` | Name of the POST form field for the "remember me" checkbox. Set to e.g. `_remember_me` to match a reused template. |
| `session_password_attribute` | `hashed_password` | User column the built-in bcrypt verifier reads the stored hash from. |
| `collect_login_ip` | `True` | Capture client IP at login; gates the IP column on the sessions pages |
| `session_track_metadata` | `True` | Capture User-Agent at login and refresh `last_seen_at` on activity |
| `session_last_seen_throttle` | `60` | Minimum seconds between `last_seen_at` writes (keeps the auth path cheap) |

### Overriding the login

The `session` backend exposes these extension points so a host application can
reuse its own login page and password scheme **without** shadowing the `/login`
route (all default to the plugin's historical behaviour, so existing
deployments are unaffected):

1. **Custom template** — set `login_template` to your own Jinja template. It
   receives `next`, `error`, `setup_needed`, `signed_out` and
   `allow_registration`; your form posts the identifier + `password` to
   `POST /login`.
2. **Login by email** — this is **two settings**, because the *form field* and
   the *DB column* are separate:
   - `session_identity_attribute = "email"` matches the submitted value against
     `FastPluggyBaseUser.email` (the **column**) instead of `username`.
   - `identity_form_field = "email"` makes the handler read the value from a
     form field named `email` (the **field**). A reused template that posts
     `name="email"` needs this — otherwise the handler looks for a `username`
     field, finds nothing, and returns 422. Likewise set
     `remember_form_field` if your template's checkbox isn't named `remember`.
3. **Own your hash scheme** — expose `verify_login(user, password) -> bool` on
   the active `auth_manager`; the login route delegates the password check to it
   (letting you support legacy formats, a migrated column, or rehash-on-login).
   If no such hook exists, the plugin falls back to a bcrypt check against
   `session_password_attribute`.

### Composable route mounting

By default the plugin mounts every route group. A host application that already
owns some of these surfaces (its own `/login`, its own `/register`) can turn the
matching group **off** so the plugin composes only the parts it wants — without
shadowing the host's routes. Each flag gates **both** the routes and the tables
that feature owns, so a disabled feature creates neither.

| Setting | Default | Gates |
|---------|---------|-------|
| `enable_login_routes` | `True` | `/login`, `/logout`, `/login/2fa` |
| `enable_setup_routes` | `True` | `/setup/*` first-admin bootstrap |
| `enable_registration` | `True` | `/register` self-service signup |
| `enable_totp` | `True` | `/profile/2fa/*` **and** the `totp_secrets` table |
| `enable_api_tokens` | `True` | `/profile/tokens/*` **and** the `api_tokens` table |
| `enable_session_admin` | `True` | `/profile/sessions/*` management UI |
| `enable_user_admin` | `True` | `/admin/users/*`, auth-settings and security UI |
| `enable_password_reset` | `False` | `/forgot` + `/reset/{token}` **and** the `password_reset_tokens` table — self-service password reset (OFF by default: inert without a listener for the emitted `auth_user.password_reset_requested` event that delivers the link) |

The server-side `sessions` table and the login rate-limit tables
(`login_attempts` / `account_lockouts`) are **always** created — they back the
session and lockout machinery regardless of which routes are mounted.

Typical host composition — keep the plugin's session backend, admin and profile
surfaces while serving your own login/register/setup pages:

```python
enable_login_routes = False   # host serves its own /login
enable_registration = False   # host serves its own /register
enable_setup_routes = False   # host bootstraps its own first admin
```

### Auth backends

| Backend | `auth_backend` | How it works |
|---------|---------------|-------------|
| **Session** (default) | `"session"` | Cookie-based sessions + Bearer tokens + HTTP Basic with `__token__` (pip/twine). Redirects to login page on auth failure. |
| **Basic** | `"basic"` | HTTP Basic authentication only. Triggers browser popup on auth failure. |
| **Proxy** | `"proxy"` | Trusts forward-auth identity headers from a reverse proxy (Caddy `forward_auth` + Authelia). See [docs/sso-backends.md](docs/sso-backends.md). |
| **OIDC** | `"oidc"` | Runs the OpenID Connect authorization-code flow against an external provider. See [docs/sso-backends.md](docs/sso-backends.md). |
| **SSO** | `"proxy"` | Trusted forward-auth headers from a reverse proxy (Caddy `forward_auth` + Authelia, authentik, oauth2-proxy…). See below. |

The auth backend is configurable via environment variable or database settings:

```bash
AUTH_BACKEND=basic  # or "session" (default), or "proxy"
```
Config keys are unprefixed env vars (field name upper-cased); there is no AUTH_USER_ prefix (#3).

### SSO backend (trusted forward-auth headers)

The proxy authenticates the user and injects `Remote-User` / `Remote-Email` /
`Remote-Groups` into every proxied request; the `sso` backend trusts those
headers — **only** when the request provably came from the proxy:

- `proxy_trusted_ips` (**required**, fail closed): client IP must match one of
  these IPs/CIDRs before headers are even read.
- `proxy_secret` (**strongly recommended on Docker**): a shared secret the
  proxy injects as `X-FP-SSO-Secret` (e.g. Caddy `header_up`). On Docker bridge
  networking, hairpin SNAT makes the proxy and any co-located container arrive
  from the same bridge-gateway IP, so IP trust alone has a same-host hole.

Behavior:

- Auth order per request: **API tokens → trusted headers → local session cookie**
  (tokens first so direct-port app→app clients keep working; cookie fallback so
  break-glass local logins still authenticate).
- Unknown identities are JIT-provisioned (`proxy_auto_create_users`, default on)
  with an **unusable password** — the local login form can never match them.
  Usernames are lowercased (Authelia lowercases identities).
- `is_admin` syncs from `Remote-Groups` ⊇ `proxy_admin_group` (default
  `fp-admins`) **per request** — an SSO group revoke demotes immediately. Set
  `proxy_manage_admin_locally=True` to keep `is_admin` under local control.
- Identity key is `username` (default) or `email` via `proxy_identity_attribute`.
- Logout redirects to `proxy_logout_url` (the proxy owns the real session); the
  local `/login` form is disabled unless `proxy_local_login_fallback=True`;
  local TOTP UI is hidden (the SSO provider owns MFA).

Minimal setup behind Authelia:

```bash
AUTH_BACKEND=proxy
AUTH_USER_PROXY_TRUSTED_PROXIES='["172.17.0.1/32"]'   # your proxy's IP as seen by the app
AUTH_USER_PROXY_PROXY_SECRET=<random-shared-secret>    # + Caddy: header_up X-FP-SSO-Secret <same>
AUTH_USER_PROXY_LOGOUT_URL=https://auth.example.com/logout
```

## Admin User Setup

The plugin provides **intelligent admin user setup** with two approaches:

### 🎯 **Recommended: UI-Based Setup (Default)**
By default, `default_admin_username` and `default_admin_password` are set to `None`, which enables the setup UI:

1. **First Install**: When no users exist, visit `/setup/` to create the first admin user
2. **Secure**: No hardcoded credentials - you choose the username and password
3. **User-Friendly**: Clean web interface with validation and error handling
4. **Automatic Detection**: The system automatically detects when setup is needed

### 🔧 **Alternative: Automatic Creation with Configured Credentials**
If you prefer automatic admin creation, configure default credentials:

```python
# In your environment or config
default_admin_username = "your_admin_username"
default_admin_password = "your_secure_password"
```

When configured, the plugin will automatically create the admin user on first startup.

### 📋 **Setup Process**
1. **Plugin Load**: System checks if any users exist
2. **If No Users**:
   - **With configured credentials**: Automatically creates admin user
   - **Without credentials (default)**: Logs message to visit `/setup/`
3. **Setup UI**: Visit `/setup/` to create admin user with custom credentials
4. **Redirect**: After successful setup, redirects to login page

### 🔍 **Setup Status Check**
You can check if setup is needed programmatically:

```python
from fastpluggy_plugin.auth_user.src.repository import needs_initial_setup
from fastpluggy.core.database import get_db

if needs_initial_setup(get_db()):
    print("Setup required - visit /setup/")
else:
    print("Admin user exists")
```

## Routes

Route groups are gated by the `enable_*` flags (see [Composable route mounting](#composable-route-mounting)); the paths below are the defaults with everything mounted.

### Setup (`enable_setup_routes`)
- `GET /setup/` — first-admin setup page (only when no users exist)
- `POST /setup/` — process admin creation
- `GET /setup/check` — API: is setup needed?

### Authentication / login (`enable_login_routes`)
- `GET|POST /login` — credential form + submit
- `GET|POST /login/2fa` — second-factor challenge during login
- `GET /logout` — the sign-out link: end the session, redirect to `/login?signed_out=1`. Reached from another site, it shows a page that asks first (see [Signing out](#signing-out))
- `POST /logout` — what that page's button sends; only a page of the application may send it

### Registration (`enable_registration`)
- `GET|POST /register` — self-service signup

### Password reset (`enable_password_reset`, OFF by default)
- `GET|POST /forgot` — request a reset link (mail-agnostic; emits an event)
- `GET|POST /reset/{token}` — set a new password via the token link (route name `reset_password`)

### OIDC (when `auth_backend="oidc"`)
- `GET /oidc/login` → provider authorization endpoint
- `GET /oidc/callback` — validate ID token, create local session

### Profile (authenticated)
- `GET|POST /profile/` — profile page + change password
- `GET /profile/2fa/` and `POST /profile/2fa/{setup,verify,disable,backup-codes}` — TOTP management (`enable_totp`)
- `GET /profile/tokens/` + `POST /profile/tokens/{create,revoke/{id}}` — personal access tokens (`enable_api_tokens`)
- `GET /profile/sessions/` + `POST /profile/sessions/{revoke/{id},revoke-all}` — session management (`enable_session_admin`)

### Admin (`enable_user_admin`, requires `fp_admin` role)
- `GET /admin/users/` + add/edit/`POST /admin/users/delete/{id}` — user CRUD
- `POST /admin/users/disable-2fa/{id}` — admin 2FA override
- `GET /admin/users/sessions/` + revoke session / revoke all of a user's sessions
- `GET|POST /admin/auth-settings/` — auth settings (`collect_login_ip`, `allow_api_tokens`, …)
- `GET /admin/security/attempts` — recent login attempts
- `GET /admin/security/lockouts` + `POST /admin/security/lockouts/unlock` (form field `username`) — lockout management

## Events

The plugin emits these on the core EventBus (declared via `emits` on `AuthUserPlugin`) for host listeners:

| Event | Payload | When |
|-------|---------|------|
| `user.login` | `user_id, username, ip, remember` | successful login |
| `user.logout` | `user_id, username` | session terminated |
| `user.password_changed` | `user_id, username, changed_by` | password changed (self or admin) |
| `user.totp_enabled` | `user_id, username` | user enables TOTP |
| `user.totp_disabled` | `user_id, username` | TOTP disabled (user or admin) |
| `user.locked_out` | `username, ip` | account locked after repeated failures |
| `user.unlocked` | `username, unlocked_by` | admin unlocks an account |
| `user.sso_provisioned` | `user_id, username, email` | proxy backend JIT-creates a user |
| `auth_user.password_reset_requested` | `reset_url, …` | `/forgot` mints a token (host delivers the link) |

## Password reset

Optional (`enable_password_reset`, **off by default**). Two entry points share one single-use, expiring, SHA-256-hashed token and the same `/reset/{token}` redemption page:

- **Self-service** — `GET|POST /forgot` mints a token and emits
  `auth_user.password_reset_requested` with a ready-built `reset_url`. The plugin
  **sends nothing**; a host listener delivers the link (email/SMS/etc.). This keeps
  the plugin mail-agnostic and avoids leaking whether an address exists
  (enumeration defense). Because it's inert without a listener, the flag defaults off.
- **Admin-initiated** — a host reaches the same machinery through the
  `authentication` capability, without hard-importing the plugin:

  ```python
  from fastpluggy.core.global_registry import GlobalRegistry

  raw = GlobalRegistry.get_capability("authentication").mint_password_reset_token(db, user_id)
  reset_url = request.url_for("reset_password", token=raw)
  # deliver reset_url yourself
  ```

  `mint_password_reset_token(db, user_id, ttl_seconds=None)` returns the **raw**
  token (safe: the admin already chose the user). It raises `RuntimeError` if
  `enable_password_reset` is off (the table/route wouldn't exist). Token lifetime
  defaults to `password_reset_token_ttl` (3600s). Both templates
  (`forgot_password_template`, `reset_password_template`) are overridable.

## Menu Integration

The plugin automatically adds the following menu items:
- **Profile** (`/profile/`) - User profile page
- **Logout** (`/logout`) - Logout functionality

## Templates

Templates live under `templates/auth_user/` and are Jinja2. Key ones (most overridable via config):

- `login.html.j2` — login form (`login_template`)
- `profile_card.html.j2` — profile page (change-password form built via ViewBuilder)
- `forgot_password.html.j2` — reset request form (`forgot_password_template`)
- `reset_password.html.j2` — set-new-password form (`reset_password_template`)
- `register.html.j2`, `setup.html.j2` — signup / first-admin bootstrap
- 2FA, sessions, tokens and admin templates for the respective UIs

## Usage

1. **Install** the plugin — it is auto-discovered via the `fastpluggy.plugins` entry point
2. **Auth is auto-wired** — the plugin calls `fast_pluggy.set_auth_manager()` during `on_load_complete`, so you do **not** need to pass `auth_manager=` to `FastPluggy()`. Just `FastPluggy(app)` is enough.
3. **First run** — visit `/setup/` to create the first admin user (or set `default_admin_username` / `default_admin_password` in config for automatic creation)
4. **Profile** — authenticated users can manage their profile at `/profile/`

> If you pass `auth_manager=` explicitly to `FastPluggy()`, the plugin respects it and does not override.

## Personal Access Tokens

Users can create long-lived API tokens for programmatic access (CI/CD, pip, twine, scripts).

### Managing tokens

Tokens are managed via the UI at `/profile/tokens/`:
- Create a token with a name and optional expiry (in days)
- The raw token value is shown **once** — copy it immediately
- Revoke any token at any time

### Using tokens — API clients (Bearer)

```http
Authorization: Bearer <your-token>
```

Any endpoint protected by `require_authentication` accepts this header.

### Using tokens — pip / twine (HTTP Basic)

pip and twine use HTTP Basic auth. Use `__token__` as the username and your token as the password:

```bash
# pip install
pip install --index-url https://__token__:<your-token>@registry.fastpluggy.xyz/pypi/simple/ my-package

# twine upload
twine upload --repository-url https://registry.fastpluggy.xyz/pypi/ \
  -u __token__ -p <your-token> dist/*
```

Or configure `~/.pypirc`:

```ini
[fastpluggy]
repository = https://registry.fastpluggy.xyz/pypi/
username = __token__
password = <your-token>
```

`SessionAuthManager` detects the `__token__` username in Basic auth headers and validates the password as a personal access token (SHA256 hash lookup), so no separate auth scheme is needed for pip/twine.

### Token model

| Field | Description |
|-------|-------------|
| `name` | User-friendly label |
| `token_hash` | SHA256 of the raw token (never stored in plaintext) |
| `expires_at` | Optional expiry timestamp |
| `last_used_at` | Updated on every successful use |

## Security Notes

- Passwords are securely hashed using BCrypt (`BasicAuthManager.hash_password()`)
- Sessions are managed with configurable lifetime (default: 1 hour)
- Admin privileges are controlled via the `is_admin` boolean field
- API tokens are stored as SHA256 hashes (never in plaintext)
- **Important**: Change the default admin password after first login for security

### Signing out

Signing out deletes the session on the server, so a copy of the cookie (another device, a
proxy log, a stolen one) is refused from then on, not only the browser that signed out.

Another site cannot sign a visitor out. `/logout` stays a plain link, so menus and host
templates need no change, but it acts only when the browser reports that one of the
application's own pages, or the visitor (address bar, bookmark), started the request
(`Sec-Fetch-Site`). A link or a redirect on another site lands on a page that asks, and its
"Sign out" button posts to `/logout`, which accepts same-origin requests only. A browser too
old to send `Sec-Fetch-Site` (before 2023) is judged on its `Referer`, which the other site can
withhold: there a forced sign-out remains possible.

### Cookies over HTTPS

The session cookie and the pending second-factor cookie are `HttpOnly` and `SameSite=Lax`. They
also carry `Secure`, so the browser never sends them over plain http, in two cases:

- the request arrived over https. Behind a reverse proxy that ends TLS, this needs the ASGI
  server to trust the proxy's `X-Forwarded-Proto` (uvicorn: `--forwarded-allow-ips`);
- the app runs with `SESSION_HTTPS_ONLY=true`, the core's switch for its own session cookie. Set
  it when TLS ends at a proxy whose headers the app does not trust.

Otherwise they are set without `Secure`: a browser drops a `Secure` cookie it receives over plain
http, so nobody could sign in to an app served without TLS.

### OIDC backend (OpenID Connect client)

The app itself runs the authorization-code flow against the provider — no
reverse proxy needed, so it works for any host that can reach the provider
over HTTPS (and needs no shared cookie domain).

- `/login` → `/oidc/login` → provider's authorization endpoint → back to
  `/oidc/callback`, which validates the ID token (authlib: issuer, JWKS
  signature, nonce, state) and creates a **normal local session**.
- Claims map to the local user through the same identity settings the proxy
  backend uses (`proxy_identity_attribute`, `proxy_auto_create_users`,
  `proxy_admin_group`, `proxy_manage_admin_locally`); username claim and
  groups claim are configurable (`oidc_username_claim`, `oidc_groups_claim`).
- The provider must have the app registered as a client (for Authelia: a
  static config block with the hashed client secret and
  `https://<app>/oidc/callback` as redirect URI).

```bash
AUTH_BACKEND=oidc
OIDC_ISSUER=https://auth.example.com
OIDC_CLIENT_ID=my-app
OIDC_CLIENT_SECRET=<plaintext — provider stores only the hash>
OIDC_CA_BUNDLE=/etc/ssl/certs/internal-root.crt   # if the provider uses an internal CA
OIDC_LOGOUT_URL=https://auth.example.com/logout   # optional
```
