Metadata-Version: 2.5
Name: appkit-user
Version: 1.20.0
Summary: Add your description here
Project-URL: Homepage, https://github.com/jenreh/appkit
Project-URL: Documentation, https://github.com/jenreh/appkit/tree/main/docs
Project-URL: Repository, https://github.com/jenreh/appkit
Project-URL: Issues, https://github.com/jenreh/appkit/issues
Author: Jens Rehpöhler
Keywords: components,mantine,reflex,ui,web
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: User Interfaces
Requires-Python: >=3.13
Requires-Dist: appkit-commons
Requires-Dist: appkit-mantine
Requires-Dist: cryptography>=50.0.2
Requires-Dist: fastapi>=0.165.0
Requires-Dist: greenlet>=3.5.6
Requires-Dist: jinja2>=3.1.6
Requires-Dist: python-dotenv>=1.2.2
Requires-Dist: requests-oauthlib>=2.0.0
Requires-Dist: urllib3>=2.8.0
Provides-Extra: azure
Requires-Dist: azure-communication-email>=1.1.0; extra == 'azure'
Provides-Extra: resend
Requires-Dist: resend>=2.53.2; extra == 'resend'
Description-Content-Type: text/markdown

# appkit-user

[![Python 3.13+](https://img.shields.io/badge/python-3.13+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Enterprise user management and authentication for Reflex applications.**

appkit-user provides comprehensive user authentication, authorization, and management capabilities for Reflex applications. It includes OAuth2 integration with GitHub and Azure, role-based access control (RBAC), multi-tenant user profiles, and secure session management.

---

## ✨ Features

- **OAuth2 Authentication** - GitHub and Azure OAuth2 providers with PKCE support
- **Role-Based Access Control** - Flexible RBAC with custom roles and permissions
- **Multi-Tenant Support** - User profiles organized by tenants and projects
- **Session Management** - Secure session handling with automatic cleanup
- **User Management UI** - Complete admin interface for user CRUD operations
- **Authentication Decorators** - Easy-to-use decorators for protecting routes and components
- **Profile Management** - User profile editing with role assignment
- **Login Throttling** - Lockout after repeated failed password logins, per email and per client address
- **Forced Password Reset** - Users flagged `needs_password_reset` get a one-time reset link instead of a session
- **Security Features** - CSRF protection, secure redirects, and session validation
- **Installation Setup** - Commands and Alembic helpers for the encryption key, the database tables and the first administrator

---

## 🚀 Installation

### As Part of AppKit Workspace

If you're using the full AppKit workspace:

```bash
git clone https://github.com/jenreh/appkit.git
cd appkit
uv sync
```

### Standalone Installation

Install from PyPI:

```bash
pip install appkit-user
```

Or with uv:

```bash
uv add appkit-user
```

### Dependencies

- `greenlet` (async utilities)
- `appkit-commons` (shared utilities)
- `appkit-mantine` (Mantine UI components)
- `requests_oauthlib>=2.0.0` (OAuth2 client)
- `fastapi`, `jinja2`, `urllib3` (REST routes, email templates, HTTP)
- `python-dotenv` (reads `.env` for the setup commands)

---

## 🏁 Quick Start

### Setup Commands

`appkit-user` ships the three setup steps of a new installation. Run them in the
project folder, next to `.env` and `configuration/`.

```bash
# Write mn-db-encryption-key to .env (local secret provider only).
# An existing key is never replaced. Back the key up.
uv run appkit-user init-db-key            # or --env-file <path>

# Create the missing database tables. Safe to repeat.
uv run appkit-user init-db

# Create the first administrator.
uv run appkit-user bootstrap-admin
```

`init-db` and `bootstrap-admin` read the database settings from `configuration/`
(honouring `PROFILES`) and exit with status 1 outside a project folder.

`init-db` creates the `auth_*` tables that do not exist yet. It never alters or
drops a table, so schema changes of a newer version still need a migration in your
app. If your Alembic migrations already create these tables, skip `init-db`:
running it first makes those migrations fail.

`bootstrap-admin` reads the secrets `mn-admin-email` and `mn-admin-password` from
the configured secret provider. It does nothing while an active administrator
exists, so a container start script can run it every time. A missing secret only logs a
warning. An invalid one exits with status 1. The password needs at least 12
characters with upper case, lower case, a digit and a special character, and must
be changed at first login.

### Alembic Migration

To manage the tables with Alembic instead of `init-db`, add one revision:

```python
from alembic import op
from appkit_user.authentication.backend.database import (
    create_user_tables,
    drop_user_tables,
)


def upgrade() -> None:
    create_user_tables(op.get_bind())


def downgrade() -> None:
    drop_user_tables(op.get_bind())  # deletes all users and their data
```

It works online and with `alembic upgrade --sql`. `upgrade` skips existing tables
(offline mode cannot check and writes all of them). `downgrade` drops all
`auth_*` tables, including ones that existed before this revision.

The tables follow the installed appkit-user version, not the date of your
revision. A fresh database therefore already gets the columns of newer versions,
so a later migration that adds one must first check that it is missing.

### Creating the Tables at Startup

```python
from appkit_user.authentication.backend.database import init_user_database

await init_user_database()  # after the service registry is configured
```

### Basic OAuth Configuration

Configure OAuth providers in your application:

```python
from appkit_user.configuration import GithubOAuthConfig, AzureOAuthConfig

# GitHub OAuth
github_config = GithubOAuthConfig(
    client_id="your-github-client-id",
    client_secret="secret:github-client-secret",
    redirect_url="http://localhost:3000/auth/github/callback",
)

# Azure OAuth
azure_config = AzureOAuthConfig(
    client_id="your-azure-client-id",
    client_secret="secret:azure-client-secret",
    tenant_id="your-tenant-id",
    redirect_url="http://localhost:3000/auth/azure/callback",
)
```

### Protecting Routes

Use authentication decorators to protect your pages:

```python
import reflex as rx
from appkit_user.authentication.components import requires_authenticated, requires_role


# Require authentication
@requires_authenticated
def protected_page():
    return rx.text("This page requires login")


# Require specific role
@requires_role("admin")
def admin_page():
    return rx.text("Admin only content")


# Require admin privileges
@requires_admin
def super_admin_page():
    return rx.text("Super admin content")
```

### Protecting Event Handlers

The session filter decides by the handler an event targets, never by the page
path the client sends, because a crafted client can fake that path:

- A handler runs without a session only if it is marked `@public_event`, its
  state is marked `@public_state`, or the state is listed in `public_states`.
- Every handler of a state marked `@admin_state` needs an admin.
- `@is_authenticated` and `@requires_admin` check the session in the database
  on every call. Put them on every `async` handler that reads or writes
  protected data.

```python
from appkit_user.authentication import decorators as auth
from appkit_user.authentication.access import admin_state


@admin_state
class ReportAdminState(rx.State):
    @rx.event
    @auth.requires_admin
    async def delete_report(self, report_id: int) -> None: ...
```

**Upgrading:** a route in `public_routes` now only lets its page load. If a
public page has its own handlers, mark them public or list their states:

```yaml
authentication:
  public_states:
    - my_app.pages.landing.*
  # session_filter_state: false  # old route check, not recommended
```

### Login Integration

Add login functionality to your app:

```python
from appkit_user.authentication.components import login_form


def login_page():
    return login_form(
        header="My App", logo="/img/logo.svg", logo_dark="/img/logo_dark.svg"
    )
```

#### Page factories

`authenticated_page` takes the page layout from the app through its `template`
argument:

```python
from appkit_user.authentication.templates import authenticated_page


def my_template(content: rx.Component) -> rx.Component:
    return mn.app_shell(mn.app_shell.main(content))


@authenticated_page(route="/settings", title="Settings", template=my_template)
def settings_page() -> rx.Component:
    return rx.box("Settings")
```

`authenticated_page` is the only page decorator in appkit-user. It adds the session
monitor and the `admin_only` gate. Theming comes from appkit-mantine
(`mn.theme_wrapper`). Layouts such as a splash page or a page with a navbar belong
in the app.

The login and password-reset page factories take the app's page decorator factory
as their first argument. It is called as
`layout(route=..., title=..., on_load=...)` and must return a page decorator
(see the `PageLayout` protocol in `appkit_user.user_management.pages`).

```python
from appkit_user.user_management.pages import (
    create_login_page,
    create_password_reset_confirm_page,
    create_password_reset_request_page,
)

from app.components.templates import default_layout  # your app's layout

create_login_page(default_layout)
create_password_reset_request_page(default_layout)
create_password_reset_confirm_page(default_layout)
```

There is no profile page factory. Build the page in your app around
`user_profile_view()` from `appkit_user.user_management.components.user_profile`.

#### New user approval

A user who signs in with OAuth for the first time gets an account without
access. The account is stored with `is_verified=False` and no roles. Until an
admin approves it, the user can only see the welcome page; every other page
redirects there, and REST routes answer with 403.

Register the welcome page once. Pass your own component as `content`, or leave
it out to use the default card (`welcome_pending`). `logout_button()` lets the
user sign out from a custom page.

```python
from appkit_user.authentication.components import logout_button
from appkit_user.user_management.pages import create_welcome_page


def my_welcome() -> rx.Component:
    return mn.stack(mn.title("Willkommen!"), logout_button())


create_welcome_page(default_layout, content=my_welcome)
```

Admins approve users in the user table: pending users carry an
"Ausstehend" badge, the "Nur ausstehende" switch filters them, and the
approve button grants access with the default role. When an email provider
is configured, every active admin gets an email about each new pending user.

The gate is on by default. Turn it off with
`require_admin_approval: false`. `welcome_route` (default `/welcome`) and
`user_admin_route` (default `/admin/users`, used in the email link) are
configurable too.

---

## 📖 Usage

### OAuth Configuration

#### GitHub OAuth

Configure GitHub OAuth application:

```python
from appkit_user.configuration import GithubOAuthConfig

config = GithubOAuthConfig(
    client_id="gh_oauth_client_id",
    client_secret="secret:github_oauth_secret",
    redirect_url="https://myapp.com/auth/github/callback",
    scopes=["user", "user:email", "read:org"],  # Optional custom scopes
)
```

#### Azure OAuth

Configure Azure AD application:

```python
from appkit_user.configuration import AzureOAuthConfig

config = AzureOAuthConfig(
    client_id="azure_client_id",
    client_secret="secret:azure_client_secret",
    tenant_id="tenant-id",  # or "common" for multi-tenant
    redirect_url="https://myapp.com/auth/azure/callback",
    is_public_client=False,  # Set to True for PKCE-only apps
    scopes=["openid", "profile", "email", "User.Read"],
)
```

### Authentication Decorators

#### Basic Authentication

```python
from appkit_user.authentication.components import requires_authenticated


@requires_authenticated
def dashboard():
    return rx.text("Welcome to your dashboard!")
```

#### Role-Based Access

```python
from appkit_user.authentication.components import requires_role


@requires_role("editor")
def content_editor():
    return rx.text("Content editor interface")


@requires_role("viewer", fallback=rx.text("Access denied"))
def reports():
    return rx.text("Reports dashboard")
```

#### Admin Access

```python
from appkit_user.authentication.components import requires_admin


@requires_admin
def admin_panel():
    return rx.text("Admin control panel")
```

### User Management

#### User Table

Display and manage users:

```python
from appkit_user.user_management.components import users_table
from appkit_user.user_management.states.user_states import UserState


# users_table does not fetch on its own; load users via the page's on_load.
@rx.page(route="/admin/users", on_load=UserState.load_users)
def user_management_page():
    return rx.vstack(rx.heading("User Management"), users_table(), spacing="4")
```

#### User Profile

Manage user profiles and roles:

```python
from appkit_user.user_management.components import profile_roles, profile_state


def user_profile_page():
    return rx.vstack(rx.heading("User Profile"), profile_roles(), spacing="4")
```

### Session Management

Access current user session:

```python
from appkit_user.authentication.states import UserSession


def current_user_info():
    return rx.vstack(
        rx.text(f"User: {UserSession.user.email}"),
        rx.text(f"Roles: {UserSession.user.roles}"),
        rx.text(f"Tenant: {UserSession.user.tenant_id}"),
        rx.text(f"Authenticated: {UserSession.is_authenticated}"),
    )
```

---

## 🔧 Configuration

### OAuth Redirect URLs

Configure OAuth callback URLs in your Reflex app:

```python
# In rxconfig.py or main app file
app.add_page(oauth_login_splash, route="/auth/github/callback", title="GitHub Login")

app.add_page(oauth_login_splash, route="/auth/azure/callback", title="Azure Login")
```

### Custom OAuth Providers

Extend OAuth support for custom providers:

```python
from appkit_user.configuration import OAuthConfig, OAuthProvider


class CustomOAuthConfig(OAuthConfig):
    provider: OAuthProvider = "custom"
    auth_url: str = "https://custom.provider.com/oauth/authorize"
    token_url: str = "https://custom.provider.com/oauth/token"
    user_url: str = "https://custom.provider.com/api/user"
    scopes: list[str] = ["read", "write"]
```

### Multi-Tenant Setup

Configure tenant-based user isolation:

```python
# Users are automatically scoped by tenant_id
# Access current tenant
current_tenant = UserSession.user.tenant_id

# Filter data by tenant
tenant_users = get_users_by_tenant(current_tenant)
```

---

## 📋 API Reference

### Authentication Components

- `requires_authenticated()` - Decorator for authentication-required content
- `requires_role()` - Decorator for role-based access control
- `requires_admin()` - Decorator for admin-only content
- `login_form()` - Login form with OAuth providers
- `oauth_login_splash()` - OAuth callback splash screen
- `default_fallback()` - Default unauthorized access message

### User Management Components

- `users_table()` - User management table with CRUD operations
- `add_user_button()` - Button to add new users
- `update_user_button()` - Button to edit existing users
- `delete_user_button()` - Button to remove users
- `user_form_fields()` - Form fields for user creation/editing
- `profile_roles()` - User profile role management
- `profile_state()` - User profile state management

### Configuration Classes

- `OAuthConfig` - Base OAuth configuration
- `GithubOAuthConfig` - GitHub OAuth settings
- `AzureOAuthConfig` - Azure AD OAuth settings
- `OAuthProvider` - Enum of supported OAuth providers
- `PasswordResetConfig` - Password reset token expiry, request limit, email templates
- `LoginRateLimitConfig` - Failed-login throttle (`enabled`, `max_attempts`, `max_attempts_per_client`, `window_minutes`, `lockout_minutes`)

### Database Setup

From `appkit_user.authentication.backend.database`:

- `create_user_tables(connection)` - Create the missing tables and return their names; pass `op.get_bind()` in Alembic
- `drop_user_tables(connection)` - Drop all `auth_*` tables **and their data**; fails while tables of your app reference them
- `init_user_database()` - Async variant of `create_user_tables` for the configured database

From `appkit_user.authentication.backend.services.admin_bootstrap`:

- `bootstrap_admin()` - Create the first administrator unless an active one exists

| Table | Content |
| --- | --- |
| `auth_users` | Accounts, roles and flags |
| `auth_sessions` | Login sessions |
| `auth_oauth_accounts` | Linked provider accounts with encrypted tokens |
| `auth_oauth_states` | OAuth CSRF state and PKCE verifier |
| `auth_password_reset_tokens` | One-time reset links |
| `auth_password_history` | Earlier password hashes |
| `auth_password_reset_requests` | Reset rate limiting |
| `auth_login_throttle` | Failed-login counters |

### State Management

- `UserSession` - Current user session state
- `LoginState` - Login form state management

---

## 🔒 Security

> [!IMPORTANT]
> Always configure HTTPS in production and use secure secrets management. OAuth client secrets should never be hardcoded.

- **OAuth2 PKCE Support** - Proof Key for Code Exchange for enhanced security
- **Secure Redirects** - Configurable redirect URLs prevent open redirect attacks
- **Login Throttle** - Failed password logins are counted per email (default 5) and per client address (default 20) within 15 minutes; a locked key is refused for 15 minutes before the password is checked. Configure via `authentication.login_rate_limit`. Counters live in the `auth_login_throttle` table (hashed keys, fixed window), so the limit holds across workers and restarts; create the table with `appkit-user init-db` or an Alembic migration of your app. Behind a proxy set `reflex.trusted_proxy_hops` so client addresses are real.
- **Session Security** - Automatic session cleanup and validation
- **CSRF Protection** - Built-in CSRF tokens for forms
- **Role Validation** - Server-side role checking in addition to client-side decorators
- **Tenant Isolation** - Multi-tenant data isolation prevents cross-tenant access

---

## 🤝 Integration Examples

### Complete Authentication Flow

Set up a full authentication system:

```python
import reflex as rx
from appkit_user.authentication.components import (
    login_form,
    requires_authenticated,
    oauth_login_splash,
)
from appkit_user.configuration import GithubOAuthConfig

# Configure OAuth
oauth_config = GithubOAuthConfig(
    client_id="your-client-id", client_secret="secret:your-client-secret"
)


# Public login page
def login():
    return login_form(
        header="My App", logo="/img/logo.svg", logo_dark="/img/logo_dark.svg"
    )


# Protected dashboard
@requires_authenticated
def dashboard():
    return rx.text(f"Welcome {UserSession.user.email}!")


# OAuth callback
def github_callback():
    return oauth_login_splash(provider="github", message="Signing in with GitHub...")


# Add to app
app = rx.App()
app.add_page(login, route="/login")
app.add_page(dashboard, route="/dashboard")
app.add_page(github_callback, route="/auth/github/callback")
```

### User Management System

Create an admin user management interface:

```python
from appkit_user.user_management.components import users_table
from appkit_user.authentication.components import requires_admin


@requires_admin
def admin_users():
    return rx.vstack(
        rx.heading("User Management", size="5"),
        rx.flex(users_table(), direction="column", gap="4", width="100%"),
        padding="6",
        spacing="4",
    )
```

### Role-Based Navigation

Dynamic navigation based on user roles:

```python
def navigation():
    return rx.hstack(
        rx.link("Home", href="/"),
        rx.cond(
            UserSession.is_authenticated,
            rx.hstack(
                rx.link("Dashboard", href="/dashboard"),
                rx.cond(
                    UserSession.user.roles.contains("admin"),
                    rx.link("Admin", href="/admin"),
                    rx.text(""),  # Empty for non-admins
                ),
                rx.button("Logout", on_click=UserSession.logout),
            ),
            rx.link("Login", href="/login"),
        ),
    )
```

---

## 📚 Related Components

- **[appkit-commons](./../appkit-commons)** - Shared utilities and configuration
- **[appkit-assistant](./../appkit-assistant)** - AI assistant with user authentication
- **[appkit-mantine](./../appkit-mantine)** - Form components for user management
