services#

Services for the accounts domain.

Accounts domain services.

class app.domain.accounts.services.APIKeyRecordService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[APIKey, Any]

Handles database operations for hashed personal API key records.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async to_model_on_create(data: ModelDictT[m.APIKey]) → ModelDictT[m.APIKey][source]#

Translate a digest-only APIKeyState into the API key it describes before creation.

Returns:

API key built from the state, or data unchanged when it is not an APIKeyState.

to_state(api_key: APIKey) → APIKeyState[source]#

Translate a stored API key into the digest-only state litestar-security verifies.

Returns:

State carrying the key’s digest, restrictions, expiry, and revocation window.

static to_item(api_key: APIKey) → APIKeyItem[source]#

Translate a stored API key into the secret-free APIKeyItem shown to its owner.

Returns:

The key’s name, display prefix, scopes, and lifecycle timestamps.

async rotate(key_id: str, replacement: APIKeyState, *, overlap_until: datetime | None, now: datetime) → bool[source]#

Revoke a live key and add the replacement that inherits its name, inside the caller’s transaction.

The revoked key stays usable until overlap_until, capped at its own expiry.

Returns:

True when this call rotated the key, False when it is missing or was already rotated or revoked.

async revoke(key_id: str, *, now: datetime) → bool[source]#

Stop a key from working at now, ending any rotation overlap it still has.

A key that already stopped working keeps the time it was revoked and the overlap it was given.

Returns:

True when a key matched key_id, False when none exists.

async record_usage(key_id: str, *, used_at: datetime) → bool[source]#

Stamp the last time a key authenticated a request.

Returns:

True when a key matched key_id, False when none exists.

repository_type#

alias of APIKeyRepository

class app.domain.accounts.services.AccountSecurityServices(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession] | ~sqlalchemy.orm.session.Session | ~sqlalchemy.orm.scoping.scoped_session[~sqlalchemy.orm.session.Session], *, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, auto_expunge: bool | None = None, auto_refresh: bool | None = None, auto_commit: bool | None = None, wrap_exceptions: bool | None = None)[source]#

Bases: ServiceGroup

Services behind local accounts, purpose tokens, login methods, and browser sessions.

Instantiate every declared service on the provided SQLAlchemy session.

async register_account(command: RegistrationCommand, password_hash: str, *, invitation_digest: bytes | None, verified: bool, now: datetime) → User | RegistrationStatus[source]#

Provision the account a registration asks for, redeeming its invitation first.

Parameters:
  • command – Normalized identifier and display name to register.

  • password_hash – Argon2 hash of the chosen password.

  • invitation_digest – Digest of the invitation the registration presents, when one is required.

  • verified – Whether the account starts with a confirmed email address.

  • now – Timestamp of the registration.

Returns:

DUPLICATE when the identifier is taken, INVALID_INVITATION when the invitation cannot be redeemed.

Return type:

The provisioned user, or the status rejecting the registration

Raises:

IntegrityError – If the database fails for a reason other than a violated constraint.

async redeem_purpose_token(token_id: str, digest: bytes, *, purpose: TokenPurpose, now: datetime) → User | Literal['invalid', 'used', 'expired', 'conflict'][source]#

Burn a verification or recovery token and hand back the account it was issued to.

A wrong digest counts against the token’s attempts and commits immediately, so the failed attempt survives whatever the caller does next. A recovery token is honoured only while the account’s security epoch still equals the epoch it was issued at.

Returns:

The token’s user when this call burned the token, otherwise why it was rejected.

async list_login_methods(account_id: str) → tuple[LoginMethod, ...][source]#

List every way the account can sign in: recorded methods, its password, MFA factors, and passkeys.

Returns:

The account’s login methods, recorded ones first.

async revoke_login_method(account_id: str, method_id: str, *, require_remaining: bool) → RevokeLoginMethodStatus[source]#

Remove one of the account’s login methods together with the MFA factor or passkey behind it.

The account stays locked for the transaction, so concurrent revocations cannot each remove a different method and leave the account without any. Every login method counts towards the one that must remain, second factors included, which is the contract of the security library’s login method store.

Returns:

REVOKED, NOT_FOUND when the account has no such method, or FINAL_METHOD when require_remaining is set and the method is the account’s only login method.

Remove one of the user’s linked provider accounts.

The account stays locked for the transaction, so concurrent unlinks cannot each remove a different link and leave the account without a way to sign in. Login methods are counted before the link is looked up, so on a database without row locks the loser of a race for the same link still reads NOT_FOUND instead of FINAL_METHOD. Only methods that sign the account in on their own count towards the one that must remain, because a TOTP factor cannot replace the link.

Returns:

UNLINKED, NOT_FOUND when the user has no such link, or FINAL_METHOD when require_remaining is set and the link is the only way left to sign in to the account.

