tempest_fastapi_sdk.sessions¶
Sessão do lado do servidor: store, serviço, middleware e router.
SessionAuth
¶
SessionAuth(
*,
user_model: type[BaseUserModel] | None = None,
store: SessionStore,
settings: SessionSettings,
passwords: PasswordUtils | None = None,
authenticator: SessionAuthenticator | None = None,
)
Server-side session lifecycle orchestrator.
Mount one instance per FastAPI app. Stateless — the only
state lives in the injected :class:SessionStore and the
project's UserModel table, or in the :class:SessionAuthenticator
that replaces it.
Initialize the service.
Pass exactly one of user_model and authenticator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_model
|
type[BaseUserModel] | None
|
Concrete user model
(typically |
None
|
store
|
SessionStore
|
Persistence backend
(:class: |
required |
settings
|
SessionSettings
|
TTL / cookie / rotation flags driving the lifecycle. |
required |
passwords
|
PasswordUtils | None
|
Override for tests.
|
None
|
authenticator
|
SessionAuthenticator | None
|
Credential verifier
for a service with no user table, used by
:meth: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When both or neither of |
ImportError
|
When |
passwords
property
writable
¶
passwords: PasswordUtils
The bcrypt helper :meth:authenticate verifies hashes with.
Built in __init__ for the user_model= mode; otherwise on
first access when none was injected, and cached. Only the
user_model= path reads it, so a service built with
authenticator= (for instance through :meth:from_credentials)
runs without bcrypt installed.
Returns:
| Name | Type | Description |
|---|---|---|
PasswordUtils |
PasswordUtils
|
The injected helper, or the lazily built one. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When none was injected and the |
from_credentials
classmethod
¶
from_credentials(
username: str,
password: str | SecretStr,
*,
store: SessionStore,
settings: SessionSettings,
user_id: UUID | None = None,
) -> SessionAuth
Build a service that accepts one fixed username / password pair.
For a service whose only account is a credential from the
environment (a root user guarding an admin panel). The pair is
checked by :class:StaticCredentialAuthenticator, which compares
both halves in constant time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
The accepted username. |
required |
password
|
str | SecretStr
|
The accepted password. |
required |
store
|
SessionStore
|
Session persistence backend. |
required |
settings
|
SessionSettings
|
TTL / cookie / rotation flags. |
required |
user_id
|
UUID | None
|
Owner written on every session.
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
SessionAuth |
SessionAuth
|
A service to call |
SessionAuth
|
meth: |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
authenticate
async
¶
authenticate(session: AsyncSession, *, email: str, password: str) -> BaseUserModel
Validate credentials and return the matching user row.
Every refusal pays one bcrypt verification: an unknown address
is checked against a throwaway hash
(:meth:~tempest_fastapi_sdk.PasswordUtils.dummy_verify) and an
inactive account's password is verified before the
is_active check, so neither branch answers faster than a
wrong password.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
email
|
str
|
Account email. |
required |
password
|
str
|
Plaintext password. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The authenticated user. |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
On any failure — wrong password, missing user, inactive user. The message is deliberately generic so the response body does not tell them apart. |
RuntimeError
|
When the service was built with
|
authenticate_credentials
async
¶
Verify username / password through the configured authenticator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
The submitted username. |
required |
password
|
str
|
The submitted plaintext password. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
UUID |
UUID
|
The id the session should belong to. |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the authenticator rejects the pair. |
RuntimeError
|
When the service was built with |
login_with_credentials
async
¶
login_with_credentials(
username: str,
password: str,
*,
ip: str | None = None,
user_agent: str | None = None,
previous_session_id: str | None = None,
) -> tuple[Session, str]
Verify the credentials, then open a session for their owner.
:meth:authenticate_credentials followed by :meth:login, the
whole login step of an HTML form handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
The submitted username. |
required |
password
|
str
|
The submitted plaintext password. |
required |
ip
|
str | None
|
Client IP. |
None
|
user_agent
|
str | None
|
Raw User-Agent header. |
None
|
previous_session_id
|
str | None
|
Plaintext cookie the
request already carried, revoked when
|
None
|
Returns:
| Type | Description |
|---|---|
Session
|
tuple[Session, str]: The persisted session and the plaintext |
str
|
id for |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the credentials do not match.
No session is created and |
RuntimeError
|
When the service was built with |
login
async
¶
login(
*,
user_id: UUID,
ip: str | None = None,
user_agent: str | None = None,
previous_session_id: str | None = None,
) -> tuple[Session, str]
Mint a brand-new session for user_id.
When :attr:SessionSettings.SESSION_ROTATE_ON_LOGIN is
True (default) and previous_session_id is provided,
the previous session is evicted before the new one is
issued — closes the session-fixation attack window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
The user the session belongs to. |
required |
ip
|
str | None
|
Client IP (resolve via
:func: |
None
|
user_agent
|
str | None
|
Raw User-Agent header. |
None
|
previous_session_id
|
str | None
|
Plaintext cookie value
of the session being replaced. Pass it when a
request already carries a session cookie — typical
during step-up login. Ignored when
|
None
|
Returns:
| Type | Description |
|---|---|
Session
|
tuple[Session, str]: The persisted session row and the |
str
|
plaintext id to ship via |
tuple[Session, str]
|
is not persisted — losing it means logging the user |
tuple[Session, str]
|
out. |
resolve
async
¶
resolve(session_id_plaintext: str) -> Session | None
Look up + (optionally) refresh a session by its cookie value.
Returns None when the cookie does not match a live
session — middleware / dependencies treat that as
"unauthenticated".
The refresh (last_seen_at and, under SESSION_SLIDING, the
new expires_at) is written through
:meth:SessionStore.touch, which updates the session only while
it still exists. A :meth:revoke or :meth:revoke_all that runs
between this method's read and its write therefore wins: the
write is dropped and the call returns None. A store without
touch (written against the protocol before it existed) falls
back to :meth:SessionStore.set and emits a
:class:DeprecationWarning, because that fallback cannot make
revocation stick.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id_plaintext
|
str
|
Raw cookie value. |
required |
Returns:
| Type | Description |
|---|---|
Session | None
|
Session | None: The resolved session, or |
revoke
async
¶
Invalidate one session by its plaintext id. Idempotent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id_plaintext
|
str
|
The raw identifier from the cookie. |
required |
revoke_all
async
¶
Invalidate every session for user_id. Returns count revoked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner of the sessions. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many sessions were removed. |
list_sessions
async
¶
list_sessions(
user_id: UUID, *, current_session_id_plaintext: str | None = None
) -> list[SessionSummarySchema]
Return public-safe summaries of user_id's sessions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner whose sessions to list. |
required |
current_session_id_plaintext
|
str | None
|
Optional
plaintext cookie of the session resolving the
current request — used to set |
None
|
Returns:
| Type | Description |
|---|---|
list[SessionSummarySchema]
|
list[SessionSummarySchema]: One entry per live |
list[SessionSummarySchema]
|
session, oldest first. |
revoke_by_public_id
async
¶
Revoke one session belonging to user_id via its public id.
The public id is the 32-char prefix of the hashed session
id (see :class:SessionSummarySchema). The match scans the
user's live sessions — fast in practice because users
rarely have more than a handful.
Raises:
| Type | Description |
|---|---|
NotFoundException
|
When no live session of |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner of the sessions. |
required |
public_id
|
str
|
Public id of the session to act on. |
required |
SessionAuthenticator
¶
Bases: Protocol
Verifies a username / password pair and names the session owner.
Implement it to back :class:SessionAuth with something other than
a BaseUserModel table — an environment credential, an LDAP bind,
an upstream API. Both parameters are positional-only, so an
implementation may name them however it likes.
authenticate
async
¶
Return the id the new session belongs to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
The submitted username. |
required |
password
|
str
|
The submitted plaintext password. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
UUID |
UUID
|
The owner stored in :attr: |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the credentials do not match. |
StaticCredentialAuthenticator
¶
StaticCredentialAuthenticator(
username: str, password: str | SecretStr, *, user_id: UUID | None = None
)
Accept exactly one username / password pair, compared in constant time.
Both halves are always compared, each with
:func:hmac.compare_digest over a SHA-256 digest, and the two
results are combined with & rather than and. A wrong
username therefore costs the same as a wrong password, and neither
the timing nor the error message says which half failed.
Only the digests are kept on the instance; the plaintext password is not stored.
Initialize the authenticator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
The accepted username. |
required |
password
|
str | SecretStr
|
The accepted password. A
|
required |
user_id
|
UUID | None
|
Owner written on every session this
credential opens. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
authenticate
async
¶
Verify the pair and return :attr:user_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
The submitted username. |
required |
password
|
str
|
The submitted plaintext password. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
UUID |
UUID
|
:attr: |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When either half differs, with the same message in both cases. |
STATIC_CREDENTIAL_NAMESPACE
module-attribute
¶
STATIC_CREDENTIAL_NAMESPACE: UUID = uuid5(
NAMESPACE_URL,
"https://github.com/mauriciobenjamin700/tempest-fastapi-sdk/sessions/static-credential",
)
UUIDv5 namespace that derives a fixed credential's default user_id.
:class:StaticCredentialAuthenticator without an explicit user_id
uses uuid5(STATIC_CREDENTIAL_NAMESPACE, username), so the id is
stable across restarts and replicas and SessionAuth.revoke_all can
target it.
make_session_router
¶
make_session_router(
service: SessionAuth,
*,
session_factory: Callable[..., AsyncIterator[AsyncSession]],
prefix: str = "/auth/session",
tags: list[str] | None = None,
docs_locale: str | None = None,
) -> APIRouter
Build the bundled session router.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
SessionAuth
|
Configured auth service that talks to the store + verifies passwords against the user model. |
required |
session_factory
|
Callable[..., AsyncIterator[AsyncSession]]
|
FastAPI dependency yielding an async SQLAlchemy session
— typically |
required |
prefix
|
str
|
URL prefix. Defaults to |
'/auth/session'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to
|
None
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
SessionMiddleware
¶
SessionMiddleware(
app: ASGIApp, *, session_auth: SessionAuth, settings: SessionSettings
)
Bases: BaseHTTPMiddleware
ASGI middleware that resolves the session cookie per request.
Attach with::
app.add_middleware(
SessionMiddleware,
session_auth=session_auth,
settings=session_settings,
)
After the middleware runs, every handler in the chain can read
request.state.session — a :class:Session instance when
the cookie was valid, None otherwise. Handlers that require
authentication should depend on
:func:make_session_dependency instead of poking
request.state directly so missing sessions raise a clean
401 envelope.
Initialize the middleware.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
ASGIApp
|
Wrapped ASGI app — Starlette passes this
automatically when used with |
required |
session_auth
|
SessionAuth
|
Configured service used to resolve cookies into sessions. |
required |
settings
|
SessionSettings
|
Read for the cookie name. |
required |
dispatch
async
¶
Resolve the cookie before delegating to the route handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The inbound request. |
required |
call_next
|
Callable[[Request], Awaitable[Response]]
|
The next handler in the middleware chain. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
The downstream response, after this middleware ran. |
make_session_dependency
¶
make_session_dependency(
*,
required: Literal[True] = ...,
session_auth: SessionAuth | SessionAuthFactory | None = ...,
on_missing: MissingSessionHandler | None = ...,
) -> Callable[[Request], Awaitable[Session]]
make_session_dependency(
*,
required: Literal[False],
session_auth: SessionAuth | SessionAuthFactory | None = ...,
on_missing: None = ...,
) -> Callable[[Request], Awaitable[Session | None]]
make_session_dependency(
*,
required: bool,
session_auth: SessionAuth | SessionAuthFactory | None = ...,
on_missing: MissingSessionHandler | None = ...,
) -> Callable[[Request], Awaitable[Session | None]]
make_session_dependency(
*,
required: bool = True,
session_auth: SessionAuth | SessionAuthFactory | None = None,
on_missing: MissingSessionHandler | None = None,
) -> Callable[[Request], Awaitable[Session | None]]
Build a FastAPI dependency that returns the resolved session.
Two ways to find the session:
- Without
session_auththe dependency readsrequest.state.session, which :class:SessionMiddlewarepopulates. Mount the middleware BEFORE you use the dependency, or it always sees no session. - With
session_auththe dependency reads the cookie and resolves it itself (sliding the TTL like the middleware does), so no middleware is needed. Only the routes that declare the dependency pay for the lookup, and a streaming route elsewhere in the app is not wrapped by aBaseHTTPMiddleware. When the middleware did run for the request, its result is reused instead of resolving twice.
session_auth may also be a :data:SessionAuthFactory — a callable
taking the request — for a service whose SessionAuth only exists
once settings are read. The dependency is then declarable at module
level (AdminDep = Annotated[Session, Depends(...)]) before any
SessionAuth is built, and the factory runs per request, only when
the middleware left no session. Two apps in one process — the shape
of tests that clear a settings cache — each resolve against their own.
With required=True (the default) the dependency is typed as
returning Session, not Session | None: it raises instead of
returning None, so a consumer needs no if to narrow the type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
required
|
bool
|
When |
True
|
session_auth
|
SessionAuth | SessionAuthFactory | None
|
Resolve the cookie directly with this service, or with the one the factory returns for the request, instead of relying on the middleware. |
None
|
on_missing
|
MissingSessionHandler | None
|
Builds the exception
to raise when no session resolves — :func: |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Request], Awaitable[Session | None]]
|
Callable[[Request], Awaitable[Session | None]]: An async FastAPI |
Callable[[Request], Awaitable[Session | None]]
|
dependency, typed |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
redirect_to
¶
redirect_to(
url: str, *, status_code: int = HTTP_303_SEE_OTHER
) -> MissingSessionHandler
Build an on_missing handler that redirects to url.
For HTML routes, where a missing session should send the browser to
the login page instead of answering a JSON 401. The dependency
raises an HTTPException carrying the status and a Location
header; FastAPI's handler and the SDK's
:func:register_exception_handlers both keep the header, and the
browser follows it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Where to send the browser, e.g. |
required |
status_code
|
int
|
Redirect status. |
HTTP_303_SEE_OTHER
|
Returns:
| Name | Type | Description |
|---|---|---|
MissingSessionHandler |
MissingSessionHandler
|
A handler for |
MissingSessionHandler
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
redirect_to_login
¶
redirect_to_login(
login_path: str, *, status_code: int = HTTP_303_SEE_OTHER
) -> MissingSessionHandler
Build an on_missing handler that sends the browser to the login.
Unlike :func:redirect_to, it carries the requested path and query
along as ?next=, so the login page can bring the user back. The
login pages of :func:~tempest_fastapi_sdk.make_auth_pages_router
only follow a next that is a path on the same site.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
login_path
|
str
|
The login page, e.g. |
required |
status_code
|
int
|
Redirect status, |
HTTP_303_SEE_OTHER
|
Returns:
| Name | Type | Description |
|---|---|---|
MissingSessionHandler |
MissingSessionHandler
|
A handler for |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
make_session_user_dependency
¶
make_session_user_dependency(
user_model: type[UserT],
session_factory: Callable[..., AsyncIterator[AsyncSession]],
*,
session_auth: SessionAuth | SessionAuthFactory,
on_missing: MissingSessionHandler | None = None,
require_mfa: bool = False,
) -> Callable[..., Awaitable[UserT]]
Build a dependency returning the user of the request's session.
:func:make_session_dependency returns the :class:Session; a page
usually wants the account. This one resolves the cookie, then reloads
the row on the request's DB session — the same provider the routes
use, so the instance stays attached — on every request: an account
deactivated or deleted after the login loses access on its next click,
not when the session expires.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_model
|
type[UserT]
|
The concrete user model. |
required |
session_factory
|
Callable[..., AsyncIterator[AsyncSession]]
|
The request-scoped DB session provider. |
required |
session_auth
|
SessionAuth | SessionAuthFactory
|
Resolves the
cookie, as in :func: |
required |
on_missing
|
MissingSessionHandler | None
|
Exception for no
session, or a session whose account is gone or inactive —
:func: |
None
|
require_mfa
|
bool
|
Also require the session to have passed the
second factor ( |
False
|
Returns:
| Type | Description |
|---|---|
Callable[..., Awaitable[UserT]]
|
Callable[..., Awaitable[UserT]]: An async FastAPI dependency. |
MissingSessionHandler
module-attribute
¶
Builds the exception a session dependency raises when no session resolves.
Receives the request, so the handler can carry the requested path
along (/login?next=...). :func:redirect_to is the bundled one.
SessionAuthFactory
module-attribute
¶
Returns the :class:SessionAuth that resolves a request's cookie.
Called once per request that needs a lookup, never at import — for a
service that builds its SessionAuth from settings at startup
(lambda request: request.app.state.session_auth) or behind a cached
factory the tests reset.
SessionStore
¶
Bases: Protocol
Persistence protocol every session backend implements.
get
async
¶
get(session_id_hash: str) -> Session | None
Return the live session for session_id_hash or None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id_hash
|
str
|
Hash of the session identifier. |
required |
Returns:
| Type | Description |
|---|---|
Session | None
|
Session | None: The live session, or |
set
async
¶
set(session: Session) -> None
Persist (or overwrite) session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The session to persist. |
required |
touch
async
¶
touch(session: Session) -> bool
Overwrite session only when its key still exists.
The read-then-write refresh :meth:SessionAuth.resolve performs
on every request goes through this method, not :meth:set, so a
request that read the session before a concurrent
:meth:delete / :meth:delete_by_user cannot bring it back.
Implementations must make the existence check and the write one
atomic step, and must not add the session to the per-user index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The refreshed session. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
delete
async
¶
Remove a single session. Idempotent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id_hash
|
str
|
Hash of the session identifier. |
required |
delete_by_user
async
¶
Remove every session for user_id. Returns count deleted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner of the sessions. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many sessions were removed. |
list_by_user
async
¶
list_by_user(user_id: UUID) -> list[Session]
Return every live session for user_id (oldest first).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner of the sessions. |
required |
Returns:
| Type | Description |
|---|---|
list[Session]
|
list[Session]: Every live session for the user, oldest first. |
MemorySessionStore
¶
In-process :class:SessionStore for dev, tests, single-replica.
Stores sessions in a dict keyed by their hashed id; a secondary
index by user_id powers list_by_user /
delete_by_user without scanning. Expired rows are pruned on
access — no background task needed.
Initialize the in-memory store.
get
async
¶
get(session_id_hash: str) -> Session | None
Return the live session for session_id_hash or None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id_hash
|
str
|
Hash of the session identifier. |
required |
Returns:
| Type | Description |
|---|---|
Session | None
|
Session | None: The live session, or |
set
async
¶
set(session: Session) -> None
Persist (or overwrite) session.
Notes
A write reusing an existing id under a different owner rewrites both indexes, so the previous owner's index never keeps a dangling entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The session to persist. |
required |
touch
async
¶
touch(session: Session) -> bool
Overwrite session only when its id is still stored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The refreshed session. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
delete
async
¶
Remove a single session. Idempotent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id_hash
|
str
|
Hash of the session identifier. |
required |
delete_by_user
async
¶
Remove every session for user_id. Returns count deleted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner of the sessions. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many sessions were removed. |
list_by_user
async
¶
list_by_user(user_id: UUID) -> list[Session]
Return every live session for user_id (oldest first).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner of the sessions. |
required |
Returns:
| Type | Description |
|---|---|
list[Session]
|
list[Session]: Every live session for the user, oldest first. |
RedisSessionStore
¶
:class:SessionStore backed by an async redis client.
Schema:
- Each session is stored at
{prefix}sess:{hash}as JSON with a TTL set to(expires_at - now)so Redis evicts the key on its own — no janitor process needed. - The user → session index lives at
{prefix}user:{user_id}as a Redis SET of session hashes. Entries are removed ondeleteand the whole SET is dropped ondelete_by_user.
Requires the [cache] extra so the redis async client is
available.
Initialize the Redis-backed store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Redis
|
Async Redis client (e.g.
|
required |
prefix
|
str
|
Key prefix so session keys do not collide with other cached data. |
'tempest:'
|
get
async
¶
get(session_id_hash: str) -> Session | None
Return the live session for session_id_hash or None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id_hash
|
str
|
Hash of the session identifier. |
required |
Returns:
| Type | Description |
|---|---|
Session | None
|
Session | None: The live session, or |
set
async
¶
set(session: Session) -> None
Persist (or overwrite) session with a TTL matching expires_at.
Notes
The user-index TTL is bumped to track the longest-lived session it points at, so the index never expires while a session it references is valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The session to persist. |
required |
touch
async
¶
touch(session: Session) -> bool
Overwrite session only when its key still exists.
Notes
The write is a single SET ... XX, so the existence check
and the update are one atomic Redis command: a key removed
by :meth:delete or :meth:delete_by_user after the caller
read it stays removed. The session is never re-added to the
user index; that index's TTL is only bumped, and EXPIRE
on a missing key is a no-op.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The refreshed session. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
delete
async
¶
Remove a single session. Idempotent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id_hash
|
str
|
Hash of the session identifier. |
required |
delete_by_user
async
¶
Remove every session for user_id. Returns count deleted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner of the sessions. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many sessions were removed. |
list_by_user
async
¶
list_by_user(user_id: UUID) -> list[Session]
Return every live session for user_id (oldest first).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Owner of the sessions. |
required |
Returns:
| Type | Description |
|---|---|
list[Session]
|
list[Session]: Every live session for the user, oldest first. |
Session
¶
Bases: BaseSchema
A live server-side session.
Stored in the configured :class:SessionStore keyed by the
SHA-256 hash of the session id (the plaintext lives only in the
cookie). Mirrors what every session-backed auth flow needs:
user identity, lifetime bounds, originating client metadata for
revocation UX ("you're signed in on Chrome from São Paulo"),
and a free-form data bag for app-level state.
Attributes:
| Name | Type | Description |
|---|---|---|
session_id |
str
|
SHA-256 hex digest of the cookie value —
NOT the plaintext. The plaintext leaves over
|
user_id |
UUID
|
Owner of the session. |
created_at |
datetime
|
UTC timestamp when the session was issued. |
expires_at |
datetime
|
UTC timestamp after which the
session is rejected. Refreshed by
:meth: |
last_seen_at |
datetime
|
UTC timestamp of the last request that resolved the session. Updated by the middleware on every hit. |
ip |
str | None
|
Client IP recorded at session creation. Useful for the "list active sessions" UI. |
user_agent |
str | None
|
User-Agent header recorded at session creation. |
data |
dict[str, Any]
|
Arbitrary JSON-serializable bag — shopping cart id, last-seen route, locale preference, etc. |
amr |
list[str]
|
RFC 8176 authentication methods the session was
opened with — |
SessionLoginSchema
¶
SessionResponseSchema
¶
Bases: BaseSchema
Body returned by POST /auth/session/login.
The session id itself is delivered via Set-Cookie —
deliberately NOT in this body — so JavaScript cannot read it
(HttpOnly cookies). The body carries everything the frontend
actually needs to render an authenticated state.
SessionSummarySchema
¶
Bases: BaseSchema
Public-safe projection of a :class:Session used by list endpoints.
Drops session_id (so revealing the list does NOT leak any
secret) and renames the visible identifier to id — a stable
UUID derived from the hashed session id by truncation, suitable
for DELETE /auth/session/{id} revocation calls.