Ushka

ushka.sessions.forge

Forging a session for tests: the supported way to be "logged in" without a login.

forge_session_cookie(app, {"uid": 1}) returns "_ushka_session=...", a cookie signed with the app's own secret key, ready for a test client, a curl --cookie or ushka verify --as-session uid=1.

This is a testing tool. Whoever can run it holds the secret key and so can become any user. Keep the key in the environment or .env (never on a command line, never in ushka.toml), and do not run it against the key of a real production deployment. Nothing here logs a session value.

In this module

def forge_session_cookie()A signed session cookie holding data, as "name=value".
def aforge_session_cookie()Like forge_session_cookie, and also works with a server-side store.
def parse_session_pairs()["uid=1", "admin=true", "name=ana"] -> {"uid": 1, "admin": True, "name": "ana"}.
def forge_session_cookie(app_or_config: Any, data: dict[str, Any]) -> str

A signed session cookie holding data, as "name=value".

app_or_config is the app (or its Config). Works for the default signed-cookie sessions; when the app keeps sessions on the server ([session] store = "database") use the coroutine aforge_session_cookie, which also creates the record in the store.

Raises

TypeDescription
RuntimeError

If there is no secret key, or the app uses a server-side store.

async def aforge_session_cookie(
    app_or_config: Any,
    data: dict[str, Any],
) -> str

Like forge_session_cookie, and also works with a server-side store.

With [session] store = "database" it writes the session record to the store (so use a test database) and returns the cookie that points to it.

def parse_session_pairs

def parse_session_pairs(pairs: list[str]) -> dict[str, Any]

["uid=1", "admin=true", "name=ana"] -> {"uid": 1, "admin": True, "name": "ana"}.

Whole numbers become int, true/false become bool, anything else stays a string. Raises ValueError for an item without key=.