class app.domain.accounts.services.AccountServices(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession] | ~sqlalchemy.orm.session.Session | ~sqlalchemy.orm.scoping.scoped_session[~sqlalchemy.orm.session.Session], *, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, auto_expunge: bool | None = None, auto_refresh: bool | None = None, auto_commit: bool | None = None, wrap_exceptions: bool | None = None)[source]#

Bases: ServiceGroup

Coordinated accounts and audit services sharing one AsyncSession.

Instantiate every declared service on the provided SQLAlchemy session.

async assign_role(role_slug: str, *, email: str, actor: User) → None[source]#

Give a user a role and record who assigned it, in one transaction.

Raises:

HTTPException – If the role or user does not exist, or the user already holds the role.

async revoke_role(role_slug: str, *, email: str, actor: User) → None[source]#

Take a role away from a user and record who revoked it, in one transaction.

Raises:

HTTPException – If the role or user does not exist, or the user does not hold the role.

class app.domain.accounts.services.LoginMethodService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[AppStore, Any]

Handles login methods recorded per account in the shared key-value store.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

static to_login_method(recorded_method: AppStore) → LoginMethod[source]#

Translate a recorded entry back into its LoginMethod.

Returns:

The login method that was recorded.

async list_for_account(account_id: str) → Sequence[m.AppStore][source]#

List the login methods recorded for one account.

Returns:

Recorded entries whose key belongs to account_id.

async find_recorded(account_id: str, method_id: str) → AppStore | None[source]#

Load the entry recorded for one of the account’s login methods.

Returns:

The recorded entry, or None when the account never recorded method_id.

async record(account_id: str, login_method: LoginMethod) → None[source]#

Insert or replace one recorded login method inside the caller’s transaction.

repository_type#

alias of AppStoreRepository

class app.domain.accounts.services.MFAFactorService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[UserMFAFactor, Any]

Handles database operations for TOTP factors and pending enrollments.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async to_model_on_create(data: ModelDictT[m.UserMFAFactor]) → ModelDictT[m.UserMFAFactor][source]#

Translate a PendingTOTPEnrollment into the unconfirmed factor stored for its account.

Returns:

The factor to persist, or data unchanged when it is not a PendingTOTPEnrollment.

to_enrollment(mfa_factor: UserMFAFactor) → PendingTOTPEnrollment | None[source]#

Translate a pending factor into the PendingTOTPEnrollment it was created from.

Returns:

The pending enrollment, or None when the factor no longer carries enrollment details.

to_totp_method(mfa_factor: UserMFAFactor) → TOTPMethod[source]#

Translate a confirmed factor into the TOTPMethod the security library verifies codes against.

Returns:

The TOTP method, reporting a counter of -1 until a code has been accepted.

static to_login_method(mfa_factor: UserMFAFactor) → LoginMethod[source]#

Describe a confirmed factor as a LoginMethod.

Returns:

Login method carrying the factor’s identifier and kind.

async find_pending(enrollment_id: str) → UserMFAFactor | None[source]#

Load the unconfirmed enrollment with this identifier.

Returns:

The pending factor, or None when it is unknown or already confirmed.

async find_active(user_id: UUID, method_id: str) → UserMFAFactor | None[source]#

Load a confirmed factor owned by user_id.

Returns:

The active factor, or None when it is unknown, pending, or owned by another account.

async list_active(user_id: UUID) → Sequence[m.UserMFAFactor][source]#

List the confirmed factors owned by user_id.

Returns:

Active factors the account can sign in with.

async confirm_enrollment(mfa_factor: m.UserMFAFactor, *, accepted_counter: int, now: datetime) → bool[source]#

Turn an unexpired pending enrollment into an active factor, updating the loaded mfa_factor to match.

Returns:

True when this call confirmed the enrollment, False when it expired or was already confirmed.

async advance_counter(method_id: str, *, accepted_counter: int, now: datetime) → bool[source]#

Advance an active factor’s counter only to a strictly greater value.

Returns:

True when the counter advanced, False when the code was already used or the factor is not active.

repository_type#

alias of UserMFAFactorRepository

class app.domain.accounts.services.MFALoginChallengeService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[MFALoginChallenge, Any]

Handles database operations for single-use MFA login challenges.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async to_model_on_create(data: ModelDictT[m.MFALoginChallenge]) → ModelDictT[m.MFALoginChallenge][source]#

Translate an MFALoginChallenge into the login challenge stored for its account.

Returns:

The login challenge to persist, or data unchanged when it is not an MFALoginChallenge.

async redeem(challenge_digest: bytes, *, account_id: str, security_epoch: int, now: datetime) → MFALoginChallenge | None[source]#

Burn an unconsumed login challenge and hand it back only when it was issued for this login.

The login challenge is burned whenever it is found, so a wrong account, a stale epoch, or an expired challenge cannot be presented a second time.

Returns:

