Skip to content

Session Management API Reference

Since 0.6, CRUDAdmin keeps admin sessions with crudauth. This page covers what CRUDAdmin itself exposes: the backend configuration classes and the session manager on a CRUDAdmin instance. For choosing a backend and the settings around sessions, see Session Backends.

Configuration classes

RedisConfig

Connection settings for the redis backend. Pass an instance, or a dict with the same keys, as SessionConfig(redis=...).

Bases: BaseModel

Configuration for Redis session backend.

Source code in crudadmin/session/configs.py
class RedisConfig(BaseModel):
    """Configuration for Redis session backend."""

    url: str | None = None
    host: str = "localhost"
    port: int = Field(default=6379, ge=1, le=65535)
    db: int = Field(default=0, ge=0)
    username: str | None = None
    password: str | None = None
    pool_size: int | None = Field(default=None, ge=1)
    connect_timeout: int | None = Field(default=None, ge=1)

    model_config = ConfigDict(extra="forbid")

    @field_validator("url", "host", "username", "password")
    @classmethod
    def validate_strings(cls, v):
        if isinstance(v, str) and v.strip() == "":
            return None
        return v

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary, excluding None values and handling URL parsing."""
        result = {}

        if self.url is not None:
            from urllib.parse import urlparse

            parsed = urlparse(self.url)
            result.update(
                {
                    "host": parsed.hostname or "localhost",
                    "port": parsed.port or 6379,
                    "db": int(parsed.path.lstrip("/"))
                    if parsed.path and parsed.path != "/"
                    else 0,
                }
            )
            if parsed.username:
                result["username"] = parsed.username
            if parsed.password:
                result["password"] = parsed.password
        else:
            result.update(
                {
                    "host": self.host,
                    "port": self.port,
                    "db": self.db,
                }
            )
            if self.username is not None:
                result["username"] = self.username
            if self.password is not None:
                result["password"] = self.password

        if self.pool_size is not None:
            result["pool_size"] = self.pool_size
        if self.connect_timeout is not None:
            result["connect_timeout"] = self.connect_timeout

        return result

to_dict()

Convert to dictionary, excluding None values and handling URL parsing.

Source code in crudadmin/session/configs.py
def to_dict(self) -> dict[str, Any]:
    """Convert to dictionary, excluding None values and handling URL parsing."""
    result = {}

    if self.url is not None:
        from urllib.parse import urlparse

        parsed = urlparse(self.url)
        result.update(
            {
                "host": parsed.hostname or "localhost",
                "port": parsed.port or 6379,
                "db": int(parsed.path.lstrip("/"))
                if parsed.path and parsed.path != "/"
                else 0,
            }
        )
        if parsed.username:
            result["username"] = parsed.username
        if parsed.password:
            result["password"] = parsed.password
    else:
        result.update(
            {
                "host": self.host,
                "port": self.port,
                "db": self.db,
            }
        )
        if self.username is not None:
            result["username"] = self.username
        if self.password is not None:
            result["password"] = self.password

    if self.pool_size is not None:
        result["pool_size"] = self.pool_size
    if self.connect_timeout is not None:
        result["connect_timeout"] = self.connect_timeout

    return result
Field Default Meaning
url None A full connection URL. When set, it is used as is (a rediss:// URL keeps TLS) and the other address fields are ignored.
host "localhost" Server host
port 6379 Server port, 1 to 65535
db 0 Database number
username None ACL username (Redis 6+)
password None Password
pool_size None Maximum number of connections in the client's pool
connect_timeout None Connection timeout in seconds
from crudadmin import CRUDAdmin, RedisConfig, SessionConfig

admin = CRUDAdmin(
    session=get_session,
    SECRET_KEY=SECRET_KEY,
    sessions=SessionConfig(
        backend="redis",
        redis=RedisConfig(url="redis://localhost:6379/0", pool_size=10),
    ),
)

MemcachedConfig

The Memcached backend was removed in 0.6. The class is kept so existing imports keep working, but passing it to CRUDAdmin (or using SessionConfig(backend="memcached")) raises a ValueError that names the replacements, redis and database.

Bases: BaseModel

Configuration for the removed Memcached session backend.

Kept so existing imports keep working; passing it to CRUDAdmin raises a ValueError that names the replacements (redis or database).

Source code in crudadmin/session/configs.py
class MemcachedConfig(BaseModel):
    """Configuration for the removed Memcached session backend.

    Kept so existing imports keep working; passing it to ``CRUDAdmin`` raises a
    ``ValueError`` that names the replacements (``redis`` or ``database``).
    """

    servers: list[str] | None = None
    host: str = "localhost"
    port: int = Field(default=11211, ge=1, le=65535)
    pool_size: int | None = Field(default=None, ge=1)

    model_config = ConfigDict(extra="forbid")

The session manager

CRUDAdmin.session_manager is crudauth's SessionManager for the admin's sessions. It is available as soon as the CRUDAdmin instance exists; call admin.initialize() before using it.

sessions = await admin.session_manager.list_for_user(user_id)

Each entry is a dict with:

Key Meaning
id The session's public handle, safe to show and to pass back; never the session id
device Browser and operating system parsed from the user agent
ip Client IP address
created_at When the admin signed in
last_activity The last request on the session
current Whether this is the session given as current_session_id

Ending sessions:

await admin.session_manager.revoke_by_handle(handle, owner_id=user_id)
await admin.session_manager.revoke_all(user_id)
await admin.session_manager.revoke_all(user_id, exclude=current_session_id)

revoke_by_handle ends one session of owner_id, found by the handle from list_for_user, and returns whether one was ended. revoke_all ends every session of the admin, optionally keeping one, and returns how many were ended.

The admin interface uses the same calls on its Sessions page (/management/sessions): admins see and end their own sessions, superusers everyone's.

For the rest of the session manager's API, see crudauth's documentation.

Session settings on CRUDAdmin

Sessions are configured with sessions=SessionConfig(...), and the login lockout and proxies with access=AccessConfig(...). The Session Backends guide explains each field.

Field Default Meaning
SessionConfig.backend "memory" "memory", "redis" or "database"
SessionConfig.redis None RedisConfig or dict, for the redis backend
SessionConfig.timeout_minutes 30 Idle time after which a session ends
SessionConfig.max_per_admin 5 Sessions one admin may hold at once
SessionConfig.cleanup_interval_minutes 15 Minimum time between sweeps of idle sessions
SessionConfig.secure_cookies True Send the session cookies over HTTPS only
AccessConfig.trusted_proxy_hops 0 Reverse proxies in front of the app; 0 ignores X-Forwarded-For
AccessConfig.lockout 5 failures, 1 to 5 minutes A crudauth LockoutConfig for the login lockout

Both classes are documented in the CRUDAdmin API reference.

Names CRUDAdmin uses

Name Value
Session cookie crudadmin_session
CSRF cookie crudadmin_csrf
CSRF request header X-CSRF-Token
Session key prefix crudadmin:<fingerprint><mount path>:session:
CSRF key prefix crudadmin:<fingerprint><mount path>:csrf:
Lockout counter prefix crudadmin:<fingerprint><mount path>:rl:
database backend tables crudadmin_auth_store, crudadmin_auth_counters

Deprecated and removed

  • The flat CRUDAdmin arguments session_backend, redis_config, session_timeout_minutes, max_sessions_per_user, cleanup_interval_minutes, secure_cookies, trusted_proxy_hops and lockout still work in 0.7, with a DeprecationWarning; use the fields above.
  • backend="hybrid" runs on redis with a DeprecationWarning, and will be removed.
  • track_sessions_in_db=True emits a DeprecationWarning. With the memory backend it switches to database; with redis it changes nothing.
  • backend="memcached" and memcached_config raise a ValueError at startup.
  • The crudadmin.session.manager, crudadmin.session.storage and crudadmin.session.backends modules were removed; crudadmin.session now only holds RedisConfig and MemcachedConfig.
  • Sessions are no longer stored in an admin_session table. After upgrading, you can drop that table.