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 integrates seamlessly with the async RPC layer.

Configuration

Auth settings are now centralized in main.py within the setup_auth() function. This allows you to configure global route protection, define roles, and set redirect paths right at the application entry point.

Global Protection & Rules

You can make your application private by default using is_all_routes_private=True, or whitelist specific public routes.

main.py
def setup_auth():
    configure_auth(AuthSettings(
        # Token validity duration
        default_token_validity="7d",

        # Route protection mode
        # False = only explicitly private routes require auth
        is_all_routes_private=False,

        # Define public/private paths
        public_routes=["/"],
        auth_routes=["/signin", "/signup"],
        
        # Where to go after login/logout
        default_signin_redirect="/dashboard",
        default_signout_redirect="/signin",

        # Role-based access control
        is_role_based=True,
        role_based_routes={
            "/admin": ["admin", "superadmin"],
        },
    ))

The Auth Object

The global auth object manages the session lifecycle. It abstracts FastAPI's response and cookie logic.

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 handles the form submission via RPC.

Protecting Routes

You can protect individual actions using the @rpc decorator, or protect entire pages.

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__)