The challenge when this call burned it and account, epoch, and expiry all match, otherwise None.

repository_type#

alias of MFALoginChallengeRepository

class app.domain.accounts.services.MFARecoveryCodeService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[UserMFARecoveryCode, Any]

Handles database operations for single-use MFA recovery codes.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async replace_all(user_id: UUID, codes: Sequence[RecoveryCodeDigest]) → None[source]#

Swap an account’s complete recovery code set, skipping digests issued for another account.

async burn(user_id: UUID, digest: bytes, *, now: datetime) → bool[source]#

Mark one unused recovery code as consumed.

Returns:

True when this call consumed the code, False when it is unknown or already consumed.

repository_type#

alias of UserMFARecoveryCodeRepository

class app.domain.accounts.services.MFAServices(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession] | ~sqlalchemy.orm.session.Session | ~sqlalchemy.orm.scoping.scoped_session[~sqlalchemy.orm.session.Session], *, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, auto_expunge: bool | None = None, auto_refresh: bool | None = None, auto_commit: bool | None = None, wrap_exceptions: bool | None = None)[source]#

Bases: ServiceGroup

Services behind TOTP factors, recovery codes, login challenges, and step-up grants.

Instantiate every declared service on the provided SQLAlchemy session.

async activate_totp(user_id: UUID, enrollment_id: str, *, accepted_counter: int, login_method: LoginMethod, codes: Sequence[RecoveryCodeDigest] | None, now: datetime) → UserMFAFactor | None[source]#

Confirm the user’s pending TOTP enrollment and record it as a login method.

Parameters:
  • user_id – Account confirming the enrollment.

  • enrollment_id – Pending enrollment being confirmed.

  • accepted_counter – TOTP counter of the code that proved possession of the secret.

  • login_method – Login method to record for the activated factor.

  • codes – Recovery codes replacing the account’s current set, or None to leave them untouched.

  • now – Timestamp of the confirmation.

Returns:

The activated factor, or None when the enrollment is unknown, owned by another account, expired, or already confirmed.

async replace_recovery_codes(user_id: UUID, codes: Sequence[RecoveryCodeDigest]) → None[source]#

Swap the account’s recovery codes while holding its row lock.

The lock makes concurrent replacements run one at a time, so the account always ends up with exactly one caller’s complete set.

class app.domain.accounts.services.OAuthAccountService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[UserOAuthAccount, Any]

Handles database operations for linked provider accounts and their protected tokens.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

static to_oauth_account_id(provider_account_id: str) → UUID | None[source]#

Translate the security library’s provider account identifier into the linked account’s primary key.

This is the inverse of the provider_account_id=str(oauth_account.id) that to_linked_account hands the library.

Returns:

The linked account identifier, or None when provider_account_id does not name one.

static to_account_email(identity: ProviderIdentity) → str[source]#

Choose the email address an account provisioned for a provider identity is stored under.

An identity without an email address gets a placeholder at oauth.local. The placeholder spells the subject as the hexadecimal of its UTF-8 bytes, so subjects that differ only by letter case stay distinct once the address is normalized.

Returns:

The identity’s email address, or its placeholder.

static to_linked_account(oauth_account: UserOAuthAccount) → LinkedProviderAccount[source]#

Translate a linked account into the LinkedProviderAccount the security library works with.

Returns:

The provider link with its current grant.

static to_stored_tokens(oauth_account: m.UserOAuthAccount, tokens: ProviderTokenSet) → StoredProviderTokens[source]#

Pair decrypted tokens with the version reference a later compare-and-swap must present.

Returns:

The tokens and their versioned reference.

async find_by_identity(identity: ProviderIdentity) → m.UserOAuthAccount | None[source]#

Load the linked account for a provider identity, whoever owns it.

Returns:

The linked account, or None when the identity has never been linked.

async find_owned(oauth_account_id: UUID, *, user_id: UUID, provider: str) → UserOAuthAccount | None[source]#

Load one of a user’s linked accounts for the named provider.

Returns:

The linked account, or None when it is unknown, owned by another user, or from another provider.

async list_expiring(*, before: datetime) → Sequence[m.UserOAuthAccount][source]#

List linked accounts whose retained tokens expire at or before before.

Returns:

Linked accounts holding tokens that are due for a refresh.

Link a provider identity to a user, renewing the grant when the user already holds that link.

Parameters:
  • user_id – Account the identity is linked to.

  • identity – Provider identity being linked.

  • grant – Scopes and expiry the provider granted.

  • protected_tokens – Encrypted tokens to retain, or None to retain none.

  • now – Timestamp of the provider exchange.

Returns:

The linked account.

Raises:

AccountLinkError – If the identity belongs to another user, or the user already linked a different identity of the same provider.

Store a new link between a provider identity and a user inside the caller’s transaction.

