Ir para o conteúdo

tempest_fastapi_sdk.auth

O fluxo de autenticação embutido: cadastro, ativação, login, reset de senha, JWT, OAuth e MFA TOTP.

« Admin, dados e API


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 src.db.models.UserModel.

required
token_model type[BaseUserTokenModel]

Concrete token model — usually src.db.models.UserTokenModel.

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, the service returns the link in the response (and never tries to send) — except under ENV=production, where every flow carrying a link answers 503 INTEGRATION_DISABLED instead (see :meth:require_mail_delivery).

None
passwords PasswordUtils | None

Override for tests; defaults to a fresh instance.

None
jwt JWTUtils | None

Override for tests; defaults to one built from jwt_settings.

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 src.db.models.UserRefreshTokenModel. Opt-in: when provided, refresh tokens become opaque, DB-backed, single-use values with real rotation, reuse detection and revocation. When None (default), the service keeps issuing the legacy stateless JWT refresh token (no DB persistence, no revocation).

None
oauth_account_model type[BaseUserOAuthAccountModel] | None

Concrete linked-identity model — usually src.db.models.UserOAuthAccountModel. Opt-in: required by :meth:login_with_oauth and therefore by the /auth/oauth/* endpoints; None (default) leaves social login unavailable.

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 code your clients already handle. None (default) raises the SDK's own classes.

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 user_model instance; True means refused, so a privileged account passes lambda user: user.is_staff. The argument is Any for the same reason as on_signup's: callable parameters are contravariant, so a signature naming BaseUserModel would reject the predicate everyone writes (typed against their own model). None (default) keeps every account on the current behavior. See :class:EmailLinkForbiddenException.

None
webauthn_credential_model type[BaseWebAuthnCredentialModel] | None

Concrete passkey table — usually src.db.models.UserWebAuthnCredentialModel, the one the project's :class:~tempest_fastapi_sdk.auth.webauthn.WebAuthnService stores into. Read by :meth:revoke_user_passkeys, which the account-recovery flows (:meth:confirm_password_reset, :meth:mfa_reset) run by default. None (default) means there are no passkeys to revoke; make_auth_router(webauthn=...) fills it from the WebAuthn service when it is left unset.

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_ACTIVATE is true and the user is born is_active=True; the caller can mint JWTs right away. The refuses_email_link predicate is not consulted, because an account born active depends on no link.
  • :class:ActivationToken — the user is inserted with is_active=False and an activation token is persisted (and mailed, when EmailUtils is wired) for the caller to surface.
  • :class:ActivationWithheld — the user is inserted with is_active=False but refuses_email_link matches the new row, so no token is persisted and no mail is sent: the link would only answer EMAIL_LINK_FORBIDDEN when used. The predicate sees the row as inserted, with fields applied and before any on_signup hook 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 AUTH_PASSWORD_MIN_LENGTH.

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 NOT NULL column the SDK does not know about (a phone, a document). Each key must be a mapped column of user_model outside :data:SIGNUP_PROTECTED_FIELDS and the model's __secret_columns__. None (default) sets nothing extra.

None

Returns:

Type Description
BaseUserModel

tuple[BaseUserModel, ActivationToken | ActivationWithheld | None]:

ActivationToken | ActivationWithheld | None

The persisted user and how it gets active — None when born

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 AUTH_AUTO_ACTIVATE is off and the e-mail integration is switched off — see :meth:require_mail_delivery. Raised before any row is written.

EmailDeliveryException

When the activation mail could not be sent (503 EMAIL_UNAVAILABLE). The user and token rows are flushed but not committed, so the caller's rollback drops them — make_auth_router never reaches its commit and the request session discards both. Signup already answers 409 for a taken address, so the 503 tells a caller nothing it could not learn there.

ValueError

When fields names something that is not a column of user_model, or a protected column; and when the insert is refused because a NOT NULL column got no value — a wiring defect, so the message names the column instead of surfacing a bare IntegrityError.

ValidationException

When the password is too short.

ConflictException

When the email, or another unique column, is already taken. For a column other than email the row is refused by the database, and details["columns"] carries what the server named; the session must then be rolled back before reuse, as after any failed flush.

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 name column.

None
fields Mapping[str, Any] | None

Extra column values, with the same rules as signup(fields=...).

None
is_admin bool

Whether the new account is an administrator. False by default; it is a parameter, not a fields key, because is_admin is a protected column.

False

Returns:

Name Type Description
BaseUserModel BaseUserModel

The persisted user, is_active=True.

Raises:

Type Description
ValueError

When fields names a protected column or something that is not a column, or a NOT NULL column got no value.

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). False is the explicit opt-out.

True
revoke_passkeys bool

Delete every WebAuthn credential of the user (default). False is the explicit opt-out. Without a webauthn_credential_model there is nothing to delete.

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 user_id.

signup_column_names

signup_column_names() -> frozenset[str]

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

signup_protected_fields() -> frozenset[str]

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 refuses_email_link matches the account — exceptions.email_link_forbidden. The token is consumed, the spend is committed, and is_active is left untouched.

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 (AUTH_RETURN_TOKEN_IN_RESPONSE, or no

ActivationToken | None

EmailUtils wired) and the account was indeed pending;

ActivationToken | None

None otherwise, including when the mail failed.

Raises:

Type Description
IntegrationDisabledException

When the e-mail integration is switched off — see :meth:require_mail_delivery.

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 (exceptions.invalid_credentials). The message is deliberately generic so attackers can't enumerate accounts.

ForbiddenException

When AUTH_REVEAL_INACTIVE_ACCOUNT is on and the right password opens a deactivated account (exceptions.account_inactive).

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:

  1. (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.
  2. 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; None means 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 by AUTH_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 under AUTH_AUTO_ACTIVATE, AUTH_RETURN_TOKEN_IN_RESPONSE or a service without EmailUtils: there, an active row says nothing about who owns its address.
  3. 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:~tempest_fastapi_sdk.resolve_locale resolved it. Required rather than defaulted because it is what picks the placeholder display name — a silent default would answer a Portuguese user in English.

required
link_by_verified_email bool | None

Override for AUTH_OAUTH_LINK_BY_VERIFIED_EMAIL. None (default) reads the setting.

None
allow_account_creation bool | None

Override for AUTH_OAUTH_ALLOW_ACCOUNT_CREATION, which itself falls back to AUTH_SIGNUP_ENABLED. None (default) walks that chain.

None

Returns:

Type Description
BaseUserModel

tuple[BaseUserModel, str, str]: The authenticated user and

str

the (access_token, refresh_token) pair, identical in

str

shape to what POST /auth/login returns.

Raises:

Type Description
RuntimeError

When the service was built without an oauth_account_model. A configuration error, not a request error.

OAuthEmailMissingException

When the provider returned no email. The column is NOT NULL UNIQUE, so there is nothing to store and inventing an address would create an account nobody can recover.

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 AUTH_OAUTH_LINK_BY_VERIFIED_EMAIL.

None
allow_account_creation bool | None

Override for AUTH_OAUTH_ALLOW_ACCOUNT_CREATION.

None

Returns:

Name Type Description
BaseUserModel BaseUserModel

The authenticated, active user.

Raises:

Type Description
RuntimeError

When the service was built without an oauth_account_model.

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 oauth_account_model.

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 oauth_account_model.

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, None

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:require_mail_delivery. Raised before the lookup, for known and unknown addresses alike.

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). False is the explicit opt-out, for a caller that ends the sessions some other way.

True
revoke_passkeys bool

Delete every WebAuthn credential of the user (default). False is the explicit opt-out. Without a webauthn_credential_model there is nothing to delete.

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:activate and :meth:confirm_email_change.

ForbiddenException

exceptions.email_link_forbidden — 403 — when the refuses_email_link predicate matches the account. The token is spent and the spend is committed, so the link cannot be retried; the password hash is left untouched.

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). False is the explicit opt-out, for a caller that ends the sessions some other way.

True

Returns:

Name Type Description
BaseUserModel BaseUserModel

The user whose password was rotated.

Raises:

Type Description
UnauthorizedException

When current_password does not match the stored hash.

ValidationException

When new_password violates the configured password policy.

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 (AUTH_RETURN_TOKEN_IN_RESPONSE

EmailChangeToken | None

or no EmailUtils), None when the link only travels by

EmailChangeToken | None

email.

Raises:

Type Description
IntegrationDisabledException

When the e-mail integration is switched off — see :meth:require_mail_delivery.

UnauthorizedException

When current_password is wrong.

ValidationException

When new_email equals the current one.

ConflictException

When new_email is already in use.

EmailDeliveryException

When the confirmation mail could not be sent (503 EMAIL_UNAVAILABLE). The token row is flushed but not committed, so the caller's rollback drops it and a pending link from an earlier request survives. The caller is authenticated, so there is nothing to enumerate.

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). False is the explicit opt-out, for a caller that ends the sessions some other way.

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 AUTH_EMAIL_CHANGE_NOTIFY_OLD is on and the e-mail integration is switched off — see :meth:require_mail_delivery. Raised before the token is consumed, so the link keeps working once e-mail is back.

EmailDeliveryException

When AUTH_EMAIL_CHANGE_NOTIFY_OLD is on and the notice to the old address could not be sent (503 EMAIL_UNAVAILABLE). The new address and the token spend are flushed but not committed: the caller's rollback undoes both, so the account keeps its old address and the same link can be confirmed again once the server is back. The change is never applied without the notice the setting promises.

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, None when it only travels by

EmailVerificationToken | None

email.

Raises:

Type Description
IntegrationDisabledException

When the e-mail integration is switched off — see :meth:require_mail_delivery.

EmailDeliveryException

When the mail could not be sent (503 EMAIL_UNAVAILABLE). The token row is flushed but not committed, so the caller's rollback drops it. The caller is authenticated, so there is nothing to enumerate.

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 mfa_code.

None
login_throttle AttemptThrottle | None

The per-e-mail login budget.

None
login_ip_throttle AttemptThrottle | None

The per-IP login budget, keyed f"login-ip:{client_ip}". Ignored without client_ip.

None
client_ip str | None

The caller's address, for login_ip_throttle.

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, None otherwise (including every soft

EmailChangeToken | None

identity-proof failure and every spent budget).

Raises:

Type Description
ValidationException

When recovery_code_model is missing for an MFA-enrolled account, or new_email equals the current one.

ConflictException

When new_email is already in use.

IntegrationDisabledException

When the e-mail integration is switched off — see :meth:require_mail_delivery. Raised before the lookup, so it reveals nothing about the account.

EmailDeliveryException

When the confirmation mail could not be sent (503 EMAIL_UNAVAILABLE). Unlike the soft failures this is raised, not turned into None: the send happens only after the password (and the MFA code, when enrolled) matched, so the 503 is answered only to someone who already proved the account is theirs — the same point where a taken new_email answers 409. The token row is flushed but not committed, so the caller's rollback drops it.

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 amr on both tokens so a refresh repeats them. Defaults to :data:~tempest_fastapi_sdk.PASSWORD_AMR. None omits the claim (an origin nobody recorded).

PASSWORD_AMR

Returns:

Type Description
str

tuple[str, str]: (access_token, refresh_token) — both

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_model set — the access token is a stateless JWT, the refresh token is an opaque value persisted (hashed) as a single-use row. family_id ties the new token to a rotation lineage; None starts a fresh family (a brand-new login).
  • refresh_token_model is None — 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 starts a new family.

None
amr Sequence[str] | None

RFC 8176 methods the session was authenticated with. Stamped as amr on the access token and stored with the refresh token, so every rotation repeats it. Defaults to :data:~tempest_fastapi_sdk.PASSWORD_AMR; the bundled router passes :data:~tempest_fastapi_sdk.MFA_AMR after the second factor. None omits the claim.

PASSWORD_AMR

Returns:

Type Description
str

tuple[str, str]: (access_token, refresh_token) — the

str

refresh_token is plaintext (opaque) or a JWT depending

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_model set (DB-backed) — the opaque token is looked up by hash. A token that is unknown, expired or already revoked is rejected with 401. Replaying an already-rotated token (used_at set) is treated as a stolen-token signal: the entire family is revoked and the call raises 401. On success the presented token is marked used_at and a new opaque token is minted in the same family. The database decides the rotation in one conditional UPDATE (:meth:_spend_refresh_record), so two concurrent redemptions of one token yield one new pair and one 401 that revokes the family — never two live descendants.
  • refresh_token_model is None (stateless / legacy) — the refresh JWT is decoded and must carry the refresh claim, 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 exp claim (HTTP 401).

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 True, revoke every active token of the user, not just this family. Defaults to False.

False

revoke_user_sessions async

revoke_user_sessions(session: AsyncSession, *, user_id: UUID) -> int

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

revoke_user_passkeys(session: AsyncSession, *, user_id: UUID) -> int

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 — 0 without a

int

webauthn_credential_model.

add_session_revoker

add_session_revoker(revoker: Callable[[UUID], Awaitable[int]]) -> None

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 sub claim — the user id.

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 sub claim — the user id.

required

Returns:

Name Type Description
BaseUserModel BaseUserModel

The loaded user.

Raises:

Type Description
RuntimeError

When the service was created without db=.

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 True, the dependency returns None instead of raising on a missing / invalid token — for endpoints that work both authenticated and anonymous.

False
session_dependency Callable[..., Any] | None

The request-scoped session provider to share with repositories. Defaults to self.db.session_dependency.

None
cookie_name str | None

Cookie to read the access token from when the Authorization header is absent (the header still wins). None (default) auto-derives it from AUTH_ACCESS_COOKIE_NAME whenever AUTH_TOKEN_DELIVERY is "cookie" or "both" — so a route guarded by this dependency accepts the cookie the bundled login set, with no extra wiring. Pass an explicit name to force it, or a bearer-only delivery mode leaves it None (header only).

None
query_param str | None

Query-string parameter to read the access token from when both the Authorization header and the cookie are absent (lookup order: header → cookie → query). None (default) disables it. Unlike cookie_name it is never auto-derived — it is an opt-in escape hatch for cookieless clients such as the browser EventSource (SSE), which cannot send a header. A token in the URL leaks into access logs, history and the Referer header, so enable it only over TLS with short-lived access tokens (never a refresh token).

None
strict bool

Refuse a token that carries no recognizable type marker. False (default) accepts it, which is the compatibility window for sessions minted before the typ claim existed. A service whose legacy tokens declared their type under a claim of their own has no typ and no SDK fallback marker on any of them, so under the default each of its refresh tokens authorizes any route for the length of its TTL — that service wants strict=True.

False
legacy_claims Collection[str]

Extra claim names to read the token type from when typ is absent, in order. Pair with strict=True. See :func:~tempest_fastapi_sdk.token_type_allowed.

()
require_active bool

Refuse a token whose account is no longer active (default True). login already refuses an inactive account, but a token issued before the deactivation stays valid until it expires — up to the whole access TTL — so without this check every route had to remember :func:~tempest_fastapi_sdk.require_active. False restores the pre-0.305.0 behavior, for the one route that must serve an inactive account (reactivation).

True
inactive_exception GuardException | None

Factory for the refusal of an inactive account. None (default) raises :meth:inactive_account_error — 403 ACCOUNT_INACTIVE, or the product's exceptions.account_inactive. With soft=True an inactive account yields None instead, as an invalid token does.

None
unauthorized_message str

detail of the 401 for a missing or invalid token, or one whose account no longer exists. Defaults to :data:~tempest_fastapi_sdk.exceptions.unauthorized.MISSING_TOKEN_MESSAGE, in English. Before this parameter a service answering in another language could not reword it: the dependency built here forwarded no message to :func:~tempest_fastapi_sdk.make_jwt_user_dependency, and the English phrase reached the end user.

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 None in soft mode).

Raises:

Type Description
RuntimeError

When the service was created without db=.

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:current_user_dependency.

None
strict bool

Refuse access tokens without a type marker; see :meth:current_user_dependency.

False
legacy_claims Collection[str]

Extra claims naming a legacy token's type; see :meth:current_user_dependency.

()
allow_access_token_query bool

Also open the stream with the access token in ?<access_token_param>=. False (default) refuses it.

False
access_token_param str

Query parameter read when allow_access_token_query is set. Defaults to "access_token".

'access_token'
channel_for Callable[[Any], str] | None

Maps the user to its broker channel. None (default) uses str(user.id).

None
prefix str

URL prefix. Defaults to "/sse".

'/sse'
tag str

OpenAPI tag. Defaults to "SSE".

'SSE'
ticket_ttl timedelta | None

Ticket lifetime. None (default) uses :data:~tempest_fastapi_sdk.DEFAULT_SSE_TICKET_TTL.

None
ticket_param str

Query parameter of the ticket. Defaults to "ticket".

'ticket'

Returns:

Name Type Description
APIRouter APIRouter

The router, ready for app.include_router.

Raises:

Type Description
RuntimeError

When the service was created without db=.

ValueError

When allow_access_token_query is set and access_token_param equals ticket_param, or ticket_ttl is shorter than one second.

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

exceptions.account_inactive with the

ForbiddenException

ACCOUNT_INACTIVE message key (403 by default).

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 (default) raises :class:UnauthorizedException with the generic UNAUTHORIZED code.

None

Returns:

Name Type Description
UserT UserT

The same user, narrowed to non-None.

Raises:

Type Description
AppException

When user is None — whatever exception builds, or :class:UnauthorizedException (HTTP 401).

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 is_active is falsy. None (default) raises :class:ForbiddenException.

None
unauthenticated GuardException | None

Factory for the user is None case.

None

Returns:

Name Type Description
UserT UserT

The authenticated, active user.

Raises:

Type Description
AppException

When user is None (HTTP 401 by default) or user.is_active is falsy (HTTP 403 by default).

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 is_admin is falsy. None (default) raises :class:ForbiddenException with the generic FORBIDDEN code — which is exactly what a project carrying its own USER_IS_NOT_ADMIN needs to replace.

None
unauthenticated GuardException | None

Factory for the user is None case.

None

Returns:

Name Type Description
UserT UserT

The authenticated admin user.

Raises:

Type Description
AppException

When user is None (HTTP 401 by default) or user.is_admin is falsy (HTTP 403 by default).

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

True when the account refuses emailed links. Always

bool

False under the default refuses_email_link=None.

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

require_mail_delivery(*, carries_token: bool = True) -> None

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 (default) for a mail carrying a link, which AUTH_RETURN_TOKEN_IN_RESPONSE replaces by the response body. False for the security notice to the old address after an e-mail change, which that flag does not cover.

True

Raises:

Type Description
IntegrationDisabledException

When the wired mailer is disabled and the operation would need it, or outside development/test (ENV unset included) when the link would be surfaced in the response.

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:~tempest_fastapi_sdk.PASSWORD_AMR after /auth/login, ["ext"] after a social login, ["email"] after an activation or reset link. Stored as the token's amr claim, which :meth:second_factor_amr reads back at /auth/mfa/verify. None omits it.

PASSWORD_AMR

Returns:

Name Type Description
str str

The generated value.

second_factor_amr

second_factor_amr(mfa_token: str) -> tuple[str, ...]

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:mfa_verify just accepted.

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:BaseUserRecoveryCodeModel.

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 user (409, code MFA_ALREADY_ENROLLED).

TypeError

When user does not compose :class:~tempest_fastapi_sdk.MFAMixin, so there is no column to stage the secret in. Raised before any write.

ImportError

When the [mfa] extra is not installed.

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). False is the explicit opt-out, for a caller that ends the sessions some other way; the tokens it keeps still refresh with the amr they were born with, never with "otp".

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:mfa_enroll first).

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 (default) accepts TOTP codes only.

None
throttle AttemptThrottle | None

Failure budget for the second factor, keyed on f"mfa:{user_id}" like :meth:mfa_verify. None (default) leaves the factor check unthrottled.

None

Returns:

Name Type Description
BaseUserModel BaseUserModel

The account, attached to session.

Raises:

Type Description
UnauthorizedException

When the password does not match, or when MFA is enrolled and code is missing or matches neither an unspent TOTP step nor an unused recovery code.

MfaThrottledException

When throttle has the account's attempt budget spent. Raised before the code is checked.

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:mfa_confirm, :meth:mfa_verify or an earlier call) is refused like a wrong one.

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 user are deleted.

required
revoke_sessions bool

Revoke every refresh token of the user through :meth:revoke_user_sessions (default): whoever holds the lost device may hold a live session too. False is the explicit opt-out.

True
revoke_passkeys bool

Delete every WebAuthn credential of the user (default). False is the explicit opt-out. Without a webauthn_credential_model there is nothing to delete.

True

Returns:

Name Type Description
int int

How many refresh-token rows were revoked — 0 with

int

revoke_sessions=False or without a refresh_token_model.

Raises:

Type Description
ValidationException

When MFA is not active for user.

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 f"mfa:{user_id}" — the account, not mfa_token, because step 1 mints a fresh token on every login and a per-token key would hand the budget back to whoever retries /auth/login. Each verification reserves one attempt before the code is checked, and the attempt past max_attempts is refused with 429 whatever the code; a success resets the key, so only wrong codes accumulate. Reserving first, rather than counting after the check, is what keeps a burst of concurrent guesses from all passing a "not blocked yet" read together. None (default) leaves the call unthrottled — the bundled router always passes one.

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 mfa_token, bad code, user not enrolled in MFA, or a TOTP code whose step was already accepted.

MfaThrottledException

When throttle has the account's attempt budget spent (429, carrying Retry-After). Raised before the code is checked.

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 (default) accepts TOTP codes only — a recovery code then reads as a wrong code.

None
revoke_sessions bool

Revoke every refresh token of the user (default). False is the explicit opt-out, for a caller that ends the sessions some other way.

True
throttle AttemptThrottle | None

Failure budget, keyed on f"mfa:{user_id}" — the same key :meth:mfa_verify uses, so guesses here and at the login step draw on one budget. Reserved before the code is checked and reset on success. None (default) leaves the call unthrottled.

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 AUTH_MFA_ENABLED kill-switch is off); nothing is spent.

ValidationException

When new_password breaks the policy; the code is not checked, so it is not spent.

MfaThrottledException

When throttle has the account's attempt budget spent. Raised before the code is checked.

UnauthorizedException

When code matches neither an unspent TOTP step nor an unused recovery code.

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. 0 disables caching entirely.

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:~uuid.UUID).

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. 0 disables caching. Defaults to 30.

30
required_app str | None

When provided, the caller's app_claim list must contain this value, otherwise access is forbidden. Defaults to None (no app gate).

None
app_claim str

Claim name holding the list of accessible applications. Defaults to "access_apps".

'access_apps'
subject_claim str

Claim name holding the subject id. Defaults to "sub".

'sub'
timeout float

Total timeout, in seconds, applied to each upstream request via :class:httpx.Timeout. Ignored when http_client is injected. Defaults to 10.0.

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.

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 () — no binding, with a warning logged.

()

fetch_userinfo async

fetch_userinfo(token: str) -> dict[str, Any]

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:httpx.HTTPError), returns 401 / 403 (the token is also evicted from the cache), returns any other non-200 status, or — with :attr:audiences set — answers for a token issued to another client.

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 HTTPBearer scheme, or None when no Authorization header was sent.

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:audiences.

ForbiddenException

When required_app is configured and is absent from the caller's app_claim list.

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 HTTPBearer scheme, or None when no Authorization header was sent.

None

Returns:

Name Type Description
UUID UUID

The subject claim parsed as a :class:~uuid.UUID.

Raises:

Type Description
UnauthorizedException

When the token is missing / invalid, or the subject claim is absent or not a valid UUID.

ForbiddenException

When required_app is configured and is absent from the caller's app_claim list.

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:

  1. credentials_json — the service-account JSON inline, for deployments that inject it as an environment variable and mount no file.
  2. credentials_path — a service-account file on disk.
  3. 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 firebase_admin app.

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 credentials_json is given.

None
credentials_json str | None

The service-account JSON itself, as a string. Takes precedence over credentials_path.

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 firebase_admin app to create or reuse. Defaults to :data:DEFAULT_FIREBASE_APP_NAME. Pass a distinct name to talk to a second Firebase project from the same process.

DEFAULT_FIREBASE_APP_NAME
check_revoked bool

When True, every verification also checks revocation and whether the user is disabled, which reaches the Firebase backend. Defaults to False (signature + claims only, no network per request once the certificates are cached).

False
clock_skew_seconds int

Seconds of tolerance for the token's iat / exp claims. Defaults to 0.

0
enabled bool

False builds an authenticator for an integration switched off by FIREBASE_ENABLED=false: no app is initialized (the [firebase] extra is not even imported), :meth:verify and the dependencies built on it raise :class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException (503, details={"integration": "firebase"}), and an :class:~tempest_fastapi_sdk.push.FCMTransport built on it claims no platform. FirebaseSettings.firebase_kwargs passes it. Defaults to True.

True

Raises:

Type Description
ImportError

When the optional [firebase] extra is not installed and enabled is True.

FirebaseCredentialError

When the credential cannot be built or the app cannot be initialized.

app property

app: App

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 firebase_admin.App bound to :attr:app_name.

App

firebase_admin ships no py.typed, so a checker that

App

does not infer from untyped sources (mypy) still sees Any.

Raises:

Type Description
IntegrationDisabledException

When built with enabled=False.

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 Bearer prefix.

required

Returns:

Name Type Description
FirebaseIdentity FirebaseIdentity

The verified identity.

Raises:

Type Description
IntegrationDisabledException

When built with enabled=False (503); nothing is verified.

FirebaseTokenRevokedError

When the token was revoked (check_revoked=True only).

FirebaseTokenExpiredError

When the token has expired.

FirebaseUserDisabledError

When the Firebase user is disabled (check_revoked=True only).

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 HTTPBearer scheme, or None when no Authorization header was sent.

None

Returns:

Name Type Description
FirebaseIdentity FirebaseIdentity

The verified identity.

Raises:

Type Description
IntegrationDisabledException

When built with enabled=False — checked first, so a request without a token gets the same 503 as one with a token.

FirebaseTokenMissingError

When no credentials were supplied.

UnauthorizedException

Any of the verification failures documented on :meth:verify.

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 HTTPBearer scheme, or None when no Authorization header was sent.

None

Returns:

Type Description
FirebaseIdentity | None

FirebaseIdentity | None: The verified identity, or None

FirebaseIdentity | None

when the request carried no usable token.

Raises:

Type Description
IntegrationDisabledException

When built with enabled=False; a disabled integration is not an anonymous caller.

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 HTTPBearer scheme, or None when no Authorization header was sent.

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:verify.

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 sub).

email str | None

The email on the token, when the sign-in provider supplied one.

email_verified bool

Whether Firebase considers that email verified. False when the claim is absent.

phone_number str | None

The phone number on the token, for phone sign-in.

provider str

The firebase.sign_in_provider claim — "password", "google.com", "apple.com", "phone", "anonymous", … Empty when absent.

claims Mapping[str, Any]

Every claim the token carried, including custom claims set with set_custom_user_claims. Read this for anything the fields above do not model.

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 uid nor sub, so there is no subject to authenticate.

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 None when no such user exists.

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 HTTPBearer scheme, or None when no Authorization header was sent.

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:FirebaseAuth.verify.

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 HTTPBearer scheme, or None when no Authorization header was sent.

None

Returns:

Type Description
UserT | None

UserT | None: The resolved user, or None.

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

FirebaseTokenMissingError(
    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 a request carries no Authorization: Bearer header.

FirebaseTokenInvalidError

FirebaseTokenInvalidError(
    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 is malformed or fails verification.

FirebaseTokenExpiredError

FirebaseTokenExpiredError(
    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's exp claim is in the past.

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 AUTH_REVEAL_INACTIVE_ACCOUNT is on — a deactivated account, on login.

account_inactive type[ForbiddenException]

The right password on a deactivated account, on login, when AUTH_REVEAL_INACTIVE_ACCOUNT is 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 UserAuthService(refuses_email_link=...) tries to spend an activation or password-reset link.

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

MfaThrottledException(
    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/mfa/verify is over the per-account budget.

SignupThrottledException

SignupThrottledException(
    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/signup is over the per-client budget.

DEFAULT_FIREBASE_APP_NAME module-attribute

DEFAULT_FIREBASE_APP_NAME: str = '[DEFAULT]'

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 get_session the rest of the app uses, sub-dependencies included (get_session(database=Depends(get_database))), or db.session_dependency where db is an :class:AsyncDatabaseManager. An (async) generator function is registered as Depends(session_factory) itself, so an app.dependency_overrides[session_factory] reaches the auth routes too; any other zero-argument callable returning an async iterator is wrapped and iterated, as before.

required
prefix str

The full public path the auth routes live under; defaults to "/auth". Pass the whole path here (prefix="/api/auth") rather than adding one through app.include_router(router, prefix=...): the router also writes this value into the URLs it builds itself, and it cannot see a prefix added at mount time. The refresh cookie's Path (AuthCookieConfig.refresh_path) is prefix (prefix + "/cookie" in both mode), the backend-rendered password-reset form posts to prefix + "/password-reset/{token}", and the OAuth state cookie is scoped to prefix. Mounting make_auth_router(prefix="/auth") with include_router(..., prefix="/api") serves /api/auth/login but sets the refresh cookie with Path=/auth, which the browser never sends to /api/auth/refresh; and include_router(..., prefix="/api/auth") doubles it into /api/auth/auth/*.

'/auth'
tags list[str] | None

OpenAPI tags. Defaults to ["auth"].

None
template_dir str | None

Optional directory holding HTML templates that override the SDK-bundled activation_success.html / activation_error.html / password_reset_form.html / password_reset_success.html / password_reset_error.html. Only consulted when AuthSettings.AUTH_BACKEND_LINKS=True.

None
me_response_model type[BaseModel] | None

Response model for GET /auth/me. None (default) uses :class:~tempest_fastapi_sdk.auth.schemas.AuthUserSchema, which covers exactly the columns BaseUserModel guarantees. Pass a subclass to expose the extra columns your user table carries — the endpoint hands the ORM instance to FastAPI, so whatever the model does not declare is never serialized.

None
allow_signup bool | None

Whether to mount POST /auth/signup. False leaves the route out of the application and out of the OpenAPI schema, which is what a closed system wants — accounts created by an administrator, never by whoever reaches the door. Activation is not unmounted with it: an admin-created account still completes /auth/activate/{token}. None (default) reads AuthSettings.AUTH_SIGNUP_ENABLED.

None
signup_schema type[SignupSchema] | None

Request body for POST /auth/signup. A subclass of :class:SignupSchema, so email / password / name keep their validation and the SDK keeps reading them by name; the extra fields are whatever the product's account carries at birth — a phone, a document, a role flag. Each extra field that is also a column of the user model (outside :meth:UserAuthService.signup_protected_fields) is set on the row before the insert, so a NOT NULL column needs no hook; a unique one that collides answers 409. The payload still reaches on_signup as-is. None (default) uses :class:SignupSchema.

None
on_signup SignupHook | None

Awaited right after the row is created and before the commit, as on_signup(session, user, payload). It is where the fields :paramref:signup_schema added get written onto the instance, and it runs inside the same transaction the row was inserted in — so a hook that raises rolls the account back instead of leaving a half-built one behind. Returning anything is ignored: the response is still :class:SignupResponseSchema.

None
token_delivery TokenDelivery | None

How login / refresh hand back the JWT pair — "bearer" (body only), "cookie" (HttpOnly cookies, body omits tokens) or "both" (bearer at /auth/* plus a parallel cookie set at /auth/cookie/*). None (default) reads AuthSettings.AUTH_TOKEN_DELIVERY.

None
cookie_config AuthCookieConfig | None

Override the cookie security attributes. None (default) builds one from the AUTH_COOKIE_* settings and the JWT TTLs. Only used when the delivery mode involves cookies.

None
recovery_code_model type[BaseUserRecoveryCodeModel] | None

Model storing the one-time MFA recovery codes. None (default) falls back to the SDK's bundled model, built on demand — pass your own when the project owns that table.

None
webauthn WebAuthnService | None

Configured :class:~tempest_fastapi_sdk.auth.webauthn.WebAuthnService. Required when AUTH_WEBAUTHN_ENABLED is on; it carries the relying-party identity, the credential model and the challenge store, none of which the router can infer. When the service was built without webauthn_credential_model, the router sets it to webauthn.credential_model, so the recovery flows (password reset, MFA reset) delete the user's passkeys.

None
oauth_clients Mapping[str, OAuthClient] | None

Social-login clients keyed by the provider name the URLs will carry — {"google": GoogleOAuthClient(...)} serves /auth/oauth/google/login. Required when AUTH_OAUTH_ENABLED is on. The key is stored on every linked-identity row, so renaming one after accounts exist orphans them. Anything satisfying :class:~tempest_fastapi_sdk.OAuthClient is accepted, so a provider the SDK does not ship is wired the same way Google is.

None
token_strict bool

Whether the router's authenticated routes refuse an access token carrying no recognizable type marker. False (default) accepts it — the compatibility window for sessions minted before the typ claim existed. A service whose legacy tokens declared their type under a claim of their own has no typ and no SDK fallback marker on any of them, so under the default each of its refresh tokens authorizes /auth/me, /auth/password-change and every other guarded route for the length of its TTL.

False
token_legacy_claims Collection[str]

Extra claim names to read the token type from when typ is absent, in order. Pair with token_strict=True: the claims classify the old tokens, strict refuses whatever stays unclassified. See :func:~tempest_fastapi_sdk.token_type_allowed.

()
mfa_throttle AttemptThrottle | None

Failure budget for POST /auth/mfa/verify, keyed per account (f"mfa:{user_id}"), so a fresh mfa_token from a new /auth/login does not reset it. Once the budget is spent the endpoint answers 429 with Retry-After before the code is checked; a successful verification clears the key. None (default) builds one over an :class:~tempest_fastapi_sdk.InMemoryThrottleBackend with MFA_THROTTLE_MAX_ATTEMPTS (5) wrong codes per MFA_THROTTLE_WINDOW_SECONDS (900). That counter lives in the process: with more than one worker or replica, pass an :class:~tempest_fastapi_sdk.AttemptThrottle over the shared Redis client instead.

None
login_throttle AttemptThrottle | Literal[False] | None

Failure budget for POST /auth/login (and the cookie login), keyed per normalized e-mail ("login:<sha256 of the e-mail>", so the backend never stores the address). Like mfa_throttle, each attempt reserves one unit before the password is checked and a successful login clears the key, so only wrong passwords accumulate; the attempt past max_attempts answers 429 with Retry-After whatever the password. The key is spent the same way for an e-mail that has no account, so the 429 does not tell which addresses exist. None (default) builds one over an :class:~tempest_fastapi_sdk.InMemoryThrottleBackend with LOGIN_THROTTLE_MAX_ATTEMPTS (5) per LOGIN_THROTTLE_WINDOW_SECONDS (900) — per process, so pass one over Redis with more than one worker. False turns the per-e-mail budget off (a service that limits login elsewhere). Whoever knows an e-mail can spend its budget and keep its owner out for one window: the trade every per-account lock makes.

None
login_ip_throttle AttemptThrottle | None

Failure budget for the login routes keyed per client IP ("login-ip:<addr>"), for one source trying many e-mails. Counts only wrong credentials, checked before the e-mail budget is spent; a success does not clear it, since one valid account would otherwise reset the counter between guesses. None (default) leaves it off: an IP key is only meaningful once trusted_ip_header names the header your edge sets — without it every client behind a proxy shares the proxy's address, and one budget would lock everyone out.

None
signup_throttle AttemptThrottle | None

Budget for POST /auth/signup keyed per client IP ("signup:<addr>"). Every attempt counts, successful or not, since the point is to cap account creation per source; the attempt past max_attempts answers 429 with Retry-After before the body reaches the service. None (default) leaves it off, for the same proxy reason as login_ip_throttle.

None
trusted_ip_header str | None

Single edge-set header holding the real client IP (e.g. "x-real-ip") for the IP-keyed throttles. None uses the transport peer. See :func:~tempest_fastapi_sdk.get_client_ip.

None
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

Notes

Which endpoint groups get mounted, and where:

  • JSON / SPA endpoints are always mounted, except POST /auth/signup, which is skipped when AUTH_SIGNUP_ENABLED is off (or allow_signup=False).
  • Cookie endpoints are mounted when AUTH_TOKEN_DELIVERY is cookie or both. In cookie mode they take the normal /login, /refresh and /logout paths; in both mode 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_LINKS is on.
  • MFA endpoints are mounted only when AUTH_MFA_ENABLED is on.
  • WebAuthn endpoints are mounted only when AUTH_WEBAUTHN_ENABLED is on and a webauthn service is passed.
  • Social-login endpoints are mounted only when AUTH_OAUTH_ENABLED is on, at least one client is passed, the service carries an oauth_account_model and the user model carries a name column. The callback honours AUTH_TOKEN_DELIVERY like every other login-equivalent step, except that both sets 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 AUTH_MFA_ENABLED is on without a recovery_code_model; when AUTH_WEBAUTHN_ENABLED is on without a webauthn service; or when AUTH_OAUTH_ENABLED is on and any of its three prerequisites — a client, an oauth_account_model, a name column — is missing; or when AUTH_BACKEND_LINKS is on and Jinja2 (the [email] extra) is not installed. Every one of these fails at construction rather than on the first request that needs the piece.

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/mfa without a session; otherwise the session opens and the browser goes to next or AUTH_PAGES_LOGIN_REDIRECT.
  • GET/POST /login/mfa — TOTP or recovery code over the pending step kept in the :data:AUTH_PAGES_MFA_COOKIE cookie.
  • GET/POST /signup — the form generated from signup_schema; only with signup enabled. Ends on "check your e-mail", or in a session with AUTH_AUTO_ACTIVATE.
  • GET /activate/{token} — activates and opens the session (amr=["email"]); an account with MFA goes to /login/mfa. Point AUTH_ACTIVATION_URL_TEMPLATE here.
  • 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 SESSION_* settings shape the cookie. Its revoke_all is registered on service (:meth:UserAuthService.add_session_revoker), so every flow that revokes the user's sessions — password reset, password change, e-mail change, the MFA resets — ends the cookie sessions too.

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 AUTH_MFA_ENABLED is on, for the recovery codes /login/mfa accepts.

None
allow_signup bool | None

Overrides AUTH_SIGNUP_ENABLED.

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. Mounted next to make_auth_router, pass both the same instance, or each router keeps a budget of its own and an e-mail gets both.

None
login_ip_throttle AttemptThrottle | None

Per-IP budget; off when None.

None
signup_throttle AttemptThrottle | None

Per-IP signup budget; :data:SIGNUP_THROTTLE_MAX_ATTEMPTS per window when None.

None
mfa_throttle AttemptThrottle | None

Per-account second-factor budget; the JSON route's default when None.

None
activation_throttle AttemptThrottle | None

Per-IP resend budget; :data:ACTIVATION_THROTTLE_MAX_ATTEMPTS per window when None.

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 AUTH_MFA_ENABLED is on without a recovery_code_model, or signup_schema does not subclass :class:SignupSchema.

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:HOST_COOKIE_PREFIX when secure and path is /.

secure bool

Whether the cookie is flagged Secure.

samesite Literal['lax', 'strict', 'none']

SameSite policy.

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 Secure. Leave True behind HTTPS; a Secure cookie is not sent back over plain HTTP, which makes every submit fail.

True
samesite Literal['lax', 'strict', 'none']

SameSite.

'lax'
path str

Cookie path. /, the only path the __Host- prefix allows.

'/'
max_age_seconds int

Cookie lifetime.

FORM_CSRF_MAX_AGE_SECONDS

issue

issue(request: Request) -> str

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

attach(response: Response, token: str) -> None

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

verify(request: Request, submitted: str) -> bool

Compare the submitted field with the cookie, in constant time.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
submitted str

The csrf_token form field.

required

Returns:

Name Type Description
bool bool

True only when both are present and equal.

is_local_path

is_local_path(value: str) -> bool

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 next parameter.

required

Returns:

Name Type Description
bool bool

True when redirecting to it stays on this site.

LOGIN_THROTTLE_MAX_ATTEMPTS module-attribute

LOGIN_THROTTLE_MAX_ATTEMPTS: int = 5

Wrong passwords one e-mail may submit to /auth/login per window.

LOGIN_THROTTLE_WINDOW_SECONDS module-attribute

LOGIN_THROTTLE_WINDOW_SECONDS: int = 900

Length, in seconds, of the default /auth/login failure window.

LOGIN_THROTTLED_MESSAGE module-attribute

LOGIN_THROTTLED_MESSAGE: str = 'too many login attempts, try again later'

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

MFA_THROTTLE_MAX_ATTEMPTS: int = 5

Wrong codes one account may submit to /auth/mfa/verify per window.

MFA_THROTTLE_WINDOW_SECONDS module-attribute

MFA_THROTTLE_WINDOW_SECONDS: int = 900

Length, in seconds, of the default /auth/mfa/verify failure window.

SIGNUP_THROTTLED_MESSAGE module-attribute

SIGNUP_THROTTLED_MESSAGE: str = 'too many signup attempts, try again later'

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 soft=True authenticated-user dependency, which yields None when no valid token was sent. A user model, a provider identity, anything a dependency returns.

required
exception GuardException | None

Factory for the refusal. None (default) raises :class:UnauthorizedException with the SDK's English message and the generic UNAUTHORIZED code. Pass your own class to keep your service's code and language.

None

Returns:

Name Type Description
SubjectT SubjectT

The same subject, narrowed to non-None (and to its

SubjectT

concrete subclass).

Raises:

Type Description
AppException

When user is None — whatever exception builds, or :class:UnauthorizedException (HTTP 401).

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 is_active is falsy. None (default) raises :class:ForbiddenException with the generic FORBIDDEN code.

None
unauthenticated GuardException | None

Factory for the user is None case. None (default) delegates to :func:require_authenticated.

None

Returns:

Name Type Description
UserT UserT

The authenticated, active user.

Raises:

Type Description
AppException

When user is None (HTTP 401 by default) or user.is_active is falsy (HTTP 403 by default).

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 is_admin is falsy. None (default) raises :class:ForbiddenException with the generic FORBIDDEN code.

None
unauthenticated GuardException | None

Factory for the user is None case. None (default) delegates to :func:require_authenticated.

None

Returns:

Name Type Description
UserT UserT

The authenticated admin user.

Raises:

Type Description
AppException

When user is None (HTTP 401 by default) or user.is_admin is falsy (HTTP 403 by default).

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 code should not have a generic default to fall back to silently.

required
unauthenticated GuardException | None

Factory for the user is None case. None (default) delegates to :func:require_authenticated's own default.

None

Returns:

Name Type Description
FlagGuard FlagGuard

A guard taking UserT | None and returning

FlagGuard

UserT.

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 allowed. Required: a guard whose whole point is the project's own code should not have a generic default to fall back to silently.

required
unauthenticated GuardException | None

Factory for the user is None case. None (default) delegates to :func:require_authenticated's own default.

None

Returns:

Name Type Description
FlagGuard FlagGuard

A guard taking UserT | None and returning

FlagGuard

UserT.

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 email-validator so malformed addresses fail at the Pydantic layer (422) instead of at insert time.

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:UserAuthService, so lowering / raising AUTH_PASSWORD_MIN_LENGTH (or toggling AUTH_PASSWORD_REQUIRE_COMPLEXITY) takes effect on the router path without the schema fighting it.

name str | None

Optional display name shown in the admin UI / front-end profile. None keeps the column NULL.

SignupResponseSchema

Bases: BaseSchema

Response body for POST /auth/signup.

The shape depends on the active settings:

  • When AUTH_AUTO_ACTIVATE=True the user is born active, activation_required=False and both access_token / refresh_token are 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 stay None and activation_url is set only when AUTH_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. None when the link travelled via email or activation was skipped.

access_token str | None

Short-lived JWT. Only set when activation_required=False.

refresh_token str | None

Long-lived JWT. Only set when activation_required=False.

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_token populated, mfa_token=None.
  • MFA required (step 1 of two-step login) — mfa_required=True, access_token / refresh_token=None, mfa_token populated. The frontend prompts for the TOTP code and replays it via POST /auth/mfa/verify to 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 mfa_required=False.

refresh_token str | None

Long-lived JWT — populated only when mfa_required=False.

mfa_required bool

When True, the caller MUST submit the TOTP code via POST /auth/mfa/verify to complete the login.

mfa_token str | None

Short-lived JWT (5-minute TTL by default) the caller passes back to POST /auth/mfa/verify together with the TOTP code. Populated only when mfa_required=True.

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 — None when mfa_required=True.

refresh_token str | None

Long-lived JWT — None when mfa_required=True.

mfa_required bool

When True, the caller must submit the TOTP code via POST /auth/mfa/verify to complete the login.

mfa_token str | None

Short-lived JWT the caller passes back to POST /auth/mfa/verify together with the TOTP code. Populated only when mfa_required=True.

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 — AUTH_RETURN_TOKEN_IN_RESPONSE or no EmailUtils wired — and the account was really pending. None otherwise, including when the link was emailed.

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, None in production.

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 request. The plaintext form — the SDK stores only the hash, so this value cannot be guessed from the database.

new_password str

Plaintext replacement password. The schema only rejects empty strings; the effective minimum length and complexity come from AUTH_PASSWORD_MIN_LENGTH / AUTH_PASSWORD_REQUIRE_COMPLEXITY and are applied by the service.

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 AUTH_ACTIVATION_URL_TEMPLATE.

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 AUTH_PASSWORD_RESET_URL_TEMPLATE.

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

otpauth:// URI to render as a QR code. Authenticator apps scan it to import the secret + issuer + account name in one step.

provisioning_qr str | None

provisioning_uri already drawn as a QR code, as a data:image/svg+xml;base64,... URI the app drops into an <img>. None when segno is not installed (it ships with the [mfa] extra), so a service without it keeps the same response. The image IS the secret: show it once, never log or store it.

recovery_codes list[str]

N single-use codes (AUTH_MFA_RECOVERY_CODES_COUNT, default 10). Display prominently — the user MUST save them somewhere offline.

MFAConfirmSchema

Bases: BaseSchema

Request body for POST /auth/mfa/confirm.

MFAVerifySchema

Bases: BaseSchema

Request body for POST /auth/mfa/verify.

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. None means it said nothing.

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 (default) builds a :class:MemoryWebAuthnChallengeStore, which is correct for a single worker only.

None

Raises:

Type Description
ImportError

When the [webauthn] extra is not installed.

ValueError

When AUTH_WEBAUTHN_RP_ID is empty — a relying party with no identity would accept assertions bound to nothing.

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

navigator.credentials.create() and the challenge_id

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:register_begin.

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

navigator.credentials.get() and the challenge_id

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:authenticate_begin.

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

put(challenge_id: str, state: dict[str, Any], ttl: int) -> None

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 fido2.

required
ttl int

Seconds after which the state is unusable.

required

pop async

pop(challenge_id: str) -> dict[str, Any] | None

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 None when it is

dict[str, Any] | None

unknown, already used, or expired.

MemoryWebAuthnChallengeStore

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

put(challenge_id: str, state: dict[str, Any], ttl: int) -> None

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 fido2.

required
ttl int

Seconds after which the state is unusable.

required

pop async

pop(challenge_id: str) -> dict[str, Any] | None

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 None.

RedisWebAuthnChallengeStore

RedisWebAuthnChallengeStore(redis: RedisLike, *, namespace: str = 'webauthn')

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. redis.asyncio.Redis).

required
namespace str

Prefix for every Redis key.

'webauthn'

put async

put(challenge_id: str, state: dict[str, Any], ttl: int) -> None

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 fido2.

required
ttl int

Seconds after which the state is unusable.

required

pop async

pop(challenge_id: str) -> dict[str, Any] | None

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 None.

CHALLENGE_ID_BYTES module-attribute

CHALLENGE_ID_BYTES: int = 16

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 /complete call; it is single-use, so a captured response cannot be replayed.

options dict[str, Any]

The publicKey payload to hand straight to navigator.credentials. Passed through verbatim — the shape is the browser's contract, not the SDK's, so the SDK does not reshape it.

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 begin call.

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 begin call.

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

AUTH_DEFAULT_DISPLAY_NAME: dict[str, str] = {'pt-BR': 'Você', 'en-US': 'You'}

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

DEFAULT_AUTH_LOCALE: str = 'pt-BR'

Locale used when no value is configured and nothing is negotiated.

default_display_name

default_display_name(locale: str) -> str

Return the placeholder display name for locale.

Parameters:

Name Type Description Default
locale str

A canonical supported locale. Unknown locales fall back to :data:DEFAULT_AUTH_LOCALE.

required

Returns:

Name Type Description
str str

The localized placeholder.

format_expires_at

format_expires_at(value: datetime, locale: str) -> str

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 en-US pattern.

required

Returns:

Name Type Description
str str

e.g. "21/06/2026 23:25 (UTC)" (pt-BR) or

str

"2026-06-21 23:25 (UTC)" (en-US).

LOCALE_QUERY_PARAM module-attribute

LOCALE_QUERY_PARAM: str = 'lang'

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 Accept-Language header value (e.g. "pt-BR,pt;q=0.9,en;q=0.8").

required
default str

Canonical locale used when negotiation fails. Should already be normalized (e.g. the configured AUTH_DEFAULT_LOCALE).

DEFAULT_AUTH_LOCALE

Returns:

Name Type Description
str str

One of :data:SUPPORTED_LOCALES.

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). None or empty yields default.

required
default str

Canonical locale returned when value cannot be matched. Defaults to :data:DEFAULT_AUTH_LOCALE ("pt-BR").

DEFAULT_AUTH_LOCALE

Returns:

Name Type Description
str str

One of :data:SUPPORTED_LOCALES.

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:

  1. query_locale — the ?lang= :data:LOCALE_QUERY_PARAM that :func:stamp_locale wrote 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.
  2. 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 with getattr because :class:~tempest_fastapi_sdk.BaseUserModel declares no such column; mix in :class:~tempest_fastapi_sdk.LocaleColumnMixin to have one.
  3. accept_language — the browser's own negotiation.
  4. default — usually AUTH_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 locale attribute is read.

None
query_locale str | None

Raw value of the lang query parameter, when the request carried one.

None
accept_language str | None

Raw Accept-Language header.

None
default str

Canonical locale used when nothing else matches.

DEFAULT_AUTH_LOCALE

Returns:

Name Type Description
str str

One of :data:SUPPORTED_LOCALES.

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's QueryParams.get returns the last occurrence ("pt-BR"), while a consumer reading parse_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.

LOCALE_QUERY_PARAM

Returns:

Name Type Description
str str

The URL with the locale parameter appended.

SUPPORTED_LOCALES module-attribute

SUPPORTED_LOCALES: tuple[str, ...] = ('pt-BR', 'en-US')

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

SignupHook = Callable[['AsyncSession', 'Any', 'Any'], 'Coroutine[Any, Any, None]']

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; None for an account that never logged in.

email_verified_at datetime | None

When ownership of the current email was proven; None when it never was.

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 request. Plaintext form — the SDK stores only the hash.

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 401.

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, None in production.

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 AUTH_EMAIL_CHANGE_URL_TEMPLATE.

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 AUTH_EMAIL_VERIFICATION_URL_TEMPLATE.

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 True, revoke every active refresh token the user owns (log out everywhere), not just this token's family. Defaults to False.

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 fetch_user, so a forged or expired one fails at the provider rather than here.

token_type str

Scheme the Authorization header will use when the SDK calls the provider's userinfo endpoint. Defaults to Bearer, which is what every provider the SDK ships a client for expects.

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 401.

new_password str

Plaintext replacement password. The schema only rejects empty strings; the effective minimum length and complexity come from AUTH_PASSWORD_MIN_LENGTH / AUTH_PASSWORD_REQUIRE_COMPLEXITY and are applied by the service.

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 /login MFA challenge. Ignored for an account without MFA.

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 refresh claim and not be expired.

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 None to leave the refresh cookie untouched (e.g. an access-only rotation).

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 JWT_ACCESS_TTL_SECONDS so the browser drops it when the token expires.

3600
refresh_max_age int

Refresh-cookie lifetime in seconds. Mirror JWT_REFRESH_TTL_SECONDS.

1209600
refresh_path str

Path the refresh cookie is scoped to. Defaults to "/"; the router narrows it to the refresh endpoint.

'/'
secure bool

Emit the Secure flag. Keep True in production; set False only for a plain-HTTP backend.

True
samesite SameSite

"lax" (default), "strict" or "none". Cross-site SPAs need "none" + secure=True.

'lax'
domain str | None

Cookie Domain. None binds to the serving host.

None
http_only bool

Block JavaScript access. Defaults to True and should stay so — it is the whole point of cookie mode.

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

TokenDelivery = Literal['bearer', 'cookie', 'both']

How the auth router returns the JWT pair. See the module docstring.