tempest_fastapi_sdk.auth¶
O fluxo de autenticação embutido: cadastro, ativação, login, reset de senha, JWT, OAuth e MFA TOTP.
UserAuthService
¶
UserAuthService(
*,
user_model: type[BaseUserModel],
token_model: type[BaseUserTokenModel],
auth_settings: AuthSettings,
jwt_settings: JWTSettings,
email: EmailUtils | None = None,
passwords: PasswordUtils | None = None,
jwt: JWTUtils | None = None,
db: AsyncDatabaseManager | None = None,
refresh_token_model: type[BaseUserRefreshTokenModel] | None = None,
oauth_account_model: type[BaseUserOAuthAccountModel] | None = None,
exceptions: AuthExceptions | None = None,
refuses_email_link: Callable[[Any], bool] | None = None,
webauthn_credential_model: type[BaseWebAuthnCredentialModel] | None = None,
)
Compose UserModel + UserTokenModel into a full auth flow.
Example:
>>> service = UserAuthService(
... db=db,
... user_model=UserModel,
... token_model=UserTokenModel,
... auth_settings=settings,
... jwt_settings=settings,
... email=email_utils,
... )
>>> async with db.get_session_context() as s:
... result = await service.signup(s, payload)
The core flow methods take the active AsyncSession explicitly
so callers control the transaction boundary. The only exception is
:meth:load_user (and the :meth:current_user_dependency it backs),
which opens its own short-lived session from the db= handle so
it can serve as a one-argument FastAPI dependency loader.
Initialize the service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_model
|
type[BaseUserModel]
|
Concrete user model
— usually |
required |
token_model
|
type[BaseUserTokenModel]
|
Concrete token
model — usually |
required |
auth_settings
|
AuthSettings
|
The mixin populating activation / reset behavior. |
required |
jwt_settings
|
JWTSettings
|
The mixin populating signing keys and TTLs. |
required |
email
|
EmailUtils | None
|
Configured email helper.
When |
None
|
passwords
|
PasswordUtils | None
|
Override for tests; defaults to a fresh instance. |
None
|
jwt
|
JWTUtils | None
|
Override for tests; defaults
to one built from |
None
|
db
|
AsyncDatabaseManager | None
|
Optional handle for services that open their own sessions inside helpers like background tasks. |
None
|
refresh_token_model
|
type[BaseUserRefreshTokenModel] | None
|
Concrete refresh-token model — usually
|
None
|
oauth_account_model
|
type[BaseUserOAuthAccountModel] | None
|
Concrete linked-identity model — usually
|
None
|
exceptions
|
AuthExceptions | None
|
The class raised at each
refusal point — wrong credentials, inactive account,
taken email, each password-policy violation, invalid
single-use link. Pass your own subclasses to keep the
|
None
|
refuses_email_link
|
Callable[[Any], bool] | None
|
Predicate
deciding, per account, whether the emailed link flows
are closed to it — an operator or staff member whose
mailbox must not be enough to rotate the password or
reactivate the account. Called with the service's own
|
None
|
webauthn_credential_model
|
type[BaseWebAuthnCredentialModel] | None
|
Concrete passkey table — usually
|
None
|
signup
async
¶
signup(
session: AsyncSession,
*,
email: str,
password: str,
name: str | None = None,
fields: Mapping[str, Any] | None = None,
) -> tuple[BaseUserModel, ActivationToken | ActivationWithheld | None]
Create a user row and (optionally) issue an activation token.
The second tuple slot says how the account gets active, and each of its three values means one thing only:
None—AUTH_AUTO_ACTIVATEis true and the user is bornis_active=True; the caller can mint JWTs right away. Therefuses_email_linkpredicate is not consulted, because an account born active depends on no link.- :class:
ActivationToken— the user is inserted withis_active=Falseand an activation token is persisted (and mailed, whenEmailUtilsis wired) for the caller to surface. - :class:
ActivationWithheld— the user is inserted withis_active=Falsebutrefuses_email_linkmatches the new row, so no token is persisted and no mail is sent: the link would only answerEMAIL_LINK_FORBIDDENwhen used. The predicate sees the row as inserted, withfieldsapplied and before anyon_signuphook of the router runs. The caller must not mint JWTs for it, and should answer the way it answers a pending signup, so the refusal cannot be enumerated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
email
|
str
|
Account email — normalized to lowercase. |
required |
password
|
str
|
Plaintext password; length is enforced
against |
required |
name
|
str | None
|
Optional display name; passed through to the model when the column exists. |
None
|
fields
|
Mapping[str, Any] | None
|
Extra column values set on
the new row before the insert, which is what lets a
product fill a |
None
|
Returns:
| Type | Description |
|---|---|
BaseUserModel
|
tuple[BaseUserModel, ActivationToken | ActivationWithheld | None]: |
ActivationToken | ActivationWithheld | None
|
The persisted user and how it gets active — |
tuple[BaseUserModel, ActivationToken | ActivationWithheld | None]
|
active, the token to surface, or the marker that the link was |
tuple[BaseUserModel, ActivationToken | ActivationWithheld | None]
|
withheld. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When |
EmailDeliveryException
|
When the activation mail could not be
sent ( |
ValueError
|
When |
ValidationException
|
When the password is too short. |
ConflictException
|
When the email, or another unique column,
is already taken. For a column other than |
admin_create_user
async
¶
admin_create_user(
session: AsyncSession,
*,
email: str,
password: str,
name: str | None = None,
fields: Mapping[str, Any] | None = None,
is_admin: bool = False,
) -> BaseUserModel
Create an active account with a password chosen by an administrator.
The back-office twin of :meth:signup, for a product where accounts
are born in an admin panel and nobody receives a link: no activation
token is minted, no mail is sent, and therefore
:meth:require_mail_delivery is not consulted — the call works with
the e-mail integration switched off and ENV unset (production).
Everything else is :meth:signup's own path: the e-mail is
normalized, fields is checked against the same protected columns,
the password policy is the same, and a taken e-mail or unique column
raises the same :class:ConflictException.
email_verified_at is left unset: the administrator typed the
address, and nobody proved control of the mailbox. The
refuses_email_link predicate is not consulted, since no link is
involved. The caller is the authority — guard the route that calls
this with :meth:require_admin or the panel's own session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The row is flushed, not committed. |
required |
email
|
str
|
Account e-mail — normalized to lowercase. |
required |
password
|
str
|
Plaintext password, checked against the policy. |
required |
name
|
str | None
|
Optional display name; set when the model has
a |
None
|
fields
|
Mapping[str, Any] | None
|
Extra column values, with the
same rules as |
None
|
is_admin
|
bool
|
Whether the new account is an administrator.
|
False
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The persisted user, |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ValidationException
|
When the password breaks the policy. |
ConflictException
|
When the e-mail, or another unique column, is already taken. |
admin_set_password
async
¶
admin_set_password(
session: AsyncSession,
*,
user_id: UUID,
new_password: str,
revoke_sessions: bool = True,
revoke_passkeys: bool = True,
) -> BaseUserModel
Replace an account's password on an administrator's authority.
The back-office twin of :meth:confirm_password_reset: no token, no
mail, so :meth:require_mail_delivery is not consulted. The new
password goes through the same policy, and the same defaults apply,
because someone other than the owner just chose the password: every
refresh token of the user is revoked (:meth:revoke_user_sessions)
and every passkey is removed (:meth:revoke_user_passkeys), in the
session the caller commits. Access tokens already issued live until
their short TTL ends; stateless refresh tokens (no
refresh_token_model) have no row to revoke. An MFA enrollment is
kept — reset it with :meth:mfa_reset when that is the intent.
The caller is the authority — guard the route that calls this with
:meth:require_admin or the panel's own session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The change is flushed, not committed. |
required |
user_id
|
UUID
|
The account whose password is replaced. |
required |
new_password
|
str
|
Plaintext replacement password. |
required |
revoke_sessions
|
bool
|
Revoke every refresh token of the user
(default). |
True
|
revoke_passkeys
|
bool
|
Delete every WebAuthn credential of the
user (default). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The user whose password was replaced. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When the new password breaks the policy. Raised before the account is read. |
NotFoundException
|
When no user has |
signup_column_names
¶
Return the user_model columns signup(fields=...) accepts.
Every mapped column attribute, minus
:meth:signup_protected_fields. make_auth_router uses it to
forward only those fields of a signup_schema that are columns,
leaving the rest (a terms checkbox, a captcha answer) to
on_signup.
Returns:
| Type | Description |
|---|---|
frozenset[str]
|
frozenset[str]: The assignable column attribute names. |
signup_protected_fields
¶
Return the user_model columns signup(fields=...) refuses.
:data:SIGNUP_PROTECTED_FIELDS plus every column the model declares
in __secret_columns__ along its MRO
(:meth:~tempest_fastapi_sdk.BaseModel.get_secret_columns): a
column the project marks as a secret is a credential, and a sign-up
form never decides a credential.
Returns:
| Type | Description |
|---|---|
frozenset[str]
|
frozenset[str]: The protected column names. |
activate
async
¶
activate(session: AsyncSession, *, token: str) -> BaseUserModel
Consume an activation token and flip is_active on the user.
email_verified_at is stamped too, but only when the link proved
the mailbox — see :meth:_record_email_proof. An activation whose
link came back in the HTTP response activates the account and
leaves the column alone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
token
|
str
|
Plaintext token from the activation URL. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The freshly-activated user. |
Raises:
| Type | Description |
|---|---|
InvalidTokenException
|
When the token is malformed, expired, already used, or doesn't match a row. |
ForbiddenException
|
When |
request_activation
async
¶
request_activation(session: AsyncSession, *, email: str) -> ActivationToken | None
Re-issue the activation link for an inactive account.
The signup email is sent once. When it does not arrive — a typo in
a spam filter, a bounced relay, a closed tab — the account is
stuck: signing up again conflicts on the email, logging in is
refused because the user is inactive, and
:meth:request_email_verification needs a bearer token that only a
successful login hands out. This is the way back in, and it needs
no credentials by design.
"Inactive" includes an account an operator deactivated
(is_active=False, e.g. tempest user deactivate): the link
goes to it too, and opening it makes the account active again.
That is intended — deactivation blocks login, and the holder of
the mailbox can reactivate it on their own. To close the account
for good, match it with the refuses_email_link predicate, which
this flow answers with no token and no mail.
Nothing is leaked about the address. An unknown email, an already
active account and a genuine re-send are indistinguishable to the
caller: all three return None unless the token is meant to be
surfaced, and the route answers 202 either way. An active
account is deliberately not re-activated or re-mailed — the link
would authorize nothing and the mail would only tell a stranger
that the address has an account here. An account the predicate
refuses_email_link matches is answered the same way: no token,
no mail, None.
A mail the SMTP server does not take is answered the same way too:
the :class:~tempest_fastapi_sdk.exceptions.EmailDeliveryException
is logged at ERROR and swallowed, nothing is stored (the
previous link keeps working), and None comes back — a 503
here would exist only for registered pending accounts, which is
the enumeration this flow avoids. See
:meth:_issue_token_after_mail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
email
|
str
|
Account email, matched case-insensitively. |
required |
Returns:
| Type | Description |
|---|---|
ActivationToken | None
|
ActivationToken | None: The token bundle when the caller |
ActivationToken | None
|
surfaces the link ( |
ActivationToken | None
|
|
ActivationToken | None
|
|
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the e-mail integration is
switched off — see :meth: |
login
async
¶
login(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 the body nor the response time
separates the three refusals.
AUTH_REVEAL_INACTIVE_ACCOUNT changes one branch only: the
right password on a deactivated account raises
exceptions.account_inactive (403 ACCOUNT_INACTIVE by
default) instead of the generic refusal, so the owner learns why
they cannot get in. The password is still verified first, so a
wrong one stays the generic refusal and the cost stays one
bcrypt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
email
|
str
|
Login identifier. |
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 ( |
ForbiddenException
|
When |
login_with_oauth
async
¶
login_with_oauth(
session: AsyncSession,
profile: OAuthUser,
*,
locale: str,
link_by_verified_email: bool | None = None,
allow_account_creation: bool | None = None,
) -> tuple[BaseUserModel, str, str]
Resolve a third-party identity to a local user and log them in.
The half of social login the OAuth clients deliberately leave
out: they end at a :class:~tempest_fastapi_sdk.OAuthUser, and
this turns it into a session. Feeding the result through
:meth:issue_token_pair — rather than signing a token by hand
at the call site — is what makes a Google login the same
session as an email login: the same typ claim, the same
opaque refresh token, the same rotation family, the same reuse
detection, the same POST /auth/logout.
Resolution order, and why:
(provider, subject)— the linked identity. This is the only lookup that authenticates. The pair is the provider's own stable id, unique in the account table, and unaffected by the user later changing their email at either end.- Email, when linking is allowed — a first-time identity
whose address already belongs to a local account. Attaches
the identity to that account, but only when the provider
explicitly states it verified the address
(
email_verified is True;Nonemeans the provider said nothing, which is not a yes). This is the branch that converts a provider's word about an email into control of an existing account, so it is off unless asked for twice — once byAUTH_OAUTH_LINK_BY_VERIFIED_EMAIL, once by the provider's own flag. Linking also requires that activating a local account proves mailbox control here, so it is refused underAUTH_AUTO_ACTIVATE,AUTH_RETURN_TOKEN_IN_RESPONSEor a service withoutEmailUtils: there, an active row says nothing about who owns its address. - Creation — an unknown identity with an unknown email.
Creates the user row with the provider's email, the
provider's name (or a localized placeholder) and a generated
password, then links the identity to it. Only when the
provider states it verified the address
(
email_verified is True): the row owns that address from the start, so an unverified claim is refused rather than turned into an account.
A created account is active immediately: the identity
provider performed the verification, as its email_verified
flag states, so re-verifying by email would ask the user to
prove something Google already proved. AUTH_AUTO_ACTIVATE is not consulted
here — a project that wants human approval before first login
turns account creation off and has an administrator create and
link the row.
The generated password is never shown to anyone. The account
owner reaches a password of their own through the ordinary
POST /auth/password-reset/request, which needs no new flow
because the email is already on the row.
This method always issues the pair, amr=["ext"], whether or
not the account has TOTP enrolled. The bundled router no longer
calls it: it calls :meth:authenticate_oauth and asks an enrolled
account for the second factor first. Call it directly only where
that is the decision you want.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. Rows are added and flushed; the caller owns the commit. |
required |
profile
|
OAuthUser
|
The identity the provider returned, normalized by the client. |
required |
locale
|
str
|
Canonical locale for this request, as
:func: |
required |
link_by_verified_email
|
bool | None
|
Override for
|
None
|
allow_account_creation
|
bool | None
|
Override for
|
None
|
Returns:
| Type | Description |
|---|---|
BaseUserModel
|
tuple[BaseUserModel, str, str]: The authenticated user and |
str
|
the |
str
|
shape to what |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the service was built without an
|
OAuthEmailMissingException
|
When the provider returned
no email. The column is |
OAuthEmailTakenException
|
When the email already belongs to another account and linking is not allowed, or this service's activation does not prove mailbox control. |
OAuthEmailUnverifiedException
|
When the provider did not state it verified the address, and the identity would either link to an existing account or create a new one. Deliberately distinct from the one above: that one has a next step for the user, this one has none. |
OAuthRegistrationDisabledException
|
When the identity is unknown and account creation is disabled. |
OAuthAccountInactiveException
|
When the resolved account is inactive. |
authenticate_oauth
async
¶
authenticate_oauth(
session: AsyncSession,
profile: OAuthUser,
*,
locale: str,
link_by_verified_email: bool | None = None,
allow_account_creation: bool | None = None,
) -> BaseUserModel
Resolve a third-party identity to a local user, issuing nothing.
Everything :meth:login_with_oauth does except minting the pair:
the (provider, subject) lookup, the verified-email link, the
account creation, the last_login_at stamps. The bundled router
calls this one so it can ask for the second factor of an account
with TOTP enrolled before any session exists, exactly like
POST /auth/login. See :meth:login_with_oauth for the
resolution order and its reasons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. Rows are added and flushed; the caller owns the commit. |
required |
profile
|
OAuthUser
|
The identity the provider returned, normalized by the client. |
required |
locale
|
str
|
Canonical locale for this request; picks the placeholder display name of a created account. |
required |
link_by_verified_email
|
bool | None
|
Override for
|
None
|
allow_account_creation
|
bool | None
|
Override for
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The authenticated, active user. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the service was built without an
|
OAuthEmailMissingException
|
When the provider returned no email. |
OAuthEmailTakenException
|
When the email belongs to another account and linking is not allowed, or this service's activation does not prove mailbox control. |
OAuthEmailUnverifiedException
|
When the provider did not state it verified the address, on the link or the creation path. |
OAuthRegistrationDisabledException
|
When the identity is unknown and account creation is disabled. |
OAuthAccountInactiveException
|
When the resolved account is inactive. |
list_oauth_accounts
async
¶
list_oauth_accounts(
session: AsyncSession, user: BaseUserModel
) -> list[BaseUserOAuthAccountModel]
Return every identity linked to user.
A user with no links is a user who signed up with a password —
an ordinary state, so this returns [] rather than raising.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The authenticated account. |
required |
Returns:
| Type | Description |
|---|---|
list[BaseUserOAuthAccountModel]
|
list[BaseUserOAuthAccountModel]: The linked identities, |
list[BaseUserOAuthAccountModel]
|
oldest first. Empty when none are linked. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the service was built without an
|
unlink_oauth_account
async
¶
unlink_oauth_account(
session: AsyncSession, user: BaseUserModel, *, provider: str
) -> None
Detach provider from user.
The user keeps their password and every other link, so the account stays reachable — unlinking the only provider on an account whose password was generated leaves the reset flow as the way back in, which is the same door that flow always offered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The row is deleted and flushed; the caller owns the commit. |
required |
user
|
BaseUserModel
|
The authenticated account. |
required |
provider
|
str
|
Provider key to unlink. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the service was built without an
|
OAuthAccountNotLinkedException
|
When that provider is not linked to this user. A single named resource, so 404 is the right answer — unlike the plural listing above. |
request_password_reset
async
¶
request_password_reset(
session: AsyncSession, *, email: str
) -> PasswordResetToken | None
Mint a one-shot reset token for email.
Returns None when no user matches — callers should
still respond 202 to avoid leaking account
existence. Sends the email (when EmailUtils is wired)
or returns the token for inline display per the
AUTH_RETURN_TOKEN_IN_RESPONSE flag. An account the
refuses_email_link predicate matches is answered
exactly like an unknown address: no token is minted, no
mail goes out, and None comes back.
A mail the SMTP server does not take is answered like an
unknown address too: the
:class:~tempest_fastapi_sdk.exceptions.EmailDeliveryException
is logged at ERROR and swallowed, no token is stored (a
previous link keeps working), and None comes back — a
503 only for registered addresses would be an enumeration
oracle. See :meth:_issue_token_after_mail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
email
|
str
|
Account email. |
required |
Returns:
| Type | Description |
|---|---|
PasswordResetToken | None
|
PasswordResetToken | None: The token bundle when the |
PasswordResetToken | None
|
caller is configured to surface the link, |
PasswordResetToken | None
|
when the link is meant to live only in the email. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the e-mail integration is
switched off — see :meth: |
confirm_password_reset
async
¶
confirm_password_reset(
session: AsyncSession,
*,
token: str,
new_password: str,
revoke_sessions: bool = True,
revoke_passkeys: bool = True,
) -> BaseUserModel
Consume a reset token and replace the user's password.
A reset is usually run because the old password is no longer
trusted, so by default every refresh token the user holds is
revoked in the same transaction (:meth:revoke_user_sessions) —
a session opened with the password alone does not survive the
rotation, exactly as in :meth:mfa_confirm. Access tokens
already issued live until their short TTL ends. The bundled
/auth/password-reset/confirm route keeps that default; the
hash is written and the sessions are killed together, so a
failure on either side rolls both back.
Stateless refresh tokens (no refresh_token_model) have no row
to revoke and keep working until they expire.
A reset is account recovery, so every passkey of the user is
removed too (:meth:revoke_user_passkeys): a passkey signs in
without the password, and one registered by whoever held the
account would otherwise outlive the recovery. The owner's own
passkeys go with it and are registered again after the reset. The
authenticated :meth:change_password keeps them — its caller just
proved the current password.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
token
|
str
|
Plaintext token from the reset URL. |
required |
new_password
|
str
|
Plaintext replacement password. |
required |
revoke_sessions
|
bool
|
Revoke every refresh token of the user
(default). |
True
|
revoke_passkeys
|
bool
|
Delete every WebAuthn credential of the
user (default). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The user whose password was rotated. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When the new password breaks the policy. |
InvalidTokenException
|
On bad / expired / spent tokens, and
when the token points to a user that no longer exists —
for the caller that is a link that does not work, as in
:meth: |
ForbiddenException
|
|
change_password
async
¶
change_password(
session: AsyncSession,
*,
user: BaseUserModel,
current_password: str,
new_password: str,
revoke_sessions: bool = True,
) -> BaseUserModel
Replace an authenticated user's password after re-auth.
The "change my own password while logged in" flow: the caller is
already authenticated (the router resolves user from the
bearer token), and must prove ownership by supplying their
current_password before the new one is accepted. No token is
involved — this is distinct from the email-driven reset flow
(:meth:request_password_reset / :meth:confirm_password_reset).
A password is changed because the old one may be known to someone
else, so by default every session of the user is revoked in the
same transaction (:meth:revoke_user_sessions), as in
:meth:confirm_password_reset: a refresh token minted before the
change no longer rotates. That includes the caller's own refresh
token; the bundled POST /auth/password-change issues the caller
a fresh pair after this returns, in the same transaction.
Passkeys are kept: the caller is authenticated and just proved the
current password, so this is not account recovery. Only the
recovery flows (:meth:confirm_password_reset, :meth:mfa_reset)
run :meth:revoke_user_passkeys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The authenticated user (already loaded from the JWT subject). |
required |
current_password
|
str
|
The user's current plaintext password, re-entered for confirmation. |
required |
new_password
|
str
|
The plaintext replacement password. |
required |
revoke_sessions
|
bool
|
Revoke every session of the user
(default). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The user whose password was rotated. |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When |
ValidationException
|
When |
request_email_change
async
¶
request_email_change(
session: AsyncSession, *, user: BaseUserModel, current_password: str, new_email: str
) -> EmailChangeToken | None
Stage a move to new_email for an authenticated user.
The "change my email while logged in" flow, mirroring
:meth:change_password: the caller is already authenticated
(the router resolves user from the bearer token) and proves
ownership with current_password. A single-use EMAIL_CHANGE
token carrying the pending address in its payload is issued, and a
confirmation link is emailed to the new address. The account
email is NOT touched until :meth:confirm_email_change consumes
the token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The authenticated user. |
required |
current_password
|
str
|
The user's current plaintext password, re-entered for confirmation. |
required |
new_email
|
str
|
The address to move to — normalized to lowercase. |
required |
Returns:
| Type | Description |
|---|---|
EmailChangeToken | None
|
EmailChangeToken | None: The token bundle when the caller is |
EmailChangeToken | None
|
configured to surface the link ( |
EmailChangeToken | None
|
or no |
EmailChangeToken | None
|
email. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the e-mail integration is
switched off — see :meth: |
UnauthorizedException
|
When |
ValidationException
|
When |
ConflictException
|
When |
EmailDeliveryException
|
When the confirmation mail could not
be sent ( |
confirm_email_change
async
¶
confirm_email_change(
session: AsyncSession, *, token: str, revoke_sessions: bool = True
) -> BaseUserModel
Consume an EMAIL_CHANGE token and apply the pending address.
Reads the pending new email from the token payload, re-checks it
is still free (an address can be taken between request and
confirm), flips user.email and — when
AUTH_EMAIL_CHANGE_NOTIFY_OLD is on — sends a security notice
to the previous address.
email_verified_at follows the new address: stamped now when
the link reached its holder only by mail to that address
(:meth:_links_prove_mailbox), cleared otherwise, because the
proof the account had belonged to the previous address.
The address is where the password reset goes, so moving it is a
credential change: by default every session of the user is
revoked in the same transaction (:meth:revoke_user_sessions), as
in :meth:confirm_password_reset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
token
|
str
|
Plaintext token from the confirmation link. |
required |
revoke_sessions
|
bool
|
Revoke every session of the user
(default). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The user whose email was changed. |
Raises:
| Type | Description |
|---|---|
InvalidTokenException
|
On bad / expired / spent tokens, a missing payload, or a missing user. |
ConflictException
|
When the target email was taken meanwhile. |
IntegrationDisabledException
|
When
|
EmailDeliveryException
|
When |
request_email_verification
async
¶
request_email_verification(
session: AsyncSession, *, user: BaseUserModel
) -> EmailVerificationToken | None
Issue a re-verification token for the user's CURRENT email.
Resends a "confirm you own this address" link to the account's
existing email — no address change. Confirming it via
:meth:confirm_email_verification marks the user active.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The user re-verifying. |
required |
Returns:
| Type | Description |
|---|---|
EmailVerificationToken | None
|
EmailVerificationToken | None: The token bundle when the |
EmailVerificationToken | None
|
caller surfaces the link, |
EmailVerificationToken | None
|
email. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the e-mail integration is
switched off — see :meth: |
EmailDeliveryException
|
When the mail could not be sent
( |
confirm_email_verification
async
¶
confirm_email_verification(session: AsyncSession, *, token: str) -> BaseUserModel
Consume an EMAIL_VERIFICATION token and mark the user active.
Also stamps email_verified_at when the link proved the
mailbox of the current address — see :meth:_record_email_proof.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
token
|
str
|
Plaintext token from the verification link. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The verified user. |
Raises:
| Type | Description |
|---|---|
InvalidTokenException
|
On bad / expired / spent tokens, or a missing user. |
request_email_recovery
async
¶
request_email_recovery(
session: AsyncSession,
*,
email: str,
new_email: str,
current_password: str,
mfa_code: str | None = None,
recovery_code_model: type[BaseUserRecoveryCodeModel] | None = None,
login_throttle: AttemptThrottle | None = None,
login_ip_throttle: AttemptThrottle | None = None,
client_ip: str | None = None,
mfa_throttle: AttemptThrottle | None = None,
) -> EmailChangeToken | None
Start an email move for a user who lost access to their mailbox.
The unauthenticated recovery entry point. The account is
located by its current (old) email; identity is proven by
current_password and — when the account has MFA enrolled — a
valid mfa_code. On success an EMAIL_CHANGE token is issued
and the confirmation link emailed to the NEW address; confirming
it runs through the same :meth:confirm_email_change path (which
notifies the old address).
To avoid account enumeration this returns None (the router
answers a generic 202) for every soft failure — unknown email,
wrong password, or a missing/invalid MFA code. The only hard error
is a target address already in use, or a deployment that enabled
recovery without wiring recovery_code_model for an MFA user.
The password and the second factor checked here are the same ones
/auth/login and /auth/mfa/verify check, so they spend the
same budgets — otherwise this route would be the way around them.
login_throttle is reserved on
:func:~tempest_fastapi_sdk.utils.throttle.login_throttle_key of
email before the password is checked, and mfa_throttle on
f"mfa:{user_id}" before the code is checked; login_ip_throttle
reserves one slot before anything else, so concurrent guesses
cannot outrun it, and gives it back once the password and code both
matched, as on /auth/login. A spent
budget answers like any other soft failure — None, the generic
202 — whatever the password or code, and never issues a link.
A matching password clears the e-mail key and a matching code the
MFA key, as on the login doors. The bundled router passes its own
throttles; None (default) leaves that budget unchecked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
email
|
str
|
The account's current (old) email. |
required |
new_email
|
str
|
The address to recover the account to. |
required |
current_password
|
str
|
The account password, for identity proof. |
required |
mfa_code
|
str | None
|
TOTP or recovery code, required when the account has MFA enrolled. |
None
|
recovery_code_model
|
type[BaseUserRecoveryCodeModel] | None
|
The project's recovery-code model, needed to verify a
recovery-code |
None
|
login_throttle
|
AttemptThrottle | None
|
The per-e-mail login budget. |
None
|
login_ip_throttle
|
AttemptThrottle | None
|
The per-IP login
budget, keyed |
None
|
client_ip
|
str | None
|
The caller's address, for
|
None
|
mfa_throttle
|
AttemptThrottle | None
|
The per-account second-factor budget. |
None
|
Returns:
| Type | Description |
|---|---|
EmailChangeToken | None
|
EmailChangeToken | None: The token bundle when the caller |
EmailChangeToken | None
|
surfaces the link, |
EmailChangeToken | None
|
identity-proof failure and every spent budget). |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When |
ConflictException
|
When |
IntegrationDisabledException
|
When the e-mail integration is
switched off — see :meth: |
EmailDeliveryException
|
When the confirmation mail could not
be sent ( |
issue_jwt_pair
¶
issue_jwt_pair(
user: BaseUserModel, *, amr: Sequence[str] | None = PASSWORD_AMR
) -> tuple[str, str]
Return a stateless (access, refresh) JWT pair.
Both tokens are signed JWTs with no DB persistence — this is
the legacy issuance path, kept for back-compat and used
whenever refresh_token_model is not wired. When a
refresh-token model is wired, prefer :meth:issue_token_pair,
which mints an opaque DB-backed refresh token instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
BaseUserModel
|
The authenticated user. |
required |
amr
|
Sequence[str] | None
|
RFC 8176 methods the session was
authenticated with, stamped as |
PASSWORD_AMR
|
Returns:
| Type | Description |
|---|---|
str
|
tuple[str, str]: |
str
|
stateless JWTs. |
issue_token_pair
async
¶
issue_token_pair(
session: AsyncSession,
user: BaseUserModel,
*,
family_id: UUID | None = None,
amr: Sequence[str] | None = PASSWORD_AMR,
) -> tuple[str, str]
Issue an (access, refresh) pair, DB-backed when configured.
This is the issuance path the bundled router uses at every login-equivalent step (login / signup-auto-activate / activation / password-reset / mfa-verify). Its shape depends on whether a refresh-token model is wired:
refresh_token_modelset — the access token is a stateless JWT, the refresh token is an opaque value persisted (hashed) as a single-use row.family_idties the new token to a rotation lineage;Nonestarts a fresh family (a brand-new login).refresh_token_modelisNone— falls back to :meth:issue_jwt_pair, the legacy stateless behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The new refresh row is added + flushed (the caller owns the commit). |
required |
user
|
BaseUserModel
|
The authenticated user. |
required |
family_id
|
UUID | None
|
Existing rotation lineage to
attach the new token to. |
None
|
amr
|
Sequence[str] | None
|
RFC 8176 methods the session was
authenticated with. Stamped as |
PASSWORD_AMR
|
Returns:
| Type | Description |
|---|---|
str
|
tuple[str, str]: |
str
|
|
tuple[str, str]
|
on configuration. The plaintext opaque token is surfaced |
tuple[str, str]
|
exactly once; only its hash is persisted. |
refresh_tokens
async
¶
refresh_tokens(
session: AsyncSession, *, refresh_token: str
) -> tuple[BaseUserModel, str, str]
Exchange a valid refresh token for a brand-new (access, refresh) pair.
The password-less counterpart to :meth:login: the caller
proves their identity with the long-lived refresh token
(returned at login / signup / activation / reset / mfa-verify)
instead of an email + password. The resolved user must be
active and a fresh pair is minted — both tokens rotate, so
the caller should persist the new refresh token and discard the
old one.
Behavior depends on whether a refresh-token model is wired:
refresh_token_modelset (DB-backed) — the opaque token is looked up by hash. A token that is unknown, expired or already revoked is rejected with401. Replaying an already-rotated token (used_atset) is treated as a stolen-token signal: the entire family is revoked and the call raises401. On success the presented token is markedused_atand a new opaque token is minted in the same family. The database decides the rotation in one conditionalUPDATE(:meth:_spend_refresh_record), so two concurrent redemptions of one token yield one new pair and one401that revokes the family — never two live descendants.refresh_token_modelisNone(stateless / legacy) — the refresh JWT is decoded and must carry therefreshclaim, so a stolen access token can't be replayed here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
refresh_token
|
str
|
The long-lived refresh token. |
required |
Returns:
| Type | Description |
|---|---|
BaseUserModel
|
tuple[BaseUserModel, str, str]: ``(user, access_token, |
str
|
refresh_token)`` — the resolved user and the new pair. |
Raises:
| Type | Description |
|---|---|
ExpiredTokenException
|
Stateless mode only — when the JWT is
past its |
InvalidTokenException
|
When the token is unknown, malformed, expired, revoked, reused, or not a refresh token (HTTP 401). |
NotFoundException
|
When the subject references no user. |
ForbiddenException
|
When the resolved user is inactive. |
revoke_refresh_token
async
¶
revoke_refresh_token(
session: AsyncSession, *, refresh_token: str, all_sessions: bool = False
) -> None
Revoke a refresh token (logout). Idempotent + best-effort.
Looks the opaque token up by hash and flips revoked_at so
it can no longer be exchanged at POST /auth/refresh, even
before its natural expiry. By default only the token's own
family (the rotation lineage from one login) is revoked;
pass all_sessions=True to kill every active refresh token
the user owns (log out everywhere).
No-op when refresh_token_model is not wired (stateless JWTs
cannot be revoked) and when the token is unknown — the call
never raises so logout endpoints stay idempotent and never leak
whether a token existed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The update is flushed (the caller owns the commit). |
required |
refresh_token
|
str
|
The opaque refresh token to revoke. |
required |
all_sessions
|
bool
|
When |
False
|
revoke_user_sessions
async
¶
Revoke every active session of a user, by id.
The administrative counterpart of :meth:revoke_refresh_token:
logout-everywhere for a user whose token nobody holds — the
account an operator just reset the password of, or one being
locked after a report. Wraps
:func:revoke_user_refresh_tokens with the service's configured
table so the caller needs no model reference of its own, then
runs every revoker in :attr:session_revokers — the cookie
sessions :func:~tempest_fastapi_sdk.auth.make_auth_pages_router
opens are registered there (:meth:add_session_revoker), so a
password reset, password change or e-mail change ends them too.
Without refresh_token_model no refresh row is revoked, since
stateless JWT refresh tokens carry no server-side row to flip;
those keep working until they expire.
The revokers act on their own store as they run, outside the database transaction: a rollback afterwards does not bring a revoked cookie session back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The update is flushed (the caller owns the commit). |
required |
user_id
|
UUID
|
Owner whose sessions are being killed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many refresh-token rows were revoked, plus what each |
int
|
revoker reported. |
revoke_user_passkeys
async
¶
Delete every WebAuthn credential of a user, by id.
The passkey counterpart of :meth:revoke_user_sessions. A passkey
signs in without the password and without the second factor, so
recovering an account has to remove the ones registered while
somebody else held it — there is no telling them apart from the
owner's, so all of them go. :meth:confirm_password_reset and
:meth:mfa_reset call this by default; the authenticated
:meth:change_password and :meth:mfa_disable do not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The delete is flushed (the caller owns the commit), so a rollback brings the credentials back. |
required |
user_id
|
UUID
|
Owner whose passkeys are deleted. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many credential rows were deleted — |
int
|
|
add_session_revoker
¶
Register a store of sessions that :meth:revoke_user_sessions ends.
A session that is not a refresh-token row — the opaque cookie of
:class:~tempest_fastapi_sdk.sessions.SessionAuth — is invisible to
the refresh table, so a password reset would leave it alive.
:func:~tempest_fastapi_sdk.auth.make_auth_pages_router registers
its session_auth.revoke_all here; register your own when you
open sessions over this service some other way. Registering the
same callable twice keeps one entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
revoker
|
Callable[[UUID], Awaitable[int]]
|
Called with the user id; ends every session of that user and returns how many it ended. |
required |
get_user
async
¶
get_user(subject: str | UUID, session: AsyncSession) -> BaseUserModel
Resolve a JWT subject (the user id) to the persisted user.
Session-explicit twin of :meth:load_user — use it when the
caller already owns a session (matches the rest of the
service's API, where every method takes the AsyncSession).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject
|
str | UUID
|
The JWT |
required |
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The loaded user. |
Raises:
| Type | Description |
|---|---|
NotFoundException
|
When the subject is malformed or no user with that id exists. |
load_user
async
¶
load_user(subject: str) -> BaseUserModel
Resolve a JWT subject to a user, opening the service's own session.
This is the single-argument async callable that
:func:tempest_fastapi_sdk.make_jwt_user_dependency expects, so
a project can wire the authenticated-user dependency without
hand-writing a loader:
>>> get_current_user = auth_service.current_user_dependency()
Requires the service to have been built with db= so it can
open a session on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject
|
str
|
The JWT |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The loaded user. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the service was created without |
NotFoundException
|
When no user with that id exists. |
current_user_dependency
¶
current_user_dependency(
*,
soft: bool = False,
session_dependency: Callable[..., Any] | None = None,
cookie_name: str | None = None,
query_param: str | None = None,
strict: bool = False,
legacy_claims: Collection[str] = (),
require_active: bool = True,
inactive_exception: GuardException | None = None,
unauthorized_message: str = MISSING_TOKEN_MESSAGE,
) -> Callable[..., Coroutine[Any, Any, Any]]
Build a FastAPI dependency that returns the authenticated user.
Wraps :func:tempest_fastapi_sdk.make_jwt_user_dependency with
this service's own :class:JWTUtils and :meth:get_user, so
the bearer token is verified with the same secret the
service signs with — there is no second JWTUtils to keep in
sync. Mount it on any of your routes:
>>> get_current_user = auth_service.current_user_dependency()
>>> get_current_user_or_none = auth_service.current_user_dependency(
... soft=True
... )
The authenticated user is loaded on the request-scoped
session (self.db.session_dependency by default), so it is
attached to the same session the request's repositories use and
can be mutated / refreshed without an
InvalidRequestError: Instance is not persistent within this
Session. If your repositories depend on a different session
callable (e.g. a project-local get_session wrapper), pass it
as session_dependency so both resolve to the same request
session — FastAPI caches a sub-dependency by its callable, so a
distinct wrapper would open a second session and detach the user.
Requires the service to have been built with db=.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
soft
|
bool
|
When |
False
|
session_dependency
|
Callable[..., Any] | None
|
The
request-scoped session provider to share with
repositories. Defaults to |
None
|
cookie_name
|
str | None
|
Cookie to read the access token
from when the |
None
|
query_param
|
str | None
|
Query-string parameter to read the
access token from when both the |
None
|
strict
|
bool
|
Refuse a token that carries no recognizable
type marker. |
False
|
legacy_claims
|
Collection[str]
|
Extra claim names to read
the token type from when |
()
|
require_active
|
bool
|
Refuse a token whose account is no
longer active (default |
True
|
inactive_exception
|
GuardException | None
|
Factory for the
refusal of an inactive account. |
None
|
unauthorized_message
|
str
|
|
MISSING_TOKEN_MESSAGE
|
Returns:
| Type | Description |
|---|---|
Callable[..., Coroutine[Any, Any, Any]]
|
Callable[..., Coroutine[Any, Any, Any]]: An async FastAPI |
Callable[..., Coroutine[Any, Any, Any]]
|
dependency yielding the user (or |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the service was created without |
sse_router
¶
sse_router(
broker: SSEBroker | Callable[[Request], SSEBroker],
*,
session_dependency: Callable[..., Any] | None = None,
strict: bool = False,
legacy_claims: Collection[str] = (),
allow_access_token_query: bool = False,
access_token_param: str = "access_token",
channel_for: Callable[[Any], str] | None = None,
prefix: str = "/sse",
tag: str = "SSE",
ticket_ttl: timedelta | None = None,
ticket_param: str = "ticket",
) -> APIRouter
Build the authenticated SSE router for this service's users.
Wires :func:~tempest_fastapi_sdk.make_sse_router to the service:
POST <prefix>/ticket is guarded by
:meth:current_user_dependency (header or the login cookie, active
account), the ticket is signed with this service's jwt, and
GET <prefix>/stream also accepts Authorization: Bearer for a
client that can send it.
The browser opens the stream in two steps::
const { ticket } = await api.post("/sse/ticket");
const events = new EventSource(`/sse/stream?ticket=${ticket}`);
allow_access_token_query=True additionally accepts the access
token itself as ?access_token= on the stream — the shape a
client written against current_user_dependency(query_param=...)
already sends. It exists so that client keeps working while it
moves to the ticket; the access token in the URL authorizes every
route until it expires, so turn it off once nothing sends it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
broker
|
SSEBroker | Callable[[Request], SSEBroker]
|
The broker, or a factory called with each request. |
required |
session_dependency
|
Callable[..., Any] | None
|
The
request-scoped session provider shared with repositories;
see :meth: |
None
|
strict
|
bool
|
Refuse access tokens without a type marker; see
:meth: |
False
|
legacy_claims
|
Collection[str]
|
Extra claims naming a legacy
token's type; see :meth: |
()
|
allow_access_token_query
|
bool
|
Also open the stream with the
access token in |
False
|
access_token_param
|
str
|
Query parameter read when
|
'access_token'
|
channel_for
|
Callable[[Any], str] | None
|
Maps the user to its
broker channel. |
None
|
prefix
|
str
|
URL prefix. Defaults to |
'/sse'
|
tag
|
str
|
OpenAPI tag. Defaults to |
'SSE'
|
ticket_ttl
|
timedelta | None
|
Ticket lifetime. |
None
|
ticket_param
|
str
|
Query parameter of the ticket. Defaults to
|
'ticket'
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
The router, ready for |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the service was created without |
ValueError
|
When |
inactive_account_error
¶
inactive_account_error() -> ForbiddenException
Build the refusal for an account that is no longer active.
One factory for every place the service refuses an inactive
account it has already identified — login under
AUTH_REVEAL_INACTIVE_ACCOUNT, :meth:refresh_tokens,
:meth:current_user_dependency and the authenticated routes of
make_auth_router — so the
code a client sees does not depend on which of them caught it.
Returns:
| Name | Type | Description |
|---|---|---|
ForbiddenException |
ForbiddenException
|
|
ForbiddenException
|
|
require_authenticated
staticmethod
¶
require_authenticated(
user: UserT | None, *, exception: GuardException | None = None
) -> UserT
Assert the user is authenticated; return it narrowed to non-None.
Thin static mirror of
:func:tempest_fastapi_sdk.require_authenticated so a service
already in scope can guard without an extra import:
>>> user = auth_service.require_authenticated(current)
Deliberately narrower than the function it forwards to: that one
takes an unbound SubjectT, because the SDK also hands out
subjects that are not user models (a FirebaseIdentity, for one).
Reached through this service the subject is always the service's own
UserT, so keeping the bound here buys back the checking the free
function had to give up. Guarding a provider identity calls the
function directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
UserT | None
|
The resolved request user. |
required |
exception
|
GuardException | None
|
Factory for the refusal.
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UserT |
UserT
|
The same user, narrowed to non- |
Raises:
| Type | Description |
|---|---|
AppException
|
When |
require_active
staticmethod
¶
require_active(
user: UserT | None,
*,
exception: GuardException | None = None,
unauthenticated: GuardException | None = None,
) -> UserT
Assert the user is authenticated and active. See :func:require_active.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
UserT | None
|
The resolved request user. |
required |
exception
|
GuardException | None
|
Factory for the refusal
when |
None
|
unauthenticated
|
GuardException | None
|
Factory for the
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UserT |
UserT
|
The authenticated, active user. |
Raises:
| Type | Description |
|---|---|
AppException
|
When |
require_admin
staticmethod
¶
require_admin(
user: UserT | None,
*,
exception: GuardException | None = None,
unauthenticated: GuardException | None = None,
) -> UserT
Assert the user is authenticated and an admin. See :func:require_admin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
UserT | None
|
The resolved request user. |
required |
exception
|
GuardException | None
|
Factory for the refusal
when |
None
|
unauthenticated
|
GuardException | None
|
Factory for the
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UserT |
UserT
|
The authenticated admin user. |
Raises:
| Type | Description |
|---|---|
AppException
|
When |
email_link_refused
¶
email_link_refused(user: BaseUserModel) -> bool
Return whether the emailed link flows are closed for user.
The gate behind refuses_email_link: :meth:signup (when it
would mint the first activation link) and every request and
confirm method that would mint or spend an activation or
password-reset link ask here first, and so does the backend-rendered reset form
(AUTH_BACKEND_LINKS=True), which only peeks the token and
would otherwise show a form whose submit is bound to fail. The
argument is the service's own user_model instance, which is
what the configured predicate was written against.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
BaseUserModel
|
The account the link points at. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
|
peek_token
async
¶
peek_token(
session: AsyncSession, *, token: str, purpose: UserTokenPurposeEnum
) -> tuple[BaseUserTokenModel, BaseUserModel]
Validate a token + load its user without consuming it.
Mirrors :meth:_consume_token (raises on
invalid/expired/already-used tokens) but leaves
used_at untouched — used by GET endpoints in
backend-only mode that need to render a page (e.g. the
password-reset form) before the user actually submits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
token
|
str
|
Plaintext token. |
required |
purpose
|
UserTokenPurposeEnum
|
Expected token purpose. |
required |
Returns:
| Type | Description |
|---|---|
BaseUserTokenModel
|
tuple[BaseUserTokenModel, BaseUserModel]: The token |
BaseUserModel
|
record and its associated user. |
Raises:
| Type | Description |
|---|---|
InvalidTokenException
|
On unknown / already-used / expired tokens. |
NotFoundException
|
When the token references a user that no longer exists. |
require_mail_delivery
¶
Refuse an operation whose e-mail could never go out.
The flows that hand a link by e-mail (signup without
AUTH_AUTO_ACTIVATE, activation re-send, password reset, e-mail
change and verification, e-mail recovery) call this before
reading or writing anything. With the e-mail integration switched
off (an :class:EmailUtils built with enabled=False, which is
what EmailUtils(**settings.email_kwargs()) gives under
EMAIL_ENABLED=false) the request is answered 503
INTEGRATION_DISABLED and nothing is created: an account whose
activation link can never arrive is never inserted, and a reset
request never mints a token nobody receives.
Nothing is refused when no mail would be sent anyway — no
EmailUtils wired, or AUTH_RETURN_TOKEN_IN_RESPONSE on for
a flow whose link travels in the response. A mailer without an
enabled attribute (a test double written before the flag
existed) counts as enabled.
The check runs before the account lookup, so a refused reset answers the same for a known and an unknown address.
Unless ENV is development or test (read from
auth_settings when it composes
:class:~tempest_fastapi_sdk.settings.EnvironmentSettings, from the
ENV environment variable otherwise; unset counts as production),
a flow carrying a link is refused the same way whenever the link
would travel in the response body instead of the mail — no
EmailUtils wired, or AUTH_RETURN_TOKEN_IN_RESPONSE on. Those
are development conveniences: in production they hand a reset or
activation link to whoever typed the address. The production guard
refuses the flag at boot; this covers the missing mailer, which is
a constructor argument no settings guard can see.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
carries_token
|
bool
|
|
True
|
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the wired mailer is
disabled and the operation would need it, or outside
|
is_mfa_enrolled
¶
is_mfa_enrolled(user: BaseUserModel) -> bool
Return True when user has finished MFA enrollment.
Checks both totp_enabled_at and the global kill-switch
:attr:AuthSettings.AUTH_MFA_ENABLED — when the kill-switch
is off, every user is treated as unenrolled so the login
flow stays single-step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
BaseUserModel
|
The user to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether the condition holds for that user. |
issue_mfa_token
¶
issue_mfa_token(
user: BaseUserModel, *, amr: Sequence[str] | None = PASSWORD_AMR
) -> str
Mint the short-lived JWT that bridges step 1 and step 2 of login.
The token proves the first step only. Its typ claim keeps a
route guard from accepting it as an access token, which would let a
caller who knows just the password skip the second factor
entirely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
BaseUserModel
|
The user to inspect. |
required |
amr
|
Sequence[str] | None
|
RFC 8176 methods the first step
proved — :data: |
PASSWORD_AMR
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The generated value. |
second_factor_amr
¶
Return the amr of the session /auth/mfa/verify opens.
The first-step methods recorded in mfa_token by
:meth:issue_mfa_token, followed by otp — so a password login
becomes :data:~tempest_fastapi_sdk.MFA_AMR (["pwd", "otp"]), a
social login ["ext", "otp"] and an emailed link
["email", "otp"]. Each value names a method that actually ran,
which is what RFC 8176 asks of the claim. A token minted without
the claim (by an issue_mfa_token override written before it
existed) falls back to ["pwd"] as the first step, the
behavior of every release before this one.
Call it only after :meth:mfa_verify accepted the token: it
decodes without re-checking the purpose.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mfa_token
|
str
|
The token :meth: |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
tuple[str, ...]: The methods to stamp on the new pair. |
mfa_enroll
async
¶
mfa_enroll(
session: AsyncSession,
*,
user: BaseUserModel,
recovery_code_model: type[BaseUserRecoveryCodeModel],
) -> tuple[str, str, list[str]]
Issue a fresh TOTP secret + recovery codes for user.
totp_enabled_at is NOT set yet; the caller MUST
confirm a valid code via :meth:mfa_confirm before MFA is
actually active. Until then, the persisted secret is dead
weight and login keeps working without the TOTP step.
Refused once MFA is active (totp_enabled_at set): enrolling
wipes the recovery codes, so allowing it over an active factor
would let a bare access token switch MFA off without the
password and code that :meth:mfa_disable requires. Rotation
is :meth:mfa_disable followed by a new enroll and confirm.
Calling it again while the previous enrollment is still
pending (never confirmed) is allowed and replaces the staged
secret and codes. The check reads the column, not
:meth:is_mfa_enrolled, so it holds even with the
AUTH_MFA_ENABLED kill-switch off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The user enrolling. |
required |
recovery_code_model
|
type[BaseUserRecoveryCodeModel]
|
The
project's concrete subclass of
:class: |
required |
Returns:
| Type | Description |
|---|---|
str
|
tuple[str, str, list[str]]: ``(secret, provisioning_uri, |
str
|
recovery_codes_plaintext)`` — show all three to the user |
list[str]
|
EXACTLY ONCE. The SDK persists only the hash of each |
tuple[str, str, list[str]]
|
recovery code. |
Raises:
| Type | Description |
|---|---|
MFAAlreadyEnrolledException
|
When MFA is already active for
|
TypeError
|
When |
ImportError
|
When the |
Notes
Enrolling over a pending enrollment wipes the recovery codes it staged, so an old code set never stays valid alongside a new one.
mfa_confirm
async
¶
mfa_confirm(
session: AsyncSession,
*,
user: BaseUserModel,
code: str,
revoke_sessions: bool = True,
) -> None
Mark MFA as active after the user proves they can read the QR.
Turning MFA on is the moment a user suspects someone else has the
password, so by default every refresh token the user holds is
revoked in the same transaction (:meth:revoke_user_sessions): a
session opened with the password alone, before the factor existed,
does not get to keep refreshing past it. Access tokens already
issued live until their short TTL ends, and carry amr ==
["pwd"], so :func:~tempest_fastapi_sdk.make_mfa_required_dependency
refuses them meanwhile. The bundled /auth/mfa/confirm route then
issues the caller a fresh pair with
:data:~tempest_fastapi_sdk.MFA_AMR, so the device that confirmed
stays signed in.
Stateless refresh tokens (no refresh_token_model) have no row to
revoke and keep working until they expire — but they carry the
amr of the login that minted them, so they never mint an MFA
token either.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The user finishing enrollment. |
required |
code
|
str
|
6-digit code from the Authenticator app. |
required |
revoke_sessions
|
bool
|
Revoke every refresh token of the user
(default). |
True
|
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the code does not match the pending secret, or when its step was already spent (no MFA enrollment happens either way). |
ValidationException
|
When no secret is staged (caller
must run :meth: |
Notes
The accepted step is stored in totp_last_step, so the
code that proves the QR was read cannot be spent again at
/auth/mfa/verify — the first login needs a later step.
reauthenticate
async
¶
reauthenticate(
session: AsyncSession,
*,
user: BaseUserModel,
current_password: str,
code: str | None = None,
recovery_code_model: type[BaseUserRecoveryCodeModel] | None = None,
throttle: AttemptThrottle | None = None,
) -> BaseUserModel
Demand fresh proof of the account's factors before a sensitive change.
A bearer access token proves that someone holds a session, not that the account owner is at the keyboard: a token read from a log, a shared device or a script injected into the page carries the same authority. Operations that add a lasting way into the account — registering a passkey is the one the bundled router guards with this — must not be reachable with the token alone, or a short-lived leak becomes a credential that outlives the token, a password reset and a later TOTP enrollment.
The password is checked first, against the stored hash, as
:meth:change_password does. When the account has TOTP enrolled
(:meth:is_mfa_enrolled) the second factor is required too and is
spent like at login: a TOTP step is recorded, a recovery code is
stamped used_at. An account without MFA is asked for the
password only, and code is ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The caller owns the commit. |
required |
user
|
BaseUserModel
|
The authenticated account. |
required |
current_password
|
str
|
The account's plaintext password. |
required |
code
|
str | None
|
A 6-digit TOTP code or a recovery code; required when the account has MFA enrolled. |
None
|
recovery_code_model
|
type[BaseUserRecoveryCodeModel] | None
|
The project's concrete recovery-code model. |
None
|
throttle
|
AttemptThrottle | None
|
Failure budget for the
second factor, keyed on |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The account, attached to |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the password does not match, or
when MFA is enrolled and |
MfaThrottledException
|
When |
mfa_disable
async
¶
mfa_disable(
session: AsyncSession,
*,
user: BaseUserModel,
password: str,
code: str,
recovery_code_model: type[BaseUserRecoveryCodeModel],
) -> None
Disable MFA — requires password + active TOTP/recovery code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The user disabling MFA. |
required |
password
|
str
|
Plaintext password — re-verified. |
required |
code
|
str
|
Active TOTP or single-use recovery code. A TOTP
code whose step was already accepted (by
:meth: |
required |
recovery_code_model
|
type[BaseUserRecoveryCodeModel]
|
The project's concrete recovery-code model — needed because disabling MFA wipes every code. |
required |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
On wrong password OR invalid code. |
ValidationException
|
When MFA is not active in the first place. |
mfa_reset
async
¶
mfa_reset(
session: AsyncSession,
*,
user: BaseUserModel,
recovery_code_model: type[BaseUserRecoveryCodeModel],
revoke_sessions: bool = True,
revoke_passkeys: bool = True,
) -> int
Switch MFA off for user without proof of the factor.
The operator's recovery path for an account whose owner lost both
the authenticator and the recovery codes: :meth:mfa_disable cannot
help them, because it asks for exactly what they lost. Nothing here
is verified — no password, no code — so it belongs behind an
operator boundary (tempest user mfa-reset, an admin action),
never on a route the account holder reaches. The caller owns the
commit and should record an audit event in the same transaction.
The secret, totp_enabled_at and totp_last_step are cleared
and every recovery code of the user is deleted, exactly as
:meth:mfa_disable does after its checks. The check for an active
factor reads the column, not :meth:is_mfa_enrolled, so it holds
with the AUTH_MFA_ENABLED kill-switch off.
Being account recovery, it also deletes every passkey of the user by
default (:meth:revoke_user_passkeys), as
:meth:confirm_password_reset does: a passkey registered by
whoever held the lost device would otherwise keep signing in.
:meth:mfa_disable, where the owner proves password and code, keeps
both the sessions and the passkeys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. The changes are flushed, not committed. |
required |
user
|
BaseUserModel
|
The user whose second factor is removed. |
required |
recovery_code_model
|
type[BaseUserRecoveryCodeModel]
|
The
project's concrete recovery-code model, whose rows for
|
required |
revoke_sessions
|
bool
|
Revoke every refresh token of the user
through :meth: |
True
|
revoke_passkeys
|
bool
|
Delete every WebAuthn credential of the
user (default). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many refresh-token rows were revoked — |
int
|
|
Raises:
| Type | Description |
|---|---|
ValidationException
|
When MFA is not active for |
mfa_verify
async
¶
mfa_verify(
session: AsyncSession,
*,
mfa_token: str,
code: str,
recovery_code_model: type[BaseUserRecoveryCodeModel],
throttle: AttemptThrottle | None = None,
) -> BaseUserModel
Step 2 of two-step login — swap the intermediate token for JWTs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
mfa_token
|
str
|
Intermediate JWT issued by step 1. |
required |
code
|
str
|
6-digit TOTP code OR plaintext recovery code from enrollment. |
required |
recovery_code_model
|
type[BaseUserRecoveryCodeModel]
|
The project's concrete recovery-code model. |
required |
throttle
|
AttemptThrottle | None
|
Failure budget keyed on
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The fully authenticated user — caller |
BaseUserModel
|
mints the JWT pair next. |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
On bad / expired |
MfaThrottledException
|
When |
Notes
A TOTP code is single-use: the accepted step is written to
totp_last_step in one conditional UPDATE, and a code
whose step is at or below it is refused — so a code seen in
transit is not worth a second login inside its drift window,
even from a session that loaded the row before it was spent.
Recovery codes were already single-use (used_at).
change_password_with_mfa
async
¶
change_password_with_mfa(
session: AsyncSession,
*,
user: BaseUserModel,
code: str,
new_password: str,
recovery_code_model: type[BaseUserRecoveryCodeModel] | None = None,
revoke_sessions: bool = True,
throttle: AttemptThrottle | None = None,
) -> BaseUserModel
Replace the password of an MFA account on proof of the second factor.
The path for the account whose reset e-mail cannot be reached (or
must not be trusted) while its owner still holds the authenticator
app or a recovery code: the factor is the proof, in place of the
current password :meth:change_password asks for and of the link
:meth:confirm_password_reset consumes.
The checks run cheapest-first and the factor is spent last: the
account must have MFA active, then the new password must pass the
policy, and only then is code verified — so a password the
policy refuses never burns a recovery code. code is checked by
the same routine :meth:mfa_verify and :meth:mfa_disable use: a
TOTP code is single-use (its step is recorded) and a recovery code
is stamped used_at.
Unlike :meth:mfa_verify this is not a login: no token pair is
minted and last_login_at is left alone. By default every refresh
token of the user is revoked in the same transaction
(:meth:revoke_user_sessions), as in :meth:confirm_password_reset.
The caller owns the commit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The account whose password is replaced. |
required |
code
|
str
|
A 6-digit TOTP code, or one of the plaintext recovery codes handed out at enrollment. |
required |
new_password
|
str
|
Plaintext replacement password. |
required |
recovery_code_model
|
type[BaseUserRecoveryCodeModel] | None
|
The project's concrete recovery-code model. |
None
|
revoke_sessions
|
bool
|
Revoke every refresh token of the user
(default). |
True
|
throttle
|
AttemptThrottle | None
|
Failure budget, keyed on
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The user whose password was rotated. |
Raises:
| Type | Description |
|---|---|
MFANotEnrolledException
|
When the account has no active
second factor (or the |
ValidationException
|
When |
MfaThrottledException
|
When |
UnauthorizedException
|
When |
revoke_user_refresh_tokens
async
¶
revoke_user_refresh_tokens(
session: AsyncSession,
refresh_token_model: type[BaseUserRefreshTokenModel],
*,
user_id: UUID,
) -> int
Revoke every still-active refresh token one user owns.
"Log out everywhere", addressed by user id rather than by a
presented token — the shape an administrator needs. Rotating a
credential out of band (an operator resetting a password from the
CLI, a support agent locking a compromised account) leaves every
already-issued refresh token exchangeable until its natural expiry,
which is exactly the window the reset exists to close, and
:meth:UserAuthService.revoke_refresh_token cannot close it because
it starts from a token the operator does not have.
Rows already carrying a revoked_at are left untouched, so the
returned count is the number of sessions this call actually killed
and calling twice reports 0 the second time.
The update is flushed, never committed — the caller owns the transaction, so the revocation lands or rolls back together with whatever else it is changing (the new password hash, typically).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
refresh_token_model
|
type[BaseUserRefreshTokenModel]
|
The project's concrete refresh-token table. |
required |
user_id
|
UUID
|
Owner whose sessions are being killed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many refresh-token rows were revoked. |
SIGNUP_PROTECTED_FIELDS
module-attribute
¶
SIGNUP_PROTECTED_FIELDS: frozenset[str] = frozenset(
{
"id",
"email",
"hashed_password",
"is_active",
"is_admin",
"email_verified_at",
"totp_secret",
"totp_enabled_at",
"totp_last_step",
"last_login_at",
"created_at",
"updated_at",
"deleted_at",
"created_by",
"updated_by",
}
)
User columns signup(fields=...) refuses to set.
The service owns each of them: email is normalized and checked for
duplicates, hashed_password comes from the policy-checked password,
is_active from AUTH_AUTO_ACTIVATE, email_verified_at from a
confirmed mailed link, and the :class:~tempest_fastapi_sdk.MFAMixin
columns (totp_secret, totp_enabled_at, totp_last_step) from the
enrollment flow, which proves the authenticator holds the secret before the
factor turns on. is_admin and id are never something a sign-up form
decides, and neither are the bookkeeping columns the SDK models keep:
last_login_at (written by login), created_at / updated_at (the
database clock), deleted_at (:class:~tempest_fastapi_sdk.SoftDeleteMixin
-- a row born deleted hides itself from every query) and created_by /
updated_by (:class:~tempest_fastapi_sdk.AuditMixin, which would let a
sign-up claim another principal authored it). On top of this set, every
column the user model declares in
__secret_columns__ (:meth:~tempest_fastapi_sdk.BaseModel.get_secret_columns)
is refused too, so a credential column a project adds is covered without
editing this list. make_auth_router drops them from a signup_schema
before forwarding, so a schema field named is_admin cannot reach the
row.
IntrospectionAuth
¶
IntrospectionAuth(
*,
userinfo_url: str | Callable[[], str],
cache_ttl_seconds: int = 30,
required_app: str | None = None,
app_claim: str = "access_apps",
subject_claim: str = "sub",
timeout: float = 10.0,
http_client: AsyncClient | None = None,
audiences: Collection[str] = (),
)
Validate opaque bearer tokens against an upstream userinfo endpoint.
The instance keeps an in-process cache keyed by the raw token, with a
time-to-live measured on :func:time.monotonic. Successful lookups are
cached; 401 / 403 responses evict the token immediately. The
cache and the HTTP client are per-instance, so distinct upstreams get
distinct :class:IntrospectionAuth objects with isolated state.
Attributes:
| Name | Type | Description |
|---|---|---|
cache_ttl_seconds |
int
|
How long a successful userinfo lookup stays
cached, in seconds. |
required_app |
str | None
|
When set, the value that must be present in the application-membership claim for access to be granted. |
app_claim |
str
|
Name of the claim holding the list of applications the subject may access. |
subject_claim |
str
|
Name of the claim holding the subject
identifier (parsed as a :class: |
audiences |
frozenset[str]
|
The client ids / audiences this service answers to. Empty means the bearer is not bound to the service. |
Initialize the introspection authenticator.
A 200 from the userinfo endpoint proves the token is valid at
the identity provider, not that it was issued to this service:
a provider that answers for tokens of every client it serves would
let a token the user granted to another application authenticate
here. audiences closes that: given, the response must name one
of them in aud (a string or a list), azp or client_id,
or the request answers 401. Left empty, behaviour is unchanged
and a warning is logged here, once per instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
userinfo_url
|
str | Callable[[], str]
|
The upstream userinfo / introspection URL, or a zero-argument callable returning it. A callable is resolved on every call, so a settings property may be passed and picked up lazily / per request. |
required |
cache_ttl_seconds
|
int
|
Seconds to cache a successful lookup.
|
30
|
required_app
|
str | None
|
When provided, the caller's
|
None
|
app_claim
|
str
|
Claim name holding the list of accessible
applications. Defaults to |
'access_apps'
|
subject_claim
|
str
|
Claim name holding the subject id. Defaults
to |
'sub'
|
timeout
|
float
|
Total timeout, in seconds, applied to each
upstream request via :class: |
10.0
|
http_client
|
AsyncClient | None
|
An optional pre-built
client to use instead of the lazily-created shared one. When
provided, the instance does not own its lifecycle. Defaults
to |
None
|
audiences
|
Collection[str]
|
The client ids / audiences this
service answers to. A bare string counts as one audience;
empty strings are ignored. Defaults to |
()
|
fetch_userinfo
async
¶
Fetch and cache the userinfo claims for a bearer token.
On a cache hit within the TTL the upstream is not contacted. On a
cache miss the configured userinfo URL is called with the token as a
bearer credential; a 200 response whose audience passes
:attr:audiences is cached and returned. A response that fails the
audience check is never cached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The raw opaque bearer token to validate. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The claims returned by the upstream userinfo |
dict[str, Any]
|
endpoint. |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the upstream is unreachable
(:class: |
get_claims
async
¶
get_claims(
credentials: Annotated[
HTTPAuthorizationCredentials | None, Depends(_bearer_scheme)
] = None,
) -> dict[str, Any]
FastAPI dependency returning the validated userinfo claims.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
HTTPAuthorizationCredentials | None
|
The bearer
credentials extracted by the |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The claims returned by the upstream userinfo |
dict[str, Any]
|
endpoint. |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When no credentials were supplied, the
token could not be validated upstream, or it was issued to
a client outside :attr: |
ForbiddenException
|
When |
get_user_id
async
¶
get_user_id(
credentials: Annotated[
HTTPAuthorizationCredentials | None, Depends(_bearer_scheme)
] = None,
) -> UUID
FastAPI dependency returning the caller's subject id as a UUID.
This depends on the bearer credentials directly and internally calls
:meth:get_claims, which avoids referencing self in a default
argument (a default is evaluated at method-definition time, when the
instance does not yet exist) while still wiring cleanly under
Depends(auth.get_user_id).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
HTTPAuthorizationCredentials | None
|
The bearer
credentials extracted by the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UUID |
UUID
|
The subject claim parsed as a :class: |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the token is missing / invalid, or the subject claim is absent or not a valid UUID. |
ForbiddenException
|
When |
FirebaseAuth
¶
FirebaseAuth(
*,
credentials_path: str | Path | None = None,
credentials_json: str | None = None,
project_id: str | None = None,
app_name: str = DEFAULT_FIREBASE_APP_NAME,
check_revoked: bool = False,
clock_skew_seconds: int = 0,
enabled: bool = True,
)
Verify Firebase ID tokens and expose them as FastAPI dependencies.
Construction initializes (or reuses) a firebase_admin app. The
reuse is the point: initialize_app() raises ValueError when
an app of that name already exists, so every service that wires
Firebase in more than one module ends up re-implementing the same
get_app() / except ValueError guard. Building two
:class:FirebaseAuth instances with the same app_name is
supported and hits the same underlying app.
Credential precedence, first hit wins:
credentials_json— the service-account JSON inline, for deployments that inject it as an environment variable and mount no file.credentials_path— a service-account file on disk.- The environment's application-default credential
(
GOOGLE_APPLICATION_CREDENTIALS, or the metadata server on Google infrastructure).
Both :meth:get_identity and :meth:get_uid are bound methods
usable directly as FastAPI dependencies, and
:meth:get_optional_identity is the soft variant that yields
None instead of raising.
Attributes:
| Name | Type | Description |
|---|---|---|
app_name |
str
|
Name of the underlying |
check_revoked |
bool
|
Whether each verification also asks the Firebase backend whether the token was revoked and whether the user is disabled. Costs one network round-trip per request. |
clock_skew_seconds |
int
|
Tolerance, in seconds, applied to the token's time claims. |
Initialize the authenticator, creating or reusing a Firebase app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials_path
|
str | Path | None
|
Path to a
service-account JSON file. Ignored when
|
None
|
credentials_json
|
str | None
|
The service-account JSON
itself, as a string. Takes precedence over
|
None
|
project_id
|
str | None
|
Firebase project id. Optional when the credential already carries it (a service-account file does); required with an application-default credential that does not. |
None
|
app_name
|
str
|
Name of the |
DEFAULT_FIREBASE_APP_NAME
|
check_revoked
|
bool
|
When |
False
|
clock_skew_seconds
|
int
|
Seconds of tolerance for the
token's |
0
|
enabled
|
bool
|
|
True
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the optional |
FirebaseCredentialError
|
When the credential cannot be built or the app cannot be initialized. |
app
property
¶
Return the initialized firebase_admin.App this instance uses.
Exposed so other Firebase-backed features reuse one loaded service
account instead of initializing a second app — the FCM transport in
:mod:tempest_fastapi_sdk.push is the first consumer.
Returns:
| Name | Type | Description |
|---|---|---|
App |
App
|
The |
App
|
|
|
App
|
does not infer from untyped sources (mypy) still sees |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When built with |
verify
async
¶
verify(token: str) -> FirebaseIdentity
Verify a raw ID token and return the identity it carries.
firebase_admin.auth.verify_id_token is synchronous and may
fetch Google's signing certificates, so it runs in a worker
thread (:func:asyncio.to_thread), matching the SDK's
async-first convention.
The except clauses are ordered most-specific first because
ExpiredIdTokenError and RevokedIdTokenError are both
subclasses of InvalidIdTokenError (measured on
firebase-admin 7.5.0). Catching the parent first would
collapse all three into FIREBASE_TOKEN_INVALID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The raw ID token, without the |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FirebaseIdentity |
FirebaseIdentity
|
The verified identity. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When built with |
FirebaseTokenRevokedError
|
When the token was revoked
( |
FirebaseTokenExpiredError
|
When the token has expired. |
FirebaseUserDisabledError
|
When the Firebase user is disabled
( |
FirebaseUnavailableError
|
When the signing certificates could not be fetched. |
FirebaseTokenInvalidError
|
When the token is malformed, has a bad signature, targets another project, or carries no subject claim. |
get_identity
async
¶
get_identity(
credentials: Annotated[
HTTPAuthorizationCredentials | None, Depends(_bearer_scheme)
] = None,
) -> FirebaseIdentity
FastAPI dependency returning the verified caller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
HTTPAuthorizationCredentials | None
|
The bearer
credentials extracted by the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FirebaseIdentity |
FirebaseIdentity
|
The verified identity. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When built with |
FirebaseTokenMissingError
|
When no credentials were supplied. |
UnauthorizedException
|
Any of the verification failures
documented on :meth: |
FirebaseUserDisabledError
|
When the user is disabled (403). |
get_optional_identity
async
¶
get_optional_identity(
credentials: Annotated[
HTTPAuthorizationCredentials | None, Depends(_bearer_scheme)
] = None,
) -> FirebaseIdentity | None
FastAPI dependency returning the caller, or None.
The soft variant, for endpoints that serve both authenticated and
anonymous callers. A missing header yields None; so does
a token that fails verification, which is logged at DEBUG
with the error code only — never the token itself. A disabled
user still raises, because that is an authorization decision the
route must not silently ignore.
Pair it with
:func:tempest_fastapi_sdk.auth.guards.require_authenticated to
narrow the value back to non-None inside a handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
HTTPAuthorizationCredentials | None
|
The bearer
credentials extracted by the |
None
|
Returns:
| Type | Description |
|---|---|
FirebaseIdentity | None
|
FirebaseIdentity | None: The verified identity, or |
FirebaseIdentity | None
|
when the request carried no usable token. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When built with |
FirebaseUserDisabledError
|
When the token verifies but the Firebase user is disabled (403). |
get_uid
async
¶
get_uid(
credentials: Annotated[
HTTPAuthorizationCredentials | None, Depends(_bearer_scheme)
] = None,
) -> str
FastAPI dependency returning only the caller's Firebase uid.
Most routes want the id, not the whole identity. This depends on
the bearer credentials directly and calls :meth:get_identity
internally, which avoids referencing self in a default
argument — a default is evaluated at method-definition time,
when the instance does not exist yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
HTTPAuthorizationCredentials | None
|
The bearer
credentials extracted by the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The verified Firebase user id. |
Raises:
| Type | Description |
|---|---|
FirebaseTokenMissingError
|
When no credentials were supplied. |
UnauthorizedException
|
Any of the verification failures
documented on :meth: |
FirebaseIdentity
dataclass
¶
FirebaseIdentity(
uid: str,
email: str | None = None,
email_verified: bool = False,
phone_number: str | None = None,
provider: str = "",
claims: Mapping[str, Any] = dict(),
)
The verified caller, as the application sees it.
Attributes:
| Name | Type | Description |
|---|---|---|
uid |
str
|
The Firebase user id (the token's |
email |
str | None
|
The email on the token, when the sign-in provider supplied one. |
email_verified |
bool
|
Whether Firebase considers that email
verified. |
phone_number |
str | None
|
The phone number on the token, for phone sign-in. |
provider |
str
|
The |
claims |
Mapping[str, Any]
|
Every claim the token carried,
including custom claims set with |
from_claims
classmethod
¶
from_claims(claims: Mapping[str, Any]) -> FirebaseIdentity
Build an identity from the claims verify_id_token returned.
firebase_admin copies sub into a uid key on the
verified claims, so uid is read first and sub is the
fallback — the mapping works with either shape, including hand
built claims in tests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
claims
|
Mapping[str, Any]
|
The verified token claims. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FirebaseIdentity |
FirebaseIdentity
|
The typed identity. |
Raises:
| Type | Description |
|---|---|
FirebaseTokenInvalidError
|
When the claims carry neither
|
FirebaseUserResolver
¶
FirebaseUserResolver(
auth: FirebaseAuth, resolver: Callable[[FirebaseIdentity], Awaitable[UserT | None]]
)
Bases: Generic[UserT]
Turn a verified Firebase identity into the project's user object.
The SDK does not decide how a uid becomes a user: that is a
database lookup, a just-in-time provisioning rule, or a call to
another service — all of them project decisions. This class is the
seam. It takes an async resolver and exposes dependencies that yield
whatever the resolver returns, keeping the concrete user type::
async def load_user(identity: FirebaseIdentity) -> UserModel | None:
return await repository.get_by_firebase_uid(identity.uid)
users: FirebaseUserResolver[UserModel] = FirebaseUserResolver(
auth, load_user
)
@router.get("/profile")
async def profile(user: UserModel = Depends(users.get_user)) -> UserModel:
return user
A resolver that answers None means "this identity has no user
here", which is a 401 and not an empty response.
Attributes:
| Name | Type | Description |
|---|---|---|
auth |
FirebaseAuth
|
The authenticator whose identities are resolved. |
Initialize the resolver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
FirebaseAuth
|
The authenticator that verifies tokens. |
required |
resolver
|
Callable[[FirebaseIdentity], Awaitable[UserT | None]]
|
Async callable mapping a verified identity to the
project's user object, or |
required |
get_user
async
¶
get_user(
credentials: Annotated[
HTTPAuthorizationCredentials | None, Depends(_bearer_scheme)
] = None,
) -> UserT
FastAPI dependency returning the project's user for the caller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
HTTPAuthorizationCredentials | None
|
The bearer
credentials extracted by the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UserT |
UserT
|
Whatever the configured resolver returned. |
Raises:
| Type | Description |
|---|---|
FirebaseTokenMissingError
|
When no credentials were supplied. |
FirebaseTokenInvalidError
|
When the resolver found no user for an otherwise valid identity. |
UnauthorizedException
|
Any of the verification failures
documented on :meth: |
get_optional_user
async
¶
get_optional_user(
credentials: Annotated[
HTTPAuthorizationCredentials | None, Depends(_bearer_scheme)
] = None,
) -> UserT | None
FastAPI dependency returning the user, or None.
The soft counterpart of :meth:get_user: no token, an
unverifiable token, or an identity with no local user all yield
None instead of raising.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
HTTPAuthorizationCredentials | None
|
The bearer
credentials extracted by the |
None
|
Returns:
| Type | Description |
|---|---|
UserT | None
|
UserT | None: The resolved user, or |
Raises:
| Type | Description |
|---|---|
FirebaseUserDisabledError
|
When the token verifies but the Firebase user is disabled (403). |
FirebaseCredentialError
¶
Bases: RuntimeError
Raised when the Firebase app cannot be initialized.
This is a configuration failure (missing service-account file,
malformed JSON, no application-default credential in the
environment), not a request failure — it happens at construction
time, never while handling a request, so it is not an
:class:~tempest_fastapi_sdk.exceptions.AppException.
FirebaseTokenMissingError
¶
FirebaseTokenInvalidError
¶
FirebaseTokenExpiredError
¶
FirebaseTokenRevokedError
¶
FirebaseTokenRevokedError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: UnauthorizedException
Raised when the ID token was revoked upstream.
Only reachable with check_revoked=True, which costs one extra
call to the Firebase backend per verification.
FirebaseUserDisabledError
¶
FirebaseUserDisabledError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: ForbiddenException
Raised when the token is valid but the Firebase user is disabled.
The caller proved who they are, so this is a 403 and not a 401. Like
:class:FirebaseTokenRevokedError, it is only reachable with
check_revoked=True.
FirebaseUnavailableError
¶
FirebaseUnavailableError(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: UnauthorizedException
Raised when Google's public certificates cannot be fetched.
Verification is local, but it needs the signing certificates, which
firebase_admin fetches and caches. When that fetch fails the
token can be neither accepted nor rejected. It answers 401 for the
same reason IntrospectionAuth does when its upstream is
unreachable: the request could not be authenticated.
MFAAlreadyEnrolledException
¶
MFAAlreadyEnrolledException(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: ConflictException
Raised when enrollment is requested for an account whose MFA is active.
/mfa/enroll only requires a bearer access token. Enrolling again
over an active second factor would wipe the recovery codes and reset
totp_enabled_at, which switches MFA off with nothing but that
token, skipping the password and the TOTP code that /mfa/disable
demands. Rotating the secret therefore goes through /mfa/disable
first, then a fresh enroll and confirm.
A pending enrollment (secret staged, never confirmed) is not active, so enrolling again over it is allowed and rotates the staged secret.
MFANotEnrolledException
¶
MFANotEnrolledException(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: ValidationException
Raised when a flow that proves the second factor meets an account without one.
:meth:~tempest_fastapi_sdk.UserAuthService.change_password_with_mfa
rotates the password on the strength of a TOTP or recovery code; an
account with no active factor has nothing to prove, so it is refused
rather than silently downgraded to a password change with no proof.
The AUTH_MFA_ENABLED kill-switch counts: with it off, every account
reads as not enrolled, exactly as at login.
AccountInactiveException
¶
AccountInactiveException(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: ForbiddenException
Raised when the right password opens a deactivated account.
Only under AUTH_REVEAL_INACTIVE_ACCOUNT: by default a deactivated
account answers the same 401 as a wrong password, so the response
does not say which emails have an account. Revealing it to whoever
proved the password enumerates nothing — that caller already owns
the account — and spares them a password reset that would not let
them in either.
The social-login counterpart is
:class:~tempest_fastapi_sdk.OAuthAccountInactiveException, which
keeps its own OAUTH_ACCOUNT_INACTIVE code and 401.
EmailLinkForbiddenException
¶
EmailLinkForbiddenException(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: ForbiddenException
Raised when a refused account tries to spend an emailed link.
Some accounts — an operator, a staff member — should never be driven
by an emailed link at all: whoever reads the mailbox could otherwise
open /password-reset/confirm (or /activate) and rotate the
password, locking the owner out even without the second factor. The
refusal is opted into per account through
UserAuthService(refuses_email_link=...).
When the predicate matches, the request routes answer the same
202 as an unknown address and mint no token, so the refusal is not
enumerable; the confirm routes raise this class — 403 — after
consuming the token and before touching the password, so a link that
leaked anyway authorizes nothing.
AuthExceptions
dataclass
¶
AuthExceptions(
invalid_credentials: type[UnauthorizedException] = UnauthorizedException,
account_inactive: type[ForbiddenException] = AccountInactiveException,
email_taken: type[ConflictException] = ConflictException,
email_link_forbidden: type[ForbiddenException] = EmailLinkForbiddenException,
password_too_short: type[ValidationException] = ValidationException,
password_too_long: type[ValidationException] = ValidationException,
password_too_weak: type[ValidationException] = ValidationException,
invalid_token: type[InvalidTokenException] = InvalidTokenException,
)
Which exception class UserAuthService raises at each refusal.
A service adopting the bundled flow keeps the code its clients
already handle by passing its own classes here, instead of overriding
methods only to swap the exception. Each field is typed with the
default class, so a replacement must subclass it: the HTTP status
(inherited) and the cost of the refusal (unchanged code path) stay
what they were, and only the class — and with it the code —
changes.
Every raise still passes message / details / message_key
as keyword arguments, so a replacement keeps the
:class:~tempest_fastapi_sdk.AppException constructor.
Attributes:
| Name | Type | Description |
|---|---|---|
invalid_credentials |
type[UnauthorizedException]
|
Wrong
password, unknown email, and — unless
|
account_inactive |
type[ForbiddenException]
|
The right password
on a deactivated account, on |
email_taken |
type[ConflictException]
|
Signup or email change to an address another account holds. |
password_too_short |
type[ValidationException]
|
A password below the policy minimum. |
password_too_long |
type[ValidationException]
|
A password above the policy's byte limit (bcrypt's 72). |
password_too_weak |
type[ValidationException]
|
A password missing a character class under complexity mode. |
invalid_token |
type[InvalidTokenException]
|
A single-use link (activation, password reset, email change or verification) that is unknown, used, expired, or points to a user that no longer exists. Refresh tokens are not covered. |
email_link_forbidden |
type[ForbiddenException]
|
An account
matched by |
LoginThrottledException
¶
LoginThrottledException(
message: str | None = None,
*,
retry_after_seconds: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
)
Bases: TooManyRequestsException
Raised when POST /auth/login is over its attempt budget.
The same class for the per-email and the per-client budget, so the answer never says which of the two ran out — saying it would tell a caller that the email is being guessed at. The body is the same for an email that has an account and one that does not.
MfaThrottledException
¶
SignupThrottledException
¶
DEFAULT_FIREBASE_APP_NAME
module-attribute
¶
Name firebase_admin gives the app created without an explicit one.
Ported from firebase_admin._DEFAULT_APP_NAME (measured on
firebase-admin 7.5.0) so callers can name the default app explicitly
without importing a private attribute. tests/auth/test_firebase.py
pins it against the installed package, so an upstream rename fails a test
instead of silently creating a second app.
make_auth_router
¶
make_auth_router(
service: UserAuthService,
*,
session_factory: Callable[..., AsyncIterator[AsyncSession]],
prefix: str = "/auth",
tags: list[str] | None = None,
template_dir: str | None = None,
recovery_code_model: type[BaseUserRecoveryCodeModel] | None = None,
me_response_model: type[BaseModel] | None = None,
allow_signup: bool | None = None,
signup_schema: type[SignupSchema] | None = None,
on_signup: SignupHook | None = None,
token_delivery: TokenDelivery | None = None,
cookie_config: AuthCookieConfig | None = None,
webauthn: WebAuthnService | None = None,
oauth_clients: Mapping[str, OAuthClient] | None = None,
token_strict: bool = False,
token_legacy_claims: Collection[str] = (),
mfa_throttle: AttemptThrottle | None = None,
login_throttle: AttemptThrottle | Literal[False] | None = None,
login_ip_throttle: AttemptThrottle | None = None,
signup_throttle: AttemptThrottle | None = None,
trusted_ip_header: str | None = None,
docs_locale: str | None = None,
) -> APIRouter
Build the bundled auth router.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
UserAuthService
|
The configured service handling signup / activation / reset. |
required |
session_factory
|
Callable[..., AsyncIterator[AsyncSession]]
|
FastAPI dependency yielding an async session — the same
|
required |
prefix
|
str
|
The full public path the auth routes live under;
defaults to |
'/auth'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to
|
None
|
template_dir
|
str | None
|
Optional directory holding
HTML templates that override the SDK-bundled
|
None
|
me_response_model
|
type[BaseModel] | None
|
Response model for
|
None
|
allow_signup
|
bool | None
|
Whether to mount
|
None
|
signup_schema
|
type[SignupSchema] | None
|
Request body for
|
None
|
on_signup
|
SignupHook | None
|
Awaited right after the row is
created and before the commit, as
|
None
|
token_delivery
|
TokenDelivery | None
|
How login / refresh hand
back the JWT pair — |
None
|
cookie_config
|
AuthCookieConfig | None
|
Override the cookie
security attributes. |
None
|
recovery_code_model
|
type[BaseUserRecoveryCodeModel] | None
|
Model
storing the one-time MFA recovery codes. |
None
|
webauthn
|
WebAuthnService | None
|
Configured
:class: |
None
|
oauth_clients
|
Mapping[str, OAuthClient] | None
|
Social-login
clients keyed by the provider name the URLs will carry —
|
None
|
token_strict
|
bool
|
Whether the router's authenticated routes
refuse an access token carrying no recognizable type marker.
|
False
|
token_legacy_claims
|
Collection[str]
|
Extra claim names to read
the token type from when |
()
|
mfa_throttle
|
AttemptThrottle | None
|
Failure budget for
|
None
|
login_throttle
|
AttemptThrottle | Literal[False] | None
|
Failure
budget for |
None
|
login_ip_throttle
|
AttemptThrottle | None
|
Failure budget for the
login routes keyed per client IP ( |
None
|
signup_throttle
|
AttemptThrottle | None
|
Budget for
|
None
|
trusted_ip_header
|
str | None
|
Single edge-set header holding the
real client IP (e.g. |
None
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
Notes
Which endpoint groups get mounted, and where:
- JSON / SPA endpoints are always mounted, except
POST /auth/signup, which is skipped whenAUTH_SIGNUP_ENABLEDis off (orallow_signup=False). - Cookie endpoints are mounted when
AUTH_TOKEN_DELIVERYiscookieorboth. Incookiemode they take the normal/login,/refreshand/logoutpaths; inbothmode they move under a/cookie/*sub-prefix so they do not collide with the bearer endpoints sharing the router. - Backend-rendered HTML endpoints are mounted only when
AUTH_BACKEND_LINKSis on. - MFA endpoints are mounted only when
AUTH_MFA_ENABLEDis on. - WebAuthn endpoints are mounted only when
AUTH_WEBAUTHN_ENABLEDis on and awebauthnservice is passed. - Social-login endpoints are mounted only when
AUTH_OAUTH_ENABLEDis on, at least one client is passed, the service carries anoauth_account_modeland the user model carries anamecolumn. The callback honoursAUTH_TOKEN_DELIVERYlike every other login-equivalent step, except thatbothsets cookies and fills the body rather than mounting a parallel/auth/cookie/*route: the callback URL is registered at the provider, so a second one would have to be registered there too.
The refresh cookie is scoped to the auth base path rather than the site root, so it reaches the refresh and logout endpoints but is not sent along with ordinary API requests.
The authenticated-user dependency is shared by the password-change route and, when enabled, the MFA routes. With cookies in play it also accepts the access token from the cookie, with the header still taking precedence.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the requested token delivery mode needs a
refresh-token model and the service was built without one;
when |
make_auth_pages_router
¶
make_auth_pages_router(
service: UserAuthService,
session_factory: Callable[..., AsyncIterator[AsyncSession]],
*,
session_auth: SessionAuth,
template_dir: str | None = None,
recovery_code_model: type[BaseUserRecoveryCodeModel] | None = None,
allow_signup: bool | None = None,
signup_schema: type[SignupSchema] | None = None,
on_signup: SignupHook | None = None,
login_throttle: AttemptThrottle | None = None,
login_ip_throttle: AttemptThrottle | None = None,
signup_throttle: AttemptThrottle | None = None,
mfa_throttle: AttemptThrottle | None = None,
activation_throttle: AttemptThrottle | None = None,
trusted_ip_header: str | None = None,
) -> APIRouter
Build the server-side login, signup and activation pages.
Routes, under AUTH_PAGES_PREFIX (site root by default), all
include_in_schema=False:
GET/POST /login— e-mail and password. An account with MFA goes to/login/mfawithout a session; otherwise the session opens and the browser goes tonextorAUTH_PAGES_LOGIN_REDIRECT.GET/POST /login/mfa— TOTP or recovery code over the pending step kept in the :data:AUTH_PAGES_MFA_COOKIEcookie.GET/POST /signup— the form generated fromsignup_schema; only with signup enabled. Ends on "check your e-mail", or in a session withAUTH_AUTO_ACTIVATE.GET /activate/{token}— activates and opens the session (amr=["email"]); an account with MFA goes to/login/mfa. PointAUTH_ACTIVATION_URL_TEMPLATEhere.GET/POST /activation/request— resend the link; the same answer with or without an account.POST /logout— revokes the session in the store.
Every POST requires the form's csrf_token; a missing or
mismatched one re-renders the form with 403 before anything else
runs, so it spends no attempt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
UserAuthService
|
The auth service the JSON router uses. |
required |
session_factory
|
Callable[..., AsyncIterator[AsyncSession]]
|
The request-scoped DB session provider. |
required |
session_auth
|
SessionAuth
|
Opens, resolves and revokes the
cookie session; its |
required |
template_dir
|
str | None
|
Project folder overriding the bundled templates, by file name (per-locale subfolder first). |
None
|
recovery_code_model
|
type[BaseUserRecoveryCodeModel] | None
|
Required when |
None
|
allow_signup
|
bool | None
|
Overrides |
None
|
signup_schema
|
type[SignupSchema] | None
|
The signup form's schema; extra fields that are user columns are set before the insert, as in the JSON route. |
None
|
on_signup
|
SignupHook | None
|
Runs after the insert, before the commit, as in the JSON route. |
None
|
login_throttle
|
AttemptThrottle | None
|
Per-e-mail budget; the
JSON route's default when |
None
|
login_ip_throttle
|
AttemptThrottle | None
|
Per-IP budget; off
when |
None
|
signup_throttle
|
AttemptThrottle | None
|
Per-IP signup budget;
:data: |
None
|
mfa_throttle
|
AttemptThrottle | None
|
Per-account second-factor
budget; the JSON route's default when |
None
|
activation_throttle
|
AttemptThrottle | None
|
Per-IP resend budget;
:data: |
None
|
trusted_ip_header
|
str | None
|
Header carrying the client IP for the IP budgets, as in the JSON router. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
The pages router. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When Jinja2 is not installed, or |
FormCSRF
¶
FormCSRF(
*,
cookie_name: str = FORM_CSRF_COOKIE,
secure: bool = True,
samesite: Literal["lax", "strict", "none"] = "lax",
path: str = "/",
max_age_seconds: int = FORM_CSRF_MAX_AGE_SECONDS,
)
Double-submit CSRF token for HTML forms.
Attributes:
| Name | Type | Description |
|---|---|---|
cookie_name |
str
|
Name of the cookie holding the token —
prefixed with :data: |
secure |
bool
|
Whether the cookie is flagged |
samesite |
Literal['lax', 'strict', 'none']
|
|
path |
str
|
Cookie path. |
max_age_seconds |
int
|
Cookie lifetime. |
Configure the cookie.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cookie_name
|
str
|
Name of the cookie holding the token. |
FORM_CSRF_COOKIE
|
secure
|
bool
|
Flag the cookie |
True
|
samesite
|
Literal['lax', 'strict', 'none']
|
|
'lax'
|
path
|
str
|
Cookie path. |
'/'
|
max_age_seconds
|
int
|
Cookie lifetime. |
FORM_CSRF_MAX_AGE_SECONDS
|
issue
¶
Return the token to embed in the form being rendered.
Reuses the request's token so two tabs do not invalidate each other; mints a new one when the request carries none.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The inbound request. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The token for the hidden field. |
attach
¶
Set the cookie carrying token, restarting its lifetime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
Response
|
The outbound response. |
required |
token
|
str
|
The token embedded in the form. |
required |
verify
¶
Compare the submitted field with the cookie, in constant time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The inbound request. |
required |
submitted
|
str
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
is_local_path
¶
Whether value is a path on this site, safe to redirect to.
Accepts /x, /x?y=1 and /. Refuses anything a browser
could resolve to another origin: an absolute URL, a scheme-relative
//host, the /\host form some browsers normalize to it, and
control characters that some parsers strip before resolving.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The candidate target, typically a |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
LOGIN_THROTTLE_MAX_ATTEMPTS
module-attribute
¶
Wrong passwords one e-mail may submit to /auth/login per window.
LOGIN_THROTTLE_WINDOW_SECONDS
module-attribute
¶
Length, in seconds, of the default /auth/login failure window.
LOGIN_THROTTLED_MESSAGE
module-attribute
¶
detail of the login 429.
The same text for an e-mail that exists and one that does not, so the refusal tells an attacker nothing about which accounts are real.
MFA_THROTTLE_MAX_ATTEMPTS
module-attribute
¶
Wrong codes one account may submit to /auth/mfa/verify per window.
MFA_THROTTLE_WINDOW_SECONDS
module-attribute
¶
Length, in seconds, of the default /auth/mfa/verify failure window.
SIGNUP_THROTTLED_MESSAGE
module-attribute
¶
detail of the signup 429.
require_authenticated
¶
require_authenticated(
user: SubjectT | None, *, exception: GuardException | None = None
) -> SubjectT
Assert that a subject is authenticated (non-None).
SubjectT is whatever a dependency resolved a caller to, user model
or not. This function reads no attribute off its argument — it only
rejects None — and the SDK hands out subjects that are not user
models: FirebaseAuth.get_optional_identity yields a
FirebaseIdentity, and the Firebase recipe guards it with this
function. Bound to BaseUserModel, that documented call resolved
the type parameter to None and failed under mypy.
Unbound means literally unbound: require_authenticated("")
type-checks and hands back a str. That is the honest reading of a
function whose whole body is if user is None: raise, and the
checking is bought back where the subject is known —
:meth:UserAuthService.require_authenticated keeps the
BaseUserModel bound, and so do :func:require_active /
:func:require_admin, because they read is_active / is_admin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
SubjectT | None
|
The subject resolved from the request —
typically the output of a |
required |
exception
|
GuardException | None
|
Factory for the
refusal. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
SubjectT |
SubjectT
|
The same subject, narrowed to non- |
SubjectT
|
concrete subclass). |
Raises:
| Type | Description |
|---|---|
AppException
|
When |
require_active
¶
require_active(
user: UserT | None,
*,
exception: GuardException | None = None,
unauthenticated: GuardException | None = None,
) -> UserT
Assert that a user is authenticated and active.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
UserT | None
|
The user resolved from the request. |
required |
exception
|
GuardException | None
|
Factory for the
refusal when |
None
|
unauthenticated
|
GuardException | None
|
Factory for
the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UserT |
UserT
|
The authenticated, active user. |
Raises:
| Type | Description |
|---|---|
AppException
|
When |
require_admin
¶
require_admin(
user: UserT | None,
*,
exception: GuardException | None = None,
unauthenticated: GuardException | None = None,
) -> UserT
Assert that a user is authenticated and an administrator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
UserT | None
|
The user resolved from the request. |
required |
exception
|
GuardException | None
|
Factory for the
refusal when |
None
|
unauthenticated
|
GuardException | None
|
Factory for
the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UserT |
UserT
|
The authenticated admin user. |
Raises:
| Type | Description |
|---|---|
AppException
|
When |
make_flag_guard
¶
make_flag_guard(
attribute: str,
*,
exception: GuardException,
unauthenticated: GuardException | None = None,
) -> FlagGuard
Build a guard asserting that a boolean column on the user is truthy.
The generalization of :func:require_active / :func:require_admin
to the flags the SDK does not model — is_producer, is_staff,
is_verified — which a project was writing by hand anyway, and
with its own exception, which is the part that could not be reused
before.
from tempest_fastapi_sdk import make_flag_guard
from src.core.exceptions import UserIsNotProducerError
require_producer = make_flag_guard(
"is_producer",
exception=UserIsNotProducerError,
)
The attribute is read with getattr(user, attribute, False), so a
user model that does not declare the column is refused rather than
raising AttributeError — a missing column and a False one
both mean "this user does not have it".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attribute
|
str
|
Name of the boolean attribute to assert. |
required |
exception
|
GuardException
|
Factory for the refusal
when the flag is falsy. Required: a guard whose whole point
is the project's own |
required |
unauthenticated
|
GuardException | None
|
Factory for
the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FlagGuard |
FlagGuard
|
A guard taking |
FlagGuard
|
|
make_value_guard
¶
make_value_guard(
column: str,
allowed: Collection[Enum | str],
*,
exception: GuardException,
unauthenticated: GuardException | None = None,
) -> FlagGuard
Build a guard asserting that a value column on the user is allowed.
The sibling of :func:make_flag_guard for the columns that are not
booleans: a role stored as an enum (role == Role.STAFF), a plan,
a tier — the checks a project was writing by hand anyway, and with
its own exception, which is the part that could not be reused before.
from enum import StrEnum
from tempest_fastapi_sdk import ForbiddenException, make_value_guard
class Role(StrEnum):
MEMBER = "member"
STAFF = "staff"
class UserIsNotStaffError(ForbiddenException):
message: str = "Only staff can access this resource"
code: str = "USER_IS_NOT_STAFF"
require_staff = make_value_guard(
"role",
{Role.STAFF},
exception=UserIsNotStaffError,
)
The comparison is by value, not by identity: enum members are
reduced to their .value on both sides, so a column holding the
raw "staff" passes a guard declared with {Role.STAFF} even
when Role is a plain Enum rather than a StrEnum. The
allowed collection is copied when the guard is built. The attribute is read with
getattr(user, column, None): a model that does not declare the
column, a NULL one, and a value outside allowed are all
refused with the same exception rather than raising
AttributeError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
Name of the attribute holding the value. |
required |
allowed
|
Collection[Enum | str]
|
The values that pass. Enum members or plain strings; both compare by value. |
required |
exception
|
GuardException
|
Factory for the refusal when the
value is not in |
required |
unauthenticated
|
GuardException | None
|
Factory for the
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FlagGuard |
FlagGuard
|
A guard taking |
FlagGuard
|
|
FlagGuard
¶
Bases: Protocol
The callable :func:make_flag_guard and :func:make_value_guard return.
Generic in the user type per call, so a guard built once still
narrows UserModel | None to UserModel at each call site
rather than degrading to the base class.
SignupSchema
¶
Bases: BaseSchema
Request body for POST /auth/signup.
Carries the credentials and the optional display name a new
account starts with. The email is normalized to lowercase
before insert (matches the unique-index convention every SDK
user table follows); the password is hashed with bcrypt by
:class:tempest_fastapi_sdk.PasswordUtils and never stored
in plaintext.
Attributes:
| Name | Type | Description |
|---|---|---|
email |
EmailStr
|
Login identifier — validated by
|
password |
str
|
Plaintext password. The schema only rejects an
empty string; the configured minimum length (default 12)
and optional complexity rules are the single source of
truth and are applied by :class: |
name |
str | None
|
Optional display name shown in the
admin UI / front-end profile. |
SignupResponseSchema
¶
Bases: BaseSchema
Response body for POST /auth/signup.
The shape depends on the active settings:
- When
AUTH_AUTO_ACTIVATE=Truethe user is born active,activation_required=Falseand bothaccess_token/refresh_tokenare populated — the client can log in immediately. - When
AUTH_AUTO_ACTIVATE=False(production default) the user must confirm the activation link before logging in.activation_required=True, the tokens stayNoneandactivation_urlis set only whenAUTH_RETURN_TOKEN_IN_RESPONSE=True(dev) or when the[email]extra isn't wired (so the link has to ship via the response instead of via SMTP).
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
Primary key of the freshly-inserted row. |
activation_required |
bool
|
Whether the user still needs to confirm via the activation link. |
activation_url |
str | None
|
Front-end URL the user must
visit. |
access_token |
str | None
|
Short-lived JWT. Only set
when |
refresh_token |
str | None
|
Long-lived JWT. Only set
when |
LoginSchema
¶
Bases: BaseSchema
Request body for POST /auth/login.
Standard email + password authentication. Both error paths
(wrong password / unknown email / inactive user) collapse
into the same generic UnauthorizedException so attackers
can't enumerate accounts by reading the response.
Attributes:
| Name | Type | Description |
|---|---|---|
email |
EmailStr
|
Login identifier. |
password |
str
|
Plaintext password — verified against the bcrypt hash stored on the row. |
LoginResponseSchema
¶
Bases: BaseSchema
Response body for POST /auth/login and the password-reset confirm.
Two shapes packed into one schema so callers can branch on
mfa_required without parsing different JSON layouts:
- Normal login (or MFA disabled / not enrolled) —
mfa_required=False,access_token+refresh_tokenpopulated,mfa_token=None. - MFA required (step 1 of two-step login) —
mfa_required=True,access_token/refresh_token=None,mfa_tokenpopulated. The frontend prompts for the TOTP code and replays it viaPOST /auth/mfa/verifyto swap the short-lived token for the real JWT pair.
The bundled router reuses this shape for POST /auth/login,
POST /auth/password-reset/confirm, POST /auth/mfa/confirm and
POST /auth/password-change, since each of them ends with an
authenticated session or, for an account with MFA enrolled, with the
challenge /auth/mfa/verify completes.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
UUID of the authenticated user. |
access_token |
str | None
|
Short-lived JWT — populated only
when |
refresh_token |
str | None
|
Long-lived JWT — populated
only when |
mfa_required |
bool
|
When |
mfa_token |
str | None
|
Short-lived JWT (5-minute TTL by
default) the caller passes back to
|
ActivationResponseSchema
¶
Bases: BaseSchema
Response body for POST /auth/activate/{token}.
Returned after the SDK has consumed a one-shot activation
token and flipped the user's is_active=True. The user is
automatically logged in — both JWTs are issued so the
front-end can complete the post-confirmation redirect in one
round-trip.
Two shapes packed into one schema, as in
:class:LoginResponseSchema. A fresh signup has no factor, so
it never branches; but /activation/request can issue a link
for a deactivated account that does have TOTP enrolled, and
then the route follows /login and answers mfa_required.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
UUID of the freshly-activated user. |
access_token |
str | None
|
Short-lived JWT — |
refresh_token |
str | None
|
Long-lived JWT — |
mfa_required |
bool
|
When |
mfa_token |
str | None
|
Short-lived JWT the caller passes
back to |
ActivationRequestSchema
¶
Bases: BaseSchema
Request body for POST /auth/activation/request.
The endpoint always answers 202 with the same generic message —
for an unknown address, for an account that is already active, and
for a genuine re-send alike — so probing it cannot enumerate
accounts.
Attributes:
| Name | Type | Description |
|---|---|---|
email |
EmailStr
|
Email of the account whose activation link never arrived. |
ActivationResendResponseSchema
¶
Bases: BaseSchema
Response body for POST /auth/activation/request.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
str
|
Generic sentence, identical in every case. |
activation_url |
str | None
|
The ready-to-use link, set only
when the caller surfaces it — |
PasswordResetRequestSchema
¶
Bases: BaseSchema
Request body for POST /auth/password-reset/request.
The endpoint always returns 202 with a generic message —
even when the email isn't on file — so probing the endpoint
can't enumerate accounts. The reset link travels via email
(production) or in the response body when
AUTH_RETURN_TOKEN_IN_RESPONSE=True (dev).
Attributes:
| Name | Type | Description |
|---|---|---|
email |
EmailStr
|
Email of the account asking for a reset. |
PasswordResetResponseSchema
¶
Bases: BaseSchema
Response body for POST /auth/password-reset/request.
message is the same generic string regardless of whether
the email matched an account. reset_url is populated only
when AUTH_RETURN_TOKEN_IN_RESPONSE=True or when the
[email] extra isn't installed — otherwise the link only
travels through SMTP.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
str
|
Human-readable summary of the next step. Always identical across the "email found" / "email not found" branches. |
reset_url |
str | None
|
Front-end reset URL when the
caller asked for an inline response, |
PasswordResetConfirmSchema
¶
Bases: BaseSchema
Request body for POST /auth/password-reset/confirm.
Carries the opaque token the user copied from the reset
link plus the replacement password. The service consumes the
token (one-shot — used_at is stamped) and replaces the
bcrypt hash atomically.
Attributes:
| Name | Type | Description |
|---|---|---|
token |
str
|
Opaque token issued by |
new_password |
str
|
Plaintext replacement password. The schema
only rejects empty strings; the effective minimum length
and complexity come from |
ActivationToken
¶
Bases: BaseSchema
Service-level result of issuing an account-activation token.
Returned by :meth:UserAuthService.signup when activation is
required — i.e. when AUTH_AUTO_ACTIVATE is false. The
plaintext token is included here exactly once; only its
SHA-256 hash is persisted, so this value cannot be recovered
later. Use it to mail the activation link, log it during
tests, or hand it back to the client in dev mode.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
UUID of the user the token authorizes. |
token |
str
|
Plaintext token — show once, never store. |
url |
str
|
Front-end activation URL with the token
already substituted into |
expires_at |
datetime
|
UTC timestamp the token becomes invalid (default 7 days after issuance). |
ActivationWithheld
¶
Bases: BaseSchema
Service-level result of a signup whose activation link was withheld.
Returned by :meth:UserAuthService.signup in place of an
:class:ActivationToken when AUTH_AUTO_ACTIVATE is false and the
refuses_email_link predicate matches the account just inserted.
The account exists and is inactive, but no activation token was
persisted and no email was sent: a link would only fail with
EMAIL_LINK_FORBIDDEN when used. Activate such an account out of
band (tempest user activate, an admin action).
It is a distinct type, and not None, because None already
means "born active" to every caller of signup — the router mints a
JWT pair on it. Reading this value as None would log an inactive
account in.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
UUID of the inactive account. |
PasswordResetToken
¶
Bases: BaseSchema
Service-level result of issuing a password-reset token.
Returned by :meth:UserAuthService.request_password_reset
when the email matches a user and the caller asked the
service to surface the link (either via
AUTH_RETURN_TOKEN_IN_RESPONSE=True or because no
:class:EmailUtils was wired). The plaintext token is
one-shot, hashed at rest, and expires after
AUTH_PASSWORD_RESET_TTL_SECONDS (default 1 hour).
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
UUID of the user whose password the token authorizes resetting. |
token |
str
|
Plaintext token — display once, never store. |
url |
str
|
Front-end reset URL with the token already
substituted into |
expires_at |
datetime
|
UTC timestamp the token becomes invalid. |
MFAEnrollResponseSchema
¶
Bases: BaseSchema
Response body for POST /auth/mfa/enroll — shown ONCE.
The user is responsible for screenshotting / printing the
payload before navigating away. The SDK does NOT re-show
these values; calling enroll again rotates the secret
and invalidates every previously issued recovery code.
Attributes:
| Name | Type | Description |
|---|---|---|
secret |
str
|
Base32 TOTP secret — exposed once so an advanced user can copy it manually into a desktop password manager (1Password, Bitwarden). Most users only scan the QR. |
provisioning_uri |
str
|
|
provisioning_qr |
str | None
|
|
recovery_codes |
list[str]
|
N single-use codes
( |
MFAConfirmSchema
¶
MFAVerifySchema
¶
MFADisableSchema
¶
Bases: BaseSchema
Request body for POST /auth/mfa/disable.
Requires both the account password AND an active TOTP / recovery code so a hijacked session cannot silently disable MFA.
OAuthAccountSchema
¶
Bases: BaseSchema
One linked social identity, as returned by the listing endpoint.
Deliberately omits the raw provider payload
(:attr:~tempest_fastapi_sdk.OAuthUser.raw): it is whatever the
IdP felt like sending, it is not part of any contract, and it is
the field most likely to carry something the account owner did not
expect to see echoed back.
Attributes:
| Name | Type | Description |
|---|---|---|
provider |
str
|
Provider key — the value to pass back when unlinking. |
subject |
str
|
The provider's stable id for this person. Opaque; useful for support, never for lookup by the client. |
email |
str | None
|
Email the provider reported at the last login through this link. |
email_verified |
bool | None
|
Whether the provider stated it
verified that address. |
name |
str | None
|
Display name the provider reported. |
picture |
str | None
|
Avatar URL the provider reported. |
created_at |
datetime
|
When the identity was linked. |
last_login_at |
datetime | None
|
Last login through this link. |
OAuthUnlinkSchema
¶
Bases: BaseSchema
Request body for POST /auth/oauth/accounts/unlink.
Attributes:
| Name | Type | Description |
|---|---|---|
provider |
str
|
Provider key to detach, as the listing endpoint reported it. |
WebAuthnService
¶
WebAuthnService(
*,
user_model: type[BaseUserModel],
credential_model: type[BaseWebAuthnCredentialModel],
auth_settings: AuthSettings,
challenge_store: WebAuthnChallengeStore | None = None,
)
Registration and passwordless login backed by fido2.
Both ceremonies are two requests: begin returns the options the
browser passes to navigator.credentials plus a challenge_id,
and complete verifies what the authenticator produced. The
challenge_id names the server-side state; it is popped on
verification, so a response can be used once.
Attributes:
| Name | Type | Description |
|---|---|---|
user_model |
type[BaseUserModel]
|
The project's user model. |
credential_model |
type[BaseWebAuthnCredentialModel]
|
The project's credential model. |
auth_settings |
AuthSettings
|
Supplies the relying-party identity, the allowed origins and the challenge TTL. |
challenge_store |
WebAuthnChallengeStore
|
Where ceremony state lives between the two requests. |
Initialize the service and build the relying party.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_model
|
type[BaseUserModel]
|
Concrete user model. |
required |
credential_model
|
type[BaseWebAuthnCredentialModel]
|
Concrete credential model. |
required |
auth_settings
|
AuthSettings
|
Populates the relying-party identity and the origin policy. |
required |
challenge_store
|
WebAuthnChallengeStore | None
|
Where
ceremony state lives. |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When |
register_begin
async
¶
register_begin(
session: AsyncSession, *, user: BaseUserModel
) -> tuple[dict[str, Any], str]
Start registering a new authenticator for user.
The credentials the account already holds are sent as
excludeCredentials, so registering the same key twice is
refused by the authenticator instead of creating a duplicate row
that can never be told apart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The authenticated account. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
tuple[dict[str, Any], str]: The options to hand to |
str
|
|
tuple[dict[str, Any], str]
|
the client must echo back. |
register_complete
async
¶
register_complete(
session: AsyncSession,
*,
user: BaseUserModel,
challenge_id: str,
response: dict[str, Any],
name: str | None = None,
) -> BaseWebAuthnCredentialModel
Verify the attestation and persist the new credential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The authenticated account. |
required |
challenge_id
|
str
|
Handle returned by
:meth: |
required |
response
|
dict[str, Any]
|
The browser's registration response, serialized as WebAuthn JSON. |
required |
name
|
str | None
|
User-supplied label for the authenticator. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseWebAuthnCredentialModel |
BaseWebAuthnCredentialModel
|
The persisted credential. |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the challenge is unknown or the attestation does not verify. |
ValidationException
|
When the authenticator returned a credential this account already registered. |
authenticate_begin
async
¶
authenticate_begin(
session: AsyncSession, *, email: str | None = None
) -> tuple[dict[str, Any], str]
Start a login ceremony.
With no email the ceremony is discoverable: the options
carry no credential list, and the authenticator picks the
account itself — the passwordless flow. Passing an email
narrows allowCredentials to that account's keys, which helps
an authenticator that stores no resident credential.
An unknown email produces a ceremony with an empty allow
list rather than an error: answering differently would turn the
endpoint into a way to enumerate accounts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
email
|
str | None
|
Account to narrow the ceremony to. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
tuple[dict[str, Any], str]: The options to hand to |
str
|
|
tuple[dict[str, Any], str]
|
the client must echo back. |
authenticate_complete
async
¶
authenticate_complete(
session: AsyncSession, *, challenge_id: str, response: dict[str, Any]
) -> BaseUserModel
Verify the assertion and return the authenticated user.
The signature counter is checked here rather than by fido2:
a counter that did not advance since the last assertion is the
spec's cloned-authenticator signal. Authenticators that always
report 0 (most platform passkeys) are exempt, since for them
a non-advancing counter carries no information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
challenge_id
|
str
|
Handle returned by
:meth: |
required |
response
|
dict[str, Any]
|
The browser's authentication response, serialized as WebAuthn JSON. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseUserModel |
BaseUserModel
|
The authenticated user. |
Raises:
| Type | Description |
|---|---|
UnauthorizedException
|
When the challenge is unknown, the credential is not registered, the assertion does not verify, the counter went backwards, or the account is inactive. |
list_credentials
async
¶
list_credentials(
session: AsyncSession, *, user: BaseUserModel
) -> list[BaseWebAuthnCredentialModel]
Return every credential registered by user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The authenticated account. |
required |
Returns:
| Type | Description |
|---|---|
list[BaseWebAuthnCredentialModel]
|
list[BaseWebAuthnCredentialModel]: The credentials, empty |
list[BaseWebAuthnCredentialModel]
|
when the account registered none. |
delete_credential
async
¶
delete_credential(
session: AsyncSession, *, user: BaseUserModel, credential_id: bytes
) -> None
Remove one of user's credentials.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
Active SQLAlchemy session. |
required |
user
|
BaseUserModel
|
The authenticated account. |
required |
credential_id
|
bytes
|
Raw credential ID to remove. |
required |
Raises:
| Type | Description |
|---|---|
NotFoundException
|
When the account holds no such credential. Scoped to the caller, so the endpoint never reveals whether the ID exists on another account. |
WebAuthnChallengeStore
¶
Bases: Protocol
Holds the state of a ceremony between its two requests.
fido2 produces an opaque state dict at begin and consumes it
at complete. It must survive the round trip to the browser without
the client being able to alter it — hence server-side storage rather
than a cookie — and must be usable exactly once.
put
async
¶
Store the ceremony state under challenge_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
challenge_id
|
str
|
Handle returned to the client. |
required |
state
|
dict[str, Any]
|
Opaque state from |
required |
ttl
|
int
|
Seconds after which the state is unusable. |
required |
pop
async
¶
Remove and return the state stored under challenge_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
challenge_id
|
str
|
Handle handed back by the client. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
dict[str, Any] | None: The state, or |
dict[str, Any] | None
|
unknown, already used, or expired. |
MemoryWebAuthnChallengeStore
¶
In-process challenge store.
Correct for a single worker. With more than one replica a ceremony
that begins on replica A and completes on replica B finds no state
and fails — use :class:RedisWebAuthnChallengeStore there.
Initialize an empty store.
put
async
¶
Store the ceremony state, dropping anything already expired.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
challenge_id
|
str
|
Handle returned to the client. |
required |
state
|
dict[str, Any]
|
Opaque state from |
required |
ttl
|
int
|
Seconds after which the state is unusable. |
required |
pop
async
¶
Remove and return the state, honoring its expiry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
challenge_id
|
str
|
Handle handed back by the client. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
dict[str, Any] | None: The state, or |
RedisWebAuthnChallengeStore
¶
Challenge store shared across replicas.
Uses GETDEL so the read and the delete are one operation: two
concurrent completions of the same ceremony cannot both find the
state, which is what makes the single-use property hold under
concurrency.
Initialize the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
RedisLike
|
Async Redis client (e.g.
|
required |
namespace
|
str
|
Prefix for every Redis key. |
'webauthn'
|
put
async
¶
Store the ceremony state with a Redis expiry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
challenge_id
|
str
|
Handle returned to the client. |
required |
state
|
dict[str, Any]
|
Opaque state from |
required |
ttl
|
int
|
Seconds after which the state is unusable. |
required |
pop
async
¶
Remove and return the state via GETDEL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
challenge_id
|
str
|
Handle handed back by the client. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
dict[str, Any] | None: The state, or |
CHALLENGE_ID_BYTES
module-attribute
¶
Entropy of the handle naming a ceremony in the challenge store.
The handle is not a secret — it only names a pending challenge, which is itself verified — but it must be unguessable enough that one caller cannot pop another's state. 128 bits matches the SDK's other opaque identifiers.
WebAuthnOptionsSchema
¶
Bases: BaseSchema
Response body for both /auth/webauthn/*/begin endpoints.
Attributes:
| Name | Type | Description |
|---|---|---|
challenge_id |
str
|
Handle naming the server-side ceremony
state. Echo it back on the matching |
options |
dict[str, Any]
|
The |
WebAuthnRegisterBeginSchema
¶
Bases: BaseSchema
Request body for POST /auth/webauthn/register/begin.
Registering a passkey adds a lasting way into the account, one that signs in without the password or the second factor. A bearer access token alone is not enough proof for that: the route asks for the password, and for the second factor when the account has TOTP enrolled, exactly as disabling MFA does.
Attributes:
| Name | Type | Description |
|---|---|---|
current_password |
str
|
The account's password, re-verified. |
code |
str | None
|
A TOTP code or a recovery code. Required when the account has MFA enrolled; ignored otherwise. |
WebAuthnRegisterCompleteSchema
¶
Bases: BaseSchema
Request body for POST /auth/webauthn/register/complete.
Attributes:
| Name | Type | Description |
|---|---|---|
challenge_id |
str
|
Handle returned by the |
credential |
dict[str, Any]
|
The registration response, as produced by the browser's WebAuthn JSON serialization. |
name |
str | None
|
Label for this authenticator. |
WebAuthnAuthenticateBeginSchema
¶
Bases: BaseSchema
Request body for POST /auth/webauthn/authenticate/begin.
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str | None
|
Narrows the ceremony to one account's credentials. Omit it for the usernameless flow, where the authenticator picks the account. |
WebAuthnAuthenticateCompleteSchema
¶
Bases: BaseSchema
Request body for POST /auth/webauthn/authenticate/complete.
Attributes:
| Name | Type | Description |
|---|---|---|
challenge_id |
str
|
Handle returned by the |
credential |
dict[str, Any]
|
The assertion, as produced by the browser's WebAuthn JSON serialization. |
WebAuthnCredentialSchema
¶
Bases: BaseSchema
One registered authenticator, as returned by the listing endpoint.
Attributes:
| Name | Type | Description |
|---|---|---|
credential_id |
str
|
Base64url credential ID — the value to pass back when deleting this credential. |
name |
str | None
|
User-supplied label. |
transports |
str | None
|
Comma-separated transport hints. |
aaguid |
str | None
|
Authenticator model identifier, hex. |
backed_up |
bool
|
Whether the credential is synced. |
created_at |
datetime
|
Registration timestamp. |
last_used_at |
datetime | None
|
Last successful assertion. |
WebAuthnDeleteSchema
¶
Bases: BaseSchema
Request body for POST /auth/webauthn/credentials/delete.
Attributes:
| Name | Type | Description |
|---|---|---|
credential_id |
str
|
Base64url credential ID to remove. |
GuardException
module-attribute
¶
GuardException: TypeAlias = Callable[[], AppException]
Type of the exception= seam: a zero-argument factory.
A factory rather than an instance, because an exception carries a
traceback once raised and a module-level singleton would accumulate one
across requests. exception=MyError works directly whenever the class
takes no required arguments, which is the shape
:func:~tempest_fastapi_sdk.not_found_exception and its siblings
produce.
AUTH_DEFAULT_DISPLAY_NAME
module-attribute
¶
Placeholder display name, per locale.
Used when an account is created without anyone having typed a name —
the OAuth callback for a provider that reports no name claim. A
second-person pronoun rather than "User" or an empty string:
whatever lands here is what a greeting renders, and "Olá, Você" reads
as a UI that has not learned your name yet, while "Olá, User" reads as
a bug and "Olá, " reads as a broken template.
DEFAULT_AUTH_LOCALE
module-attribute
¶
Locale used when no value is configured and nothing is negotiated.
default_display_name
¶
Return the placeholder display name for locale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
locale
|
str
|
A canonical supported locale. Unknown locales fall
back to :data: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The localized placeholder. |
format_expires_at
¶
Render a token-expiry datetime as a short, locale-aware string.
Drops seconds and microseconds and appends (UTC) so the reader
knows the timezone. pt-BR uses DD/MM/YYYY HH:MM; en-US
uses YYYY-MM-DD HH:MM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
datetime
|
The expiry timestamp. Naive values are assumed to be UTC (the SDK stores token expiries in UTC). |
required |
locale
|
str
|
A canonical supported locale; unknown values fall
back to the |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
e.g. |
str
|
|
LOCALE_QUERY_PARAM
module-attribute
¶
Query parameter carrying the locale from an emailed link to the page it
opens. Read by :func:resolve_locale, written by :func:stamp_locale.
negotiate_locale
¶
negotiate_locale(
accept_language: str | None, *, default: str = DEFAULT_AUTH_LOCALE
) -> str
Pick the best supported locale for an HTTP request.
Parses the Accept-Language header (ordered by q weight) and
returns the first tag that maps to a :data:SUPPORTED_LOCALES entry.
When the header is absent or matches nothing, default is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accept_language
|
str | None
|
Raw |
required |
default
|
str
|
Canonical locale used when negotiation fails.
Should already be normalized (e.g. the configured
|
DEFAULT_AUTH_LOCALE
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
One of :data: |
normalize_locale
¶
normalize_locale(value: str | None, *, default: str = DEFAULT_AUTH_LOCALE) -> str
Coerce a loose locale string into a canonical supported tag.
Accepts any casing and the common separators users type — "PT-BR",
"pt_br", "ptbr", "pt" all map to "pt-BR"; "EN",
"en_US", "enus" all map to "en-US". Anything unrecognized
falls back to default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str | None
|
The raw locale value (e.g. read from an env
var). |
required |
default
|
str
|
Canonical locale returned when |
DEFAULT_AUTH_LOCALE
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
One of :data: |
Notes
An unknown full tag falls back to its primary subtag, so pt-pt
resolves as pt.
resolve_locale
¶
resolve_locale(
*,
user: object | None = None,
query_locale: str | None = None,
accept_language: str | None = None,
default: str = DEFAULT_AUTH_LOCALE,
) -> str
Pick one locale for a whole auth flow, from every signal available.
Both ends of a flow call this, so the email and the page it links to cannot disagree. Precedence, first match wins:
query_locale— the?lang=:data:LOCALE_QUERY_PARAMthat :func:stamp_localewrote on the emailed link. It outranks the stored preference on purpose: it records the language this email went out in, so a user who changes their preference between the send and the click still opens a page that matches the message they are reading. Preferring the row instead would recreate the exact split this function exists to close.user.locale— the preference the consumer persisted, and what the email side resolves from (there is no link yet when the email is built). Read withgetattrbecause :class:~tempest_fastapi_sdk.BaseUserModeldeclares no such column; mix in :class:~tempest_fastapi_sdk.LocaleColumnMixinto have one.accept_language— the browser's own negotiation.default— usuallyAUTH_DEFAULT_LOCALE.
A signal that is absent, empty, or names an unsupported locale is
skipped rather than treated as an answer, so a row saying fr-FR
still reaches the header instead of rendering in a language the SDK
does not ship.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
object | None
|
The user the flow is about, when the caller
has one. Only its |
None
|
query_locale
|
str | None
|
Raw value of the |
None
|
accept_language
|
str | None
|
Raw |
None
|
default
|
str
|
Canonical locale used when nothing else matches. |
DEFAULT_AUTH_LOCALE
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
One of :data: |
stamp_locale
¶
stamp_locale(url: str, locale: str, *, param: str = LOCALE_QUERY_PARAM) -> str
Append ?lang=<locale> to an emailed link.
Lets the page the link opens render in the language of the email that carried it, which is the only signal available for an account that was just created and has no stored preference yet.
Every other query parameter is carried over verbatim — the opaque token already sitting there is never re-encoded.
Three cases for a URL that already mentions param:
?lang=en-US— returned unchanged. A consumer who writes the language into their own template stays in charge.?lang=— the blank pair is dropped and the real value appended, instead of leaving a repeated parameter whose answer depends on who parses it. Measured: Starlette'sQueryParams.getreturns the last occurrence ("pt-BR"), while a consumer readingparse_qs(query)["lang"][0]gets the blank one. Dropping removes the ambiguity rather than betting on the reader.?LANG=en-US— left alone, and stamped beside. Query-parameter names are case-sensitive, so that is somebody else's parameter, not another spelling of this one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The absolute link that goes into the email. |
required |
locale
|
str
|
A canonical supported locale. |
required |
param
|
str
|
Query-parameter name. Defaults to
:data: |
LOCALE_QUERY_PARAM
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The URL with the locale parameter appended. |
SUPPORTED_LOCALES
module-attribute
¶
Locales the SDK ships bundled auth templates for. pt-BR is first
so it acts as the default when nothing else matches.
SignupHook
module-attribute
¶
Post-create hook for POST /auth/signup.
Awaited as on_signup(session, user, payload) right after the row is
inserted and before the commit, which is what makes it the place to
write the columns a product-specific signup_schema added: the
account and its extra fields become one transaction, so a rejected
field cannot leave a half-built user behind.
The second argument is the created row — an instance of the service's
own user_model — and the third is the validated body, an instance of
whatever signup_schema declared. Annotate your hook with those two
concrete classes, which is what makes user.phone = … type-check on
your side.
Both are Any here on purpose. Callable parameters are contravariant,
so an alias naming BaseUserModel and SignupSchema would reject
exactly the hook everyone writes — one typed against their own model and
their own schema — and push every consumer into a cast for no gain:
the SDK can only ever pass those two objects, so the narrowing is sound
and it is the consumer, not the SDK, that knows the real types.
AuthUserSchema
¶
Bases: BaseResponseSchema
The authenticated account, as returned by GET /auth/me.
Covers exactly the columns
:class:~tempest_fastapi_sdk.db.user_model.BaseUserModel
guarantees, so it is safe as the default response model for any
project: id / is_active / created_at / updated_at
come from :class:BaseResponseSchema, and email / is_admin
/ last_login_at / email_verified_at are added here.
hashed_password is deliberately absent. FastAPI serializes the
handler's return value through the response model, so a column
the schema does not declare never reaches the wire — that is what
makes the default safe even though the handler hands over the whole
ORM instance.
A project whose user table carries extra fields (a display name, an
avatar, a tenant id) subclasses this and passes the subclass as
me_response_model to
:func:tempest_fastapi_sdk.make_auth_router::
class UserResponseSchema(AuthUserSchema):
name: str | None = None
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The account's login identifier. |
is_admin |
bool
|
Whether the account may reach the admin site. |
last_login_at |
datetime | None
|
Timestamp of the most recent
successful login; |
email_verified_at |
datetime | None
|
When ownership of the
current email was proven; |
EmailChangeConfirmSchema
¶
Bases: BaseSchema
Request body for POST /auth/email-change/confirm.
Carries the opaque token the user copied from the confirmation link sent to their new address. The service consumes the token (one-shot) and flips the account email to the staged value.
Attributes:
| Name | Type | Description |
|---|---|---|
token |
str
|
Opaque token issued by |
EmailChangeRequestSchema
¶
Bases: BaseSchema
Request body for POST /auth/email-change/request.
Used by an already-authenticated user to start moving to a new
email address. The bearer access_token identifies the user;
current_password re-confirms ownership before the change is
staged. A confirmation link is sent to the NEW address — the change
only takes effect once that link is confirmed.
Attributes:
| Name | Type | Description |
|---|---|---|
new_email |
EmailStr
|
The address the user wants to move to. |
current_password |
str
|
The user's current plaintext password,
re-entered for confirmation. A mismatch returns |
EmailChangeResponseSchema
¶
Bases: BaseSchema
Response body for the email change / verify / recovery request endpoints.
message is a generic, constant string. confirm_url is
populated only when AUTH_RETURN_TOKEN_IN_RESPONSE=True or when
the [email] extra isn't installed — otherwise the link travels
only through email.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
str
|
Human-readable summary of the next step. |
confirm_url |
str | None
|
Confirmation URL when the caller asked
for an inline response, |
EmailChangeToken
¶
Bases: BaseSchema
Service-level result of issuing an email-change token.
Returned by :meth:UserAuthService.request_email_change /
:meth:request_email_recovery when the caller asked the service to
surface the link (AUTH_RETURN_TOKEN_IN_RESPONSE=True or no
:class:EmailUtils wired). The plaintext token is one-shot, hashed
at rest, and expires after AUTH_EMAIL_CHANGE_TTL_SECONDS.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
UUID of the user the token authorizes. |
new_email |
str
|
The pending new address the token confirms. |
token |
str
|
Plaintext token — display once, never store. |
url |
str
|
Confirmation URL with the token already substituted
into |
expires_at |
datetime
|
UTC timestamp the token becomes invalid. |
EmailRecoveryRequestSchema
¶
Bases: BaseSchema
Request body for POST /auth/email-recovery/request.
The unauthenticated recovery entry point for a user who lost
access to their mailbox. Identity is proven by the account password
(and a valid MFA code when TOTP is enrolled) rather than a bearer
token. Always returns 202 with a generic message so the endpoint
can't be used to enumerate accounts. On success a confirmation link
is sent to the NEW address and a security notice to the old one.
Attributes:
| Name | Type | Description |
|---|---|---|
email |
EmailStr
|
The account's CURRENT (old) email — locates the account. |
new_email |
EmailStr
|
The address the user wants to move to. |
current_password |
str
|
The account password, for identity proof. |
mfa_code |
str | None
|
TOTP or recovery code — required when the account has MFA enrolled, ignored otherwise. |
EmailVerificationToken
¶
Bases: BaseSchema
Service-level result of issuing an email re-verification token.
Returned by :meth:UserAuthService.request_email_verification when
the caller asked the service to surface the link. Confirms the
user's CURRENT email (no address change). Expires after
AUTH_EMAIL_VERIFICATION_TTL_SECONDS.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
UUID of the user the token authorizes. |
token |
str
|
Plaintext token — display once, never store. |
url |
str
|
Verification URL with the token already substituted
into |
expires_at |
datetime
|
UTC timestamp the token becomes invalid. |
LogoutSchema
¶
Bases: BaseSchema
Request body for POST /auth/logout.
Carries the refresh token to revoke so the session can be
killed before its natural expiry. Only meaningful when the
service is wired with a refresh_token_model (DB-backed
refresh tokens) — in stateless mode the endpoint is not
mounted, since a stateless JWT cannot be revoked.
Attributes:
| Name | Type | Description |
|---|---|---|
refresh_token |
str
|
The opaque refresh token to revoke. Its whole rotation family is revoked, so the descendant token a thief may hold dies too. |
all_sessions |
bool
|
When |
OAuthTokenLoginSchema
¶
Bases: BaseSchema
Request body for POST /auth/oauth/{provider}/token.
The token-in-hand half of social login. A native mobile client
completes the provider's own SDK flow on the device and ends up
holding an access token, with no browser to redirect through the
/login → consent → /callback dance. It posts that token
here and gets back the same session the redirect flow issues.
The token travels in the body, never in the path or the query
string: a URL is written to the access log, the browser history and
every Referer header on the way, and this value is a live
credential at the provider.
Attributes:
| Name | Type | Description |
|---|---|---|
access_token |
str
|
The provider's OAuth2 access token, as the
device SDK returned it. Exchanged for the profile through
the registered client's |
token_type |
str
|
Scheme the |
PasswordChangeSchema
¶
Bases: BaseSchema
Request body for POST /auth/password-change.
Used by an already-authenticated user to rotate their own
password. Unlike the reset flow there is no token — the bearer
access_token identifies the user and current_password
re-confirms ownership before the new password is accepted.
Attributes:
| Name | Type | Description |
|---|---|---|
current_password |
str
|
The user's current plaintext password,
re-entered for confirmation. A mismatch is rejected with
|
new_password |
str
|
Plaintext replacement password. The schema
only rejects empty strings; the effective minimum length
and complexity come from |
code |
str | None
|
A TOTP code or a recovery code. Only an account
with MFA enrolled reads it: with a valid code the response
carries a new pair; without one the password still changes and
the response is the |
RefreshSchema
¶
Bases: BaseSchema
Request body for POST /auth/refresh.
Carries the long-lived refresh token so the caller can mint a fresh
access_token + refresh_token pair without re-entering their
email and password. Both tokens rotate on success — store the new
refresh token and discard the one sent here.
Attributes:
| Name | Type | Description |
|---|---|---|
refresh_token |
str
|
The refresh JWT issued by login / signup /
activation / password-reset / mfa-verify. Must still carry
the |
apply_auth_cookies
¶
apply_auth_cookies(
response: Response,
*,
access_token: str,
refresh_token: str | None,
config: AuthCookieConfig,
) -> None
Stamp the access (and optional refresh) cookie on response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
Response
|
The outgoing response to mutate. |
required |
access_token
|
str
|
The freshly issued access token. |
required |
refresh_token
|
str | None
|
The freshly issued refresh token, or
|
required |
config
|
AuthCookieConfig
|
The cookie security attributes. |
required |
AuthCookieConfig
dataclass
¶
AuthCookieConfig(
access_name: str = "access_token",
refresh_name: str = "refresh_token",
access_max_age: int = 3600,
refresh_max_age: int = 1209600,
refresh_path: str = "/",
secure: bool = True,
samesite: SameSite = "lax",
domain: str | None = None,
http_only: bool = True,
)
Security attributes for the auth cookie pair.
The access cookie is scoped to / so it rides along with every
request; the refresh cookie is scoped to refresh_path (the
refresh endpoint) so the long-lived token is never sent on ordinary
calls, shrinking its exposure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_name
|
str
|
Cookie name for the short-lived access token. |
'access_token'
|
refresh_name
|
str
|
Cookie name for the long-lived refresh token. |
'refresh_token'
|
access_max_age
|
int
|
Access-cookie lifetime in seconds. Mirror
|
3600
|
refresh_max_age
|
int
|
Refresh-cookie lifetime in seconds.
Mirror |
1209600
|
refresh_path
|
str
|
Path the refresh cookie is scoped to.
Defaults to |
'/'
|
secure
|
bool
|
Emit the |
True
|
samesite
|
SameSite
|
|
'lax'
|
domain
|
str | None
|
Cookie |
None
|
http_only
|
bool
|
Block JavaScript access. Defaults to |
True
|
clear_auth_cookies
¶
clear_auth_cookies(response: Response, *, config: AuthCookieConfig) -> None
Delete both auth cookies on response (logout).
The delete attributes mirror :func:apply_auth_cookies so the
browser actually drops the cookies — a delete_cookie whose
path / domain / flags don't match the original is silently
ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
Response
|
The outgoing response to mutate. |
required |
config
|
AuthCookieConfig
|
The cookie security attributes. |
required |
TokenDelivery
module-attribute
¶
How the auth router returns the JWT pair. See the module docstring.