Parameters:
  • user_id – Owner of the new link.

  • identity – Provider identity being linked.

  • email – Email address recorded for the linked identity.

  • grant – Scopes and expiry the provider granted.

  • protected_tokens – Encrypted tokens to retain, or None to retain none.

  • now – Timestamp of the provider exchange.

Returns:

The flushed linked account.

Raises:
  • AccountLinkError – If the identity is already linked, the user already linked the provider, or the user does not exist.

  • IntegrityError – If the database fails for a reason other than a violated constraint.

async replace_grant(oauth_account: m.UserOAuthAccount, *, grant: ProviderGrant, protected_tokens: ProtectedOAuthSecret | None, now: datetime, issuer: str | None = None) → None[source]#

Overwrite a linked account’s grant and retained tokens after a completed provider exchange.

The token version advances with every replacement, so a writer still holding the previous version fails its next compare-and-swap instead of overwriting these tokens.

Parameters:
  • oauth_account – Linked account receiving the new grant.

  • grant – Scopes and expiry the provider granted.

  • protected_tokens – Encrypted tokens to retain, or None to drop any retained tokens.

  • now – Timestamp of the provider exchange.

  • issuer – Issuer to record, or None to keep the stored issuer.

Raises:

AccountLinkError – If the linked account no longer exists.

async replace_tokens(oauth_account: m.UserOAuthAccount, *, expected_version: int, tokens: ProviderTokenSet, protected_tokens: ProtectedOAuthSecret) → bool[source]#

Store refreshed tokens only while the stored token version still equals expected_version.

Returns:

True when the tokens were replaced, False when another writer advanced the version first.

async discard_tokens(oauth_account_id: UUID, *, expected_version: int | None) → bool[source]#

Clear retained tokens and advance the token version, optionally only at expected_version.

Returns:

True when the tokens were cleared, False when the account is missing or its version moved.

Remove a linked account together with its grant and retained tokens.

Returns:

True when this call removed the link, False when it was already gone.

repository_type#

alias of UserOAuthAccountRepository

class app.domain.accounts.services.OAuthServices(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession] | ~sqlalchemy.orm.session.Session | ~sqlalchemy.orm.scoping.scoped_session[~sqlalchemy.orm.session.Session], *, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, auto_expunge: bool | None = None, auto_refresh: bool | None = None, auto_commit: bool | None = None, wrap_exceptions: bool | None = None)[source]#

Bases: ServiceGroup

Services behind signing in with a linked provider account.

Instantiate every declared service on the provided SQLAlchemy session.

async login(identity: ProviderIdentity, *, grant: ProviderGrant, protected_tokens: ProtectedOAuthSecret | None, provision_unknown: bool, now: datetime) → OAuthLoginOutcome[source]#

Sign in the account linked to a provider identity, provisioning one first when allowed.

Parameters:
  • identity – Provider identity that completed the exchange.

  • grant – Scopes and expiry the provider granted.

  • protected_tokens – Encrypted tokens to retain, or None to retain none.

  • provision_unknown – Whether an identity nobody has linked yet gets a new account.

  • now – Timestamp of the provider exchange.

Returns:

The linked account and whether this call provisioned its user.

Raises:

AccountLinkError – If the identity is unknown and may not be provisioned, or provisioning collides with an existing account.

class app.domain.accounts.services.OAuthTransactionService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[OAuthTransaction, Any]

Handles database operations for single-use OAuth authorization transactions.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

static to_transaction(oauth_transaction: m.OAuthTransaction, *, pkce_verifier: SecretStr, nonce: SecretStr | None) → OAuthTransaction[source]#

Translate a stored transaction into the OAuthTransaction it was recorded from.

Returns:

The transaction as the provider callback expects it, carrying its decrypted secrets.

async record(transaction: OAuthTransaction, *, protected_secrets: ProtectedOAuthSecret) → m.OAuthTransaction[source]#

Store a pending transaction with its PKCE verifier and nonce already encrypted.

Returns:

The flushed transaction.

async redeem(state_digest: bytes, *, binding_digest: bytes, provider: str, now: datetime) → m.OAuthTransaction | None[source]#

Burn an unconsumed transaction only when it was issued for this provider callback.

A callback with a wrong provider or binding, or one arriving after expiry, leaves the transaction unconsumed.

Returns:

The transaction when provider, binding, and expiry all match and this call burned it, otherwise None.

repository_type#

alias of OAuthTransactionRepository

class app.domain.accounts.services.PasskeyChallengeService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[PasskeyChallenge, Any]

Handles database operations for single-use WebAuthn ceremony challenges.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async to_model_on_create(data: ModelDictT[m.PasskeyChallenge]) → ModelDictT[m.PasskeyChallenge][source]#

Translate a WebAuthnChallenge into the stored ceremony challenge.

Returns:

The challenge to persist, or data unchanged when it is not a WebAuthnChallenge.

