Authentication

Caspian provides a robust, session-based authentication system built on FastAPI's security utilities. It is secure by default (HttpOnly cookies), supports Role-Based Access Control (RBAC), and now uses a dedicated centralized auth configuration file for all auth-related behavior.

Configuration

Auth settings are now centralized in src/lib/auth/auth_config.py. This file is the single place where you define token behavior, route visibility, auth routes, redirect paths, API prefixes, and optional role-based access rules.

This keeps authentication configuration clean, reusable, and separate from your application bootstrapping logic. Secrets such as AUTH_SECRET and AUTH_COOKIE_NAME should stay in your .env, while framework-level auth behavior is configured in build_auth_settings().

Centralized Auth Rules

Define all authentication behavior in one place: token validity, route access mode, auth pages, redirect destinations, and role-based route restrictions.

src/lib/auth/auth_config.py
from __future__ import annotations
from casp.auth import AuthSettings


def build_auth_settings() -> AuthSettings:
    return AuthSettings(
        # Token settings
        default_token_validity="1h",
        token_auto_refresh=False,

        # Route protection
        is_all_routes_private=False,
        public_routes=["/"],
        auth_routes=["/signin", "/signup"],
        private_routes=[],

        # Role-based access
        is_role_based=False,
        role_identifier="role",
        role_based_routes={},

        # Redirects / prefixes
        default_signin_redirect="/dashboard",
        default_signout_redirect="/signin",
        api_auth_prefix="/api/auth",
    )
default_token_validity

Controls how long the auth token remains valid, for example "1h", "7d", or other supported duration strings.

token_auto_refresh

Enables or disables automatic token refresh behavior for active sessions.

is_all_routes_private

When set to True, every route is private by default unless explicitly listed in public_routes.

public_routes / auth_routes / private_routes

Define which paths are public, which belong to auth pages, and which require authentication when global-private mode is not enabled.

default_signin_redirect

The fallback redirect used after a successful sign-in when no custom destination is provided.

default_signout_redirect

The default location users are sent to after signing out.

is_role_based / role_identifier

Enables role-aware authorization and defines which payload field is used as the user role key.

role_based_routes

Maps paths to a list of allowed roles. The expected format is PATH -> [ROLES].

Role-Based Routes

When role-based access is enabled, Caspian checks the configured role_identifier inside the auth payload and matches the current path against role_based_routes.

Example RBAC Configuration

src/lib/auth/auth_config.py
def build_auth_settings() -> AuthSettings:
    return AuthSettings(
        is_role_based=True,
        role_identifier="role",
        role_based_routes={
            "/report": ["admin"],
            "/admin": ["admin", "superadmin"],
        },
    )

The Auth Object

The global auth object manages the session lifecycle. It abstracts FastAPI's response and cookie logic, and uses your centralized configuration automatically.

auth.sign_in(data, redirect_to?)

Creates a session. data is a dict stored in the secure session cookie. Returns a response object handling the cookie set.

auth.sign_out(redirect_to?)

Destroys the session and clears HttpOnly cookies.

auth.is_authenticated()

Returns True if the current session is valid.

auth.get_payload()

Retrieves the user data stored during sign-in.

Implementation Example

A complete async sign-in flow. The backend handles verification using Prisma (Async), while the frontend submits the form via RPC. After authentication, the redirect falls back to the centralized auth config when no next value is provided.

Protecting Routes

You can protect individual actions using the @rpc decorator, protect entire pages, or define path-level rules centrally in auth_config.py.

Action Level (RPC)

Best for securing specific buttons or form submissions. The client receives a 401/403 error.

@rpc(require_auth=True)
async def delete_account():
    # Only runs if authenticated
    await prisma.user.delete(...)

Page Level

Best for securing entire views. Redirects unauthenticated users to the sign-in page.

from casp.auth import require_auth

@require_auth
def page():
    return render_page(__file__)