async redeem(challenge_digest: bytes, *, binding_digest: bytes, purpose: str, now: datetime) → WebAuthnChallenge | None[source]#

Burn an unconsumed challenge and hand it back only when it was issued for this ceremony.

The challenge is burned whenever it is found, so a wrong binding, purpose, or an expired challenge cannot be presented a second time.

Returns:

The challenge when this call burned it and binding, purpose, and expiry all match, otherwise None.

repository_type#

alias of PasskeyChallengeRepository

class app.domain.accounts.services.PasskeyService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[UserPasskey, Any]

Handles database operations for WebAuthn passkey credentials.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async to_model_on_create(data: ModelDictT[m.UserPasskey]) → ModelDictT[m.UserPasskey][source]#

Translate a PasskeyCredential into the passkey stored for its account.

Returns:

The passkey to persist, or data unchanged when it is not a PasskeyCredential.

static to_credential(passkey: UserPasskey) → PasskeyCredential[source]#

Translate a stored passkey into the PasskeyCredential the security library verifies against.

Returns:

Credential carrying the stored public key, counters, and flags.

static to_login_method(passkey: UserPasskey) → LoginMethod[source]#

Describe a passkey as a LoginMethod identified by its encoded credential identifier.

Returns:

Passkey login method carrying the credential’s display name.

async find_for_login_method(user_id: UUID, method_id: str) → UserPasskey | None[source]#

Load the passkey a login method identifier names, when user_id owns it.

Returns:

The passkey, or None when method_id does not name one of the user’s passkeys.

async record_assertion(passkey: m.UserPasskey, *, expected_version: int, sign_count: int, backup_eligible: bool, backup_state: bool, clone_risk: bool, now: datetime) → bool[source]#

Advance the signature counter only while the stored version still equals expected_version.

Returns:

True when the passkey was updated, False when another assertion won the race.

repository_type#

alias of UserPasskeyRepository

class app.domain.accounts.services.PasskeyServices(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession] | ~sqlalchemy.orm.session.Session | ~sqlalchemy.orm.scoping.scoped_session[~sqlalchemy.orm.session.Session], *, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, auto_expunge: bool | None = None, auto_refresh: bool | None = None, auto_commit: bool | None = None, wrap_exceptions: bool | None = None)[source]#

Bases: ServiceGroup

Services behind registering a WebAuthn credential as a login method.

Instantiate every declared service on the provided SQLAlchemy session.

class app.domain.accounts.services.PurposeTokenService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[PurposeToken, Any]

Handles database operations for verification, recovery, and invitation tokens.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async issue(token_issue: TokenIssue, *, user_id: UUID | None) → m.PurposeToken[source]#

Store the digest of a newly issued token inside the caller’s transaction.

Parameters:
  • token_issue – Token digest, purpose, account binding, and expiry to store.

  • user_id – Account the token belongs to, or None when it is not bound to an existing account.

Returns:

The stored purpose token.

Raises:

ValueError – If a purpose token with the same identifier already exists.

async redeem_invitation(digest: bytes, *, now: datetime) → bool[source]#

Burn the unconsumed, unrevoked, unexpired invitation stored under digest.

Returns:

True when this call burned the invitation, False when no usable invitation matched.

async burn(purpose_token: PurposeToken, *, now: datetime) → bool[source]#

Mark an unconsumed token as consumed.

Returns:

True when this call consumed the token, False when it was already consumed.

async record_failed_attempt(purpose_token: PurposeToken, *, now: datetime) → None[source]#

Count one failed proof in a single statement, consuming the token on its last allowed attempt.

repository_type#

alias of PurposeTokenRepository

class app.domain.accounts.services.RoleService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[Role, Any]

Handles database operations for roles with automatic unique slug generation.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

class Repo(*, statement: ~sqlalchemy.sql.selectable.Select | None = None, session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, wrap_exceptions: bool = True, uniquify: bool | None = None, count_with_window_function: bool | None = None, cache_manager: CacheManager | None = None, bind_group: str | None = None, **kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncSlugRepository[Role]

Role SQLAlchemy slug repository.

Repository for SQLAlchemy models.

Parameters:
  • statement – To facilitate customization of the underlying select query.

  • session – Session managing the unit-of-work for the operation.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap SQLAlchemy exceptions in a RepositoryError. When set to False, the original exception will be raised.

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • cache_manager – Optional cache manager for repository-level caching. If not provided, retrieved from session.info.

  • bind_group – Optional default routing group to use for all operations. Can be overridden per-method.

  • **kwargs – Additional arguments.

model_type#

alias of Role

repository_type#

alias of Repo

match_fields: ClassVar[List[str] | str | None] = ['name']#

List of dialects that prefer to use field.id = ANY(:1) instead of field.id IN (...).

async to_model_on_create(data: ModelDictT[m.Role]) → ModelDictT[m.Role][source]#

Populate a unique slug from the role name when creating a new role.

Returns:

Prepared role payload with a unique slug populated when omitted.

async ensure_default_access_role() → Role[source]#

Load the default access role, creating it inside the caller’s transaction when it is missing.

Sign-ups racing on a database without the role all try to create it. The insert runs in a savepoint, so a caller that loses to the role’s unique constraint keeps its transaction and uses the winner’s role.

Returns:

The stored default access role.

Raises:

IntegrityError – If the database fails for a reason other than a violated constraint.

class app.domain.accounts.services.StepUpGrantService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[StepUpGrant, Any]

Handles database operations for single-use step-up grants.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async to_model_on_create(data: ModelDictT[m.StepUpGrant]) → ModelDictT[m.StepUpGrant][source]#

Translate a StepUpGrantState into the stored step-up grant.

Returns:

The step-up grant to persist, or data unchanged when it is not a StepUpGrantState.

async redeem(grant_digest: bytes, *, principal_id: str, security_epoch: int, purpose: str, transport_digest: bytes, now: datetime) → StepUpGrantState | None[source]#

Burn an unspent step-up grant only when it was granted for this request.

A request with a wrong principal, epoch, purpose, or transport, or one arriving after expiry, leaves the step-up grant unspent.

Returns:

The grant when every binding matches and this call burned it, otherwise None.

repository_type#

alias of StepUpGrantRepository

class app.domain.accounts.services.UserRoleService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[UserRole, Any]

Handles database operations for user role assignments using an inferred repository.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

repository_type#

alias of UserRoleRepository

class app.domain.accounts.services.UserService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[User, Any]

Handles database operations for user accounts using Argon2 password hashing.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

match_fields: ClassVar[List[str] | str | None] = ['email']#

List of dialects that prefer to use field.id = ANY(:1) instead of field.id IN (...).

async to_model_on_create(data: ModelDictT[m.User]) → ModelDictT[m.User][source]#

Normalize the email address, hash a plaintext password, and attach an initial role before creation.

Returns:

Normalized user payload or model instance ready for persistence.

async to_model_on_update(data: ModelDictT[m.User]) → ModelDictT[m.User][source]#

Normalize the email address when updating a user record.

An update never replaces a password: set_password does, so the security epoch advances and the user’s sessions end with it.

Returns:

Normalized user payload or model instance ready for update.

async to_model_on_upsert(data: ModelDictT[m.User]) → ModelDictT[m.User][source]#

Normalize the email address and hash a plaintext password when upserting a user record.

Returns:

Normalized user payload or model instance ready for upsert.

static to_user_id(account_id: str | None) → UUID | None[source]#

Translate the security library’s account identifier into the user’s primary key.

This is the inverse of the account_id=str(user.id) that to_account_state hands the library.

Returns:

The user identifier, or None when account_id is blank or does not name a user.

static to_account_state(user: User) → LocalAccountState[User][source]#

Translate a user loaded by find_for_authorization into the security library’s account projection.

Returns:

Account state carrying the identifier, activity flags, security epoch, and the user itself.

static to_password_state(user: User) → PasswordCredentialState | None[source]#

Translate a user loaded by find_with_password into its password credential snapshot.

Returns:

The password hash paired with the account state it was read with, or None without a password.

static to_login_method(user: User) → LoginMethod[source]#

Describe the user’s password as a LoginMethod.

Returns:

Password login method dated from the account’s creation.

async find_for_authorization(criterion: ColumnElement[bool]) → m.User | None[source]#

Load the user matching criterion with the roles, teams, and MFA factors authorization reads.

Returns:

The user ready for to_account_state, or None when no user matches.

async find_with_password(user_id: UUID) → User | None[source]#

Load a user together with its deferred password hash.

Returns:

The user, or None when the account does not exist.

async find_for_update(user_id: UUID) → User | None[source]#

Load a user with its password hash and keep its row locked until the transaction ends.

Changes that depend on the account’s complete set of login methods or recovery codes take this lock first, so concurrent changes to one account run one at a time.

Returns:

The locked user, or None when the account does not exist.

async find_by_email(email: str) → User | None[source]#

Load the account an email address identifies, however the address is capitalized or padded.

Returns:

The user, or None when no account has that address.

async get_by_email(email: str) → User[source]#

Load the account an email address identifies, however the address is capitalized or padded.

A missing account surfaces as the NotFoundError raised by get_one.

Returns:

The user holding that address.

async get_security_epoch(user_id: UUID) → int | None[source]#

Read an account’s security epoch without loading the account.

Returns:

The current epoch, or None when the account does not exist.

async provision(*, email: str, name: str | None, verified: bool, now: datetime, hashed_password: str | None = None, is_superuser: bool = False) → User[source]#

Create an active account holding the default access role inside the caller’s transaction.

The default access role is created first when the database does not have it yet, so no account is ever provisioned without it.

Parameters:
  • email – Email address identifying the account, stored normalized.

  • name – Display name, when known.

  • verified – Whether the email address is already confirmed.

  • now – Timestamp recorded for verification and the role assignment.

  • hashed_password – Argon2 hash for password accounts; None for accounts that sign in another way.

  • is_superuser – Whether the account bypasses role checks.

Returns:

The flushed user record.

async reload_for_authorization(user: User) → User[source]#

Refresh a user changed in this transaction together with everything authorization reads.

Returns:

The same user, reflecting the roles, teams, and MFA factors now stored for it.

async swap_password_hash(user_id: UUID, *, expected_hash: str, password_hash: str) → bool[source]#

Replace the password hash only while the stored hash still equals expected_hash.

Returns:

True when the hash was replaced, False when it had already changed.

async replace_password_hash_and_bump_epoch(user_id: UUID, password_hash: str, *, expected_epoch: int, reset_at: datetime | None = None) → bool[source]#

Replace the password hash and advance the security epoch only while it equals expected_epoch.

Parameters:
  • user_id – Account whose password is replaced.

  • password_hash – Encoded replacement hash.

  • expected_epoch – Epoch the caller read; any other stored epoch leaves the account untouched.

  • reset_at – Timestamp to record when the replacement completes a password reset.

Returns:

True when the password and epoch changed, False when the epoch had already moved on.

async static hash_password(password: str, *, email: str | None) → str[source]#

Hash a plaintext password that satisfies the application’s password policy.

Every password the application itself sets passes through here, so PASSWORD_POLICY is the only rule a new password meets.

Parameters:
  • password – Plaintext password chosen for the account.

  • email – Email address of the account, which the password must not repeat, when it is known.

Returns:

Encoded Argon2 hash.

Raises:

ClientException – If the policy rejects the password. The detail names every violated rule.

async set_password(user: User, password: str) → None[source]#

Give a user a new password inside the caller’s transaction, signing the account out everywhere.

Advancing the security epoch and revoking every session ends whatever the previous password had opened. user reflects its new credentials when this returns.

Raises:

ClientException – If hash_password rejects the password, or the account’s credentials changed after user was loaded.

async update_password(user: User, *, current_password: str, new_password: str) → None[source]#

Replace the user’s password after verifying the current one, signing the account out everywhere.

A rejected new password, or credentials that changed while this request was verifying them, surface as the ClientException raised by set_password.

Parameters:
  • user – Account changing its password.

  • current_password – Plaintext password the account holds now.

  • new_password – Plaintext replacement password.

Raises:

PermissionDeniedException – If current password verification fails or the account is inactive.

async upload_avatar(user: User, data: bytes) → User[source]#

Store a new avatar image for user and commit, replacing any previous one.

The image is written to object storage under a server-generated key before the row is committed; the previous image is deleted once the commit succeeds, and the new one is deleted if it fails.

Parameters:
  • user – Account loaded by this service.

  • data – Raw image bytes.

Returns:

The updated user.

Raises:

ServiceUnavailableException – If no upload storage backend is registered.

async remove_avatar(user: User) → User[source]#

Clear user’s avatar and commit; the stored image is deleted once the commit succeeds.

Returns:

The updated user.

repository_type#

alias of UserRepository

class app.domain.accounts.services.UserSessionService(session: ~sqlalchemy.ext.asyncio.session.AsyncSession | ~sqlalchemy.ext.asyncio.scoping.async_scoped_session[~sqlalchemy.ext.asyncio.session.AsyncSession], *, statement: ~sqlalchemy.sql.selectable.Select | None = None, model_type: type[~advanced_alchemy.repository.typing.ModelT] | None = None, repository_type: type[~advanced_alchemy.repository.typing.SQLAlchemyAsyncRepositoryT] | None = None, auto_expunge: bool = False, auto_refresh: bool = True, auto_commit: bool = False, order_by: ~typing.List[tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any]] | tuple[str | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any], bool] | ~sqlalchemy.sql.elements.UnaryExpression[~typing.Any] | None = None, error_messages: ~advanced_alchemy.exceptions.ErrorMessages | type[~advanced_alchemy.utils.dataclass.Empty] | None = <class 'advanced_alchemy.utils.dataclass.Empty'>, wrap_exceptions: bool = True, load: ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~collections.abc.Sequence[~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any]]] | ~sqlalchemy.orm.interfaces.LoaderOption | ~typing.Literal['*'] | ~sqlalchemy.orm.attributes.InstrumentedAttribute[~typing.Any] | ~sqlalchemy.orm.relationships.RelationshipProperty[~typing.Any] | ~sqlalchemy.orm.interfaces.MapperProperty[~typing.Any] | ~sqlalchemy.sql.base.ExecutableOption | ~collections.abc.Sequence[~sqlalchemy.sql.base.ExecutableOption] | None = None, execution_options: dict[str, ~typing.Any] | None = None, uniquify: bool | None = None, count_with_window_function: bool | None = None, **repo_kwargs: ~typing.Any)[source]#

Bases: SQLAlchemyAsyncRepositoryService[UserSession, Any]

Handles database operations for server-side browser sessions.

Configure the service object.

Parameters:
  • session – Session managing the unit-of-work for the operation.

  • statement – To facilitate customization of the underlying select query.

  • model_type – Optional SQLAlchemy model type when instantiating directly without subclassing.

  • repository_type – Optional repository class override when instantiating directly.

  • auto_expunge – Remove object from session before returning.

  • auto_refresh – Refresh object from session before returning.

  • auto_commit – Commit objects before returning.

  • order_by – Set default order options for queries.

  • error_messages – A set of custom error messages to use for operations

  • wrap_exceptions – Wrap exceptions in a RepositoryError

  • load – Set default relationships to be loaded

  • execution_options – Set default execution options

  • uniquify – Optionally apply the unique() method to results before returning.

  • count_with_window_function – When false, list and count will use two queries instead of an analytical window function. Defaults to True in 1.x (planned to change to False in v2.0).

  • **repo_kwargs – passed as keyword args to repo instantiation.

async to_model_on_create(data: ModelDictT[m.UserSession]) → ModelDictT[m.UserSession][source]#

Translate a CreateSessionCommand into the browser session stored for its account.

Returns:

The browser session to persist, or data unchanged when it is not a CreateSessionCommand.

static to_auth_session(user_session: UserSession) → UserAuthSession[source]#

Translate a stored browser session into the UserAuthSession the security library works with.

Returns:

Session record carrying the binding, owner, epoch, and lifetime.

async find_active(session_id: str, *, now: datetime) → UserSession | None[source]#

Load a browser session that is neither revoked nor expired at now.

Returns:

The active browser session, or None when it is unknown, revoked, or expired.

async find_active_with_user(session_id: str, user_id: UUID, *, now: datetime) → UserSession | None[source]#

Load an active browser session owned by user_id together with its user in one query.

The user arrives with the relationships UserService.to_account_state exposes.

Returns:

The active browser session, or None when it is unknown, revoked, expired, or owned by another user.

async list_active_for_user(user_id: UUID, *, now: datetime) → list[UserSession][source]#

List the user’s browser sessions that are neither revoked nor expired at now.

Returns:

Active browser sessions owned by user_id.

async start(command: CreateSessionCommand) → UserSession[source]#

Store a newly authenticated browser session inside the caller’s transaction.

Returns:

The stored browser session.

Raises:
  • ValueError – If command.account_id is not a UUID or the session identifier is already taken.

  • IntegrityError – If the database fails for a reason other than a violated constraint.

async mark_seen(user_session: UserSession, *, now: datetime) → bool[source]#

Advance last_seen_at only while the browser session is still unrevoked.

Returns:

True when the browser session was updated, False when it was revoked in the meantime.

async revoke(session_id: str, *, now: datetime) → bool[source]#

Revoke one browser session that is not already revoked.

Returns:

True when this call revoked the browser session, False when it was unknown or already revoked.

async revoke_for_user(user_id: UUID, session_id: str, *, now: datetime) → bool[source]#

Revoke one browser session only when user_id owns it.

Returns:

True when this call revoked the browser session, False when it was unknown, already revoked, or owned by another user.

async revoke_all_for_user(user_id: UUID, *, now: datetime, keep_session_id: str | None = None) → int[source]#

Revoke every unrevoked browser session the user owns, optionally keeping one.

Returns:

Number of browser sessions revoked.

repository_type#

alias of UserSessionRepository

app.domain.accounts.services.detect_image_type(data: bytes) → str | None[source]#

Identify a JPEG, PNG, GIF, or WebP image from its leading magic bytes.

The client’s filename and Content-Type are never consulted, so a renamed file or an SVG is rejected.

Returns:

The image’s content type, or None when the bytes are not one of the accepted formats.

app.domain.accounts.services.is_constraint_violation(error: IntegrityError) → bool[source]#

Tell whether an Advanced Alchemy IntegrityError reports a row the database refused to store.

Advanced Alchemy raises IntegrityError for every statement that fails, including a lost connection, a lock timeout, and a missing table. Only a violated constraint means the row conflicts with stored data, so callers answering “duplicate” or “conflict” check here first and re-raise everything else.

Returns:

True when a unique, foreign key, not-null, or check constraint rejected the statement.

app.domain.accounts.services.validate_avatar(data: bytes) → str[source]#

Check an avatar upload’s size and format.

Returns:

The content type detected from the image’s magic bytes.

Raises:

ClientException – With status 413 when the image exceeds AVATAR_MAX_BYTES, or 400 when it is empty or not a JPEG, PNG, GIF, or WebP image.