Reference
components.authentication.bootstrap ¶
blueprint ¶
get_all_blueprints ¶
Source code in components/authentication/bootstrap/blueprint.py
bootstrap ¶
authentication_bootstrap
module-attribute
¶
authentication_bootstrap = ComponentBootstrap(
name="authentication",
load_all_models=load_all_models,
get_all_blueprints=get_all_blueprints,
get_all_command_groups=get_all_command_groups,
get_all_schemas=get_all_schemas,
get_flask_admin_configuration=get_flask_admin_configuration,
subscribe_to_events=subscribe_to_events,
)
command ¶
get_all_command_groups ¶
Source code in components/authentication/bootstrap/command.py
flask_admin_configuration ¶
get_flask_admin_configuration ¶
Source code in components/authentication/bootstrap/flask_admin_configuration.py
load_all_models ¶
load_all_models ¶
Source code in components/authentication/bootstrap/load_all_models.py
components.authentication.conftest ¶
app ¶
Source code in components/authentication/conftest.py
components.authentication.internal ¶
application ¶
command_handlers ¶
change_identity_first_name ¶
Source code in components/authentication/internal/application/command_handlers.py
change_identity_language ¶
Source code in components/authentication/internal/application/command_handlers.py
change_identity_last_name ¶
Source code in components/authentication/internal/application/command_handlers.py
change_mfa_status ¶
Source code in components/authentication/internal/application/command_handlers.py
clear_identity_email ¶
Source code in components/authentication/internal/application/command_handlers.py
create_identity ¶
Source code in components/authentication/internal/application/command_handlers.py
create_or_change_keycloak_id ¶
Source code in components/authentication/internal/application/command_handlers.py
delete_identity ¶
Source code in components/authentication/internal/application/command_handlers.py
delete_identity_credentials ¶
Source code in components/authentication/internal/application/command_handlers.py
log_out_identity_from_all_sessions ¶
Source code in components/authentication/internal/application/command_handlers.py
request_change_identity_email ¶
Source code in components/authentication/internal/application/command_handlers.py
request_set_identity_credentials ¶
Source code in components/authentication/internal/application/command_handlers.py
send_password_reset_email ¶
Source code in components/authentication/internal/application/command_handlers.py
send_verification_email ¶
Source code in components/authentication/internal/application/command_handlers.py
commands ¶
ChangeIdentityCredentialsCommand
dataclass
¶
ChangeIdentityCredentialsCommand(
identity_id,
email,
is_email_verified,
prehashed_password,
mfa_required,
realm=RealmName.ALAN,
)
Bases: Command
ChangeIdentityFirstNameCommand
dataclass
¶
ChangeIdentityLanguageCommand
dataclass
¶
ChangeIdentityLastNameCommand
dataclass
¶
ChangeIdentityMfaStatusCommand
dataclass
¶
ClearIdentityEmail
dataclass
¶
DeleteIdentityCommand
dataclass
¶
DeleteIdentityCredentialsCommand
dataclass
¶
IdentityCreationCommand
dataclass
¶
IdentityCreationCommand(
profile_id,
email,
first_name,
last_name,
language,
mfa_required,
realm=RealmName.ALAN,
)
Bases: Command
LogOutIdentityFromAllSessionsCommand
dataclass
¶
RequestChangeIdentityEmailCommand
dataclass
¶
SendPasswordResetEmailCommand
dataclass
¶
SendVerificationEmailCommand
dataclass
¶
event_handlers ¶
change_identity_email ¶
Source code in components/authentication/internal/application/event_handlers.py
merge_identities ¶
Source code in components/authentication/internal/application/event_handlers.py
idp_login_flow ¶
Use-cases for the web Keycloak BFF login flow (Authorization-Code + PKCE).
Orchestrates the flow on top of the infrastructure adapter (keycloak_oidc_client):
generate PKCE + state and stash it, assemble the authorize URL, then on callback
pop the state and exchange the code; plus refresh and logout. Stateless — the
Keycloak token is the session; no backend RefreshToken. Controllers call these;
they never reach into infrastructure directly.
IdpCallbackResult
dataclass
¶
IdpLoginStart
dataclass
¶
abort_idp_login ¶
Consume the started login after an IdP error callback; return where to land.
Pops (one-time) the stashed flow so it can't be reused — a terminal error
callback must consume the single-use flow exactly like a successful one,
dropping the PKCE code_verifier immediately rather than waiting on its TTL.
Returns the app path the login started from (None if unknown/expired) so the
controller can send the browser back where it came from with an error flag.
Source code in components/authentication/internal/application/idp_login_flow.py
complete_idp_callback ¶
Callback leg: consume the stashed flow state and exchange the code.
Returns None if the state is unknown/expired or the exchange fails.
Source code in components/authentication/internal/application/idp_login_flow.py
logout_idp_session ¶
Revoke the Keycloak session (if a refresh token is present) and return the end-session URL for the client to front-channel-redirect to.
post_logout_redirect_uri (if given) is where Keycloak sends the browser
after ending the session — must be registered in the realm client.
id_token_hint lets Keycloak skip its logout confirmation page.
Source code in components/authentication/internal/application/idp_login_flow.py
refresh_idp_session ¶
Refresh the Keycloak session from the BFF-held refresh token.
Source code in components/authentication/internal/application/idp_login_flow.py
start_idp_login ¶
Begin the BFF login: stash PKCE/state and return the authorize URL + state.
The lib's auth_url supports neither PKCE nor kc_idp_hint, so we assemble
the URL ourselves from the discovered authorization endpoint, using authlib's
vetted RFC-7636 helper for the PKCE challenge.
state is returned so the controller can bind it to the initiating browser
(httpOnly cookie) and reject callbacks that don't carry it — CSRF /
auth-code-injection defense.
app_redirect_path (a validated same-origin path) is carried through to the
callback so the browser lands back in the app it started from.
Source code in components/authentication/internal/application/idp_login_flow.py
message_bus ¶
MessageBus ¶
MessageBus that dispatches messages to their respective handlers.
Note: this is a glorified for loop.
The order in which handlers will be called is NOT guaranteed.
Message inheritance isn't supported at the moment and handlers needs to be explicitly attached to their exact types.
Taking a fictional example:
class CompanyUpdated(DomainEvent): ... class VatNumberUpdated(CompanyUpdated): ... class SiretNumberUpdated(CompanyUpdated): ...
event_handlers = { CompanyUpdated: [print] }
If VatNumberUpdated is triggered, print will NOT be called.
Source code in components/authentication/internal/application/message_bus.py
collect_processed ¶
command_handlers
instance-attribute
¶
event_handlers
instance-attribute
¶
handle ¶
Source code in components/authentication/internal/application/message_bus.py
subscribers ¶
update_keycloak_identity_information ¶
Update a keycloak identity first and last name when changed in the global profile.
Source code in components/authentication/internal/application/subscribers.py
update_keycloak_identity_language ¶
Update a keycloak identity preferred language when changed in the global profile.
Source code in components/authentication/internal/application/subscribers.py
token_verifier ¶
Use-case: verify a Keycloak IdP access token and resolve its identity.
Composes the domain realm policy (realm_from_issuer) with the infrastructure
JWKS decode (decode_token_for_realm) and a local audience check. Stateless:
realm is derived from the (allow-listed) iss, the signature is checked against
that realm's cached JWKS, and the audience against the realm's allowed set. No
userinfo round-trip, no backend session.
VerifiedKeycloakToken
dataclass
¶
verify_keycloak_access_token ¶
Verify a Keycloak access token locally; return its identity claims.
Realm is derived from the (allow-listed) iss claim and the signature is
checked against that realm's cached JWKS. Returns None on any failure —
unknown/missing issuer, bad signature, wrong audience, or expiry.
Source code in components/authentication/internal/application/token_verifier.py
business_logic ¶
actions ¶
lockdown_compromised_account ¶
CompromisedAccountStatus
dataclass
¶
CompromisedAccountStatus(
keycloak_id,
app_name=optional_to_empty_str_field(),
user_id=optional_to_empty_str_field(),
credentials_reset=bool_field_with_string_parsing(
default=False
),
email_sent=bool_field_with_string_parsing(
default=False
),
email_changed=bool_field_with_string_parsing(
default=False
),
old_email=optional_to_empty_str_field(),
latest_fraud_change=optional_to_empty_str_field(),
)
Bases: DataClassJsonMixin
Dataclass tracking all operations done for a compromised account.
class-attribute
instance-attribute
¶class-attribute
instance-attribute
¶class-attribute
instance-attribute
¶classmethod
¶class-attribute
instance-attribute
¶class-attribute
instance-attribute
¶Convert to spreadsheet row with proper encoding, preserving field order
Source code in components/authentication/internal/business_logic/actions/lockdown_compromised_account.py
NotificationStrategy ¶
bool_field_with_string_parsing ¶
Helper for boolean fields that parses string values like "NO", "FALSE", "0" as False. Handles case-insensitive string values: "NO"/"FALSE"/"0" → False, "YES"/"TRUE"/"1" → True.
Source code in components/authentication/internal/business_logic/actions/lockdown_compromised_account.py
build_marmot_url ¶
Source code in components/authentication/internal/business_logic/actions/lockdown_compromised_account.py
lockdown_compromised_accounts ¶
lockdown_compromised_accounts(
compromised_accounts,
notify_users,
check_changes_since_days=7,
dry_run=True,
)
Source code in components/authentication/internal/business_logic/actions/lockdown_compromised_account.py
optional_to_empty_str_field ¶
Helper for optional string fields that converts None ↔ empty string
Source code in components/authentication/internal/business_logic/actions/lockdown_compromised_account.py
reset_user_credentials ¶
reset_user_credentials ¶
Reset user credentials by removing password and revoking all sessions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keycloak_id
|
UUID
|
The Keycloak ID of the user |
required |
dry_run
|
bool
|
Whether to perform a dry run (default True) |
True
|
Returns:
| Type | Description |
|---|---|
str | None
|
User ID if successful, None if failed or dry run |
Source code in components/authentication/internal/business_logic/actions/reset_user_credentials.py
queries ¶
check_sso_domain ¶
SsoDomainCheckResult
dataclass
¶
check_sso_domain ¶
Check if the email domain is configured for enterprise SSO.
Returns the same response shape regardless of whether the domain exists to prevent email enumeration.
Source code in components/authentication/internal/business_logic/queries/check_sso_domain.py
get_user_changes ¶
get_email_changes_by_keycloak_ids ¶
Get email changes for users identified by their Keycloak IDs.
Flow: keycloak_id → authentication_identity → profile_id → Activity
Source code in components/authentication/internal/business_logic/queries/get_user_changes.py
get_fr_users_fraud_relevant_changes ¶
Source code in components/authentication/internal/business_logic/queries/get_user_changes.py
rules ¶
enterprise_sso ¶
is_login_credentials_change_allowed ¶
Check if email or password change is allowed for a given profile.
Source code in components/authentication/internal/business_logic/rules/enterprise_sso.py
commands ¶
app_group ¶
backfill_authentication_identity ¶
backfill_users_identity ¶
check_all_user_have_identity ¶
Check if all the users with a keycloak_id have an identity in the authentication_identity table
Source code in components/authentication/internal/commands/backfill_authentication_identity.py
find_identity_conlicts ¶
Find any keycloak_id conflicts between users in different components.
Source code in components/authentication/internal/commands/backfill_authentication_identity.py
compromised_accounts ¶
lockdown_compromised_user_accounts ¶
lockdown_compromised_user_accounts(
gsheet_key,
keycloak_ids,
gsheet_tab,
notify_users,
check_changes_since_days=7,
dry_run=True,
)
Lockdown compromised user accounts by removing password and revoking all sessions. How To: https://www.notion.so/alaninsurance/Compromised-member-accounts-18f1426e8be780e783a3e250de980c42 ⧉
This command can work in two modes: 1. --gsheet-key: Read keycloak_ids from a spreadsheet and update it with results 2. --keycloak-ids: Process a list of IDs directly without spreadsheet persistence
Additionally, we check for any email change (all countries) or relevant fraud change (FR only)
Source code in components/authentication/internal/commands/compromised_accounts.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
notify_compromised_accounts ¶
Source code in components/authentication/internal/commands/compromised_accounts.py
reset_users_credentials ¶
Source code in components/authentication/internal/commands/compromised_accounts.py
fix_email_consistency ¶
fix_be_ca_email_inconsistency ¶
Source code in components/authentication/internal/commands/fix_email_consistency.py
fix_be_es_email_inconsistency ¶
Source code in components/authentication/internal/commands/fix_email_consistency.py
fix_be_fr_email_inconsistency ¶
Source code in components/authentication/internal/commands/fix_email_consistency.py
fix_ca_es_email_inconsistency ¶
Source code in components/authentication/internal/commands/fix_email_consistency.py
fix_ca_fr_email_inconsistency ¶
Source code in components/authentication/internal/commands/fix_email_consistency.py
fix_es_fr_email_inconsistency ¶
Source code in components/authentication/internal/commands/fix_email_consistency.py
fix_inconsistencies ¶
fix_identity_inconsistencies ¶
fix_identity_inconsistencies(
profile_id,
dry_run=False,
first_name=None,
last_name=None,
language=None,
)
Fix inconsistent keycloak identity for a given profile ID if possible. We only consider inconsistencies on the first name, last name, and language. If one of those field is inconsistent, the command will: - if the field is given as argument of the command replace this field in the profile table and keycloak by the provided value - if the field is not given as argument of the command, it will try to fix it automatically
Two names can be automatically fixed if they are the same once all capitalization, accents are removed and the string has been stripped.
Source code in components/authentication/internal/commands/fix_inconsistencies.py
fix_many_identities_inconsistencies ¶
Fix inconsistent keycloak identity for a given profile ID if possible. We only consider inconsistencies on the first name, last name, and language. If one of those field is inconsistent, the command will: - if the field is given as argument of the command replace this field in the profile table and keycloak by the provided value - if the field is not given as argument of the command, it will try to fix it automatically
Two names can be automatically fixed if they are the same once all capitalization, accents are removed and the string has been stripped.
Source code in components/authentication/internal/commands/fix_inconsistencies.py
controllers ¶
api ¶
create_api ¶
Source code in components/authentication/internal/controllers/api.py
domain ¶
authorization_flow ¶
The in-flight Authorization-Code+PKCE login state — a domain value object.
Generated when a BFF login starts and consumed (one-time) at the callback to exchange the code. Pure value object: frozen, value-equality, no I/O. The authorization-state repository (infrastructure) round-trips this between the two legs of the flow.
AuthorizationFlowState
dataclass
¶
events ¶
ChangeIdentityEmailApprovedEvent
dataclass
¶
Bases: DomainEvent
IdentityCreatedEvent
dataclass
¶
IdentityCreatedEvent(
identity_id,
profile_id,
email,
first_name,
last_name,
language,
is_email_verified,
)
Bases: DomainEvent
IdentityEmailChangedEvent
dataclass
¶
Bases: DomainEvent
IdentityEmailCleared
dataclass
¶
Bases: DomainEvent
IdentityFirstNameChanged
dataclass
¶
Bases: DomainEvent
IdentityLanguageChanged
dataclass
¶
Bases: DomainEvent
IdentityLastNameChanged
dataclass
¶
Bases: DomainEvent
IdentityMergedEvent
dataclass
¶
Bases: DomainEvent
MergeIdentityEvent
dataclass
¶
Bases: DomainEvent
keycloak_tokens ¶
The IdP session tokens — a domain value object.
In the stateless doctor-auth model the Keycloak token is the session (no
backend RefreshToken), so the token triple is a first-class domain concept.
Pure value object: frozen, value-equality, no I/O.
KeycloakTokens
dataclass
¶
realm ¶
Keycloak realm names + the realm-level authorization policy for IdP tokens.
RealmName (a StrEnum) keeps wire-compatibility with the existing string-based
DB column (authentication_identity.realm) — RealmName.ALAN == "alan" — while
giving the type checker a fixed set of valid values across the codebase.
realm_from_issuer below is pure authorization policy (no I/O, no config
reads): which realms may authenticate and how a token's iss maps to one. The
infrastructure layer fetches keys and decodes; the application layer composes
this policy with that decode. The Keycloak host is passed in by the caller so
this module stays I/O-free.
realm_from_issuer ¶
Map a token iss claim to an allow-listed member-identity realm.
Returns None for unknown issuers, host mismatches, or non-authenticatable
realms (e.g. master, customer-sso-test) — callers must reject those.
Source code in components/authentication/internal/domain/realm.py
infrastructure ¶
authorization_state_repository ¶
Short-lived, one-time auth-flow state store (Redis-backed, FakeStrictRedis fallback).
Decoupled from Keycloak/BFF specifics: it stores an opaque JSON-serialisable
payload under a string key with a TTL and reads it once (delete-on-read; replay
protection). The caller (the /auth/idp BFF) owns the
AuthorizationFlowState shape and its (de)serialisation to/from the payload.
A single AuthorizationStateRepository serves both prod (real Redis) and
dev (FakeStrictRedis when REDIS_URL is unset) — one code path, real Redis
setex/get/delete + JSON round-trip everywhere.
The repository is built once (process-wide singleton via
get_authorization_state_repository) so the dev FakeStrictRedis instance
survives across requests. We can't lazily call get_redis_main_connection()
per request in dev because it returns a fresh, isolated FakeStrictRedis()
each call, losing the state written at /authorize by the time /callback
reads it.
AuthorizationStateRepository ¶
Redis-backed store: setex to write, get + delete to pop.
Source code in components/authentication/internal/infrastructure/authorization_state_repository.py
pop ¶
Source code in components/authentication/internal/infrastructure/authorization_state_repository.py
JsonValue
module-attribute
¶
create_authorization_state_repository ¶
Build the repository — real Redis if reachable, else dev FakeStrictRedis.
Source code in components/authentication/internal/infrastructure/authorization_state_repository.py
get_authorization_state_repository ¶
Process-wide singleton — built once so the dev FakeStrictRedis survives requests.
Source code in components/authentication/internal/infrastructure/authorization_state_repository.py
double_write_repository ¶
DoubleWriteAuthenticationRepository ¶
Bases: BaseAuthenticationRepository
Source code in components/authentication/internal/infrastructure/double_write_repository.py
authentication_repository
instance-attribute
¶
delete ¶
Source code in components/authentication/internal/infrastructure/double_write_repository.py
get_by_id ¶
get_by_keycloak_id ¶
Source code in components/authentication/internal/infrastructure/double_write_repository.py
get_by_profile_id ¶
Source code in components/authentication/internal/infrastructure/double_write_repository.py
retro_compatibility_repository
instance-attribute
¶
retro_compatibility_repository = (
RetroCompatibilityAuthenticationRepository(
session=session, app_name=app_name
)
)
save ¶
event_dispatcher ¶
AlanMessagingEventDispatcher ¶
Bases: EventDispatcher
EventDispatcher implementation using shared.messaging.
Source code in components/authentication/internal/infrastructure/event_dispatcher.py
dispatch ¶
Source code in components/authentication/internal/infrastructure/event_dispatcher.py
EventDispatcher ¶
Bases: ABC
Interface for dispatching domain events as integration events.
dispatch
abstractmethod
¶
Dispatch a domain event as an integration event.
WARNING: this method should not raise exceptions.
MAPPERS
module-attribute
¶
MAPPERS = {
IdentityCreatedEvent: identity_created_mapper,
IdentityEmailChangedEvent: email_changed_mapper,
PasswordResetEmailSent: password_reset_email_sent_mapper,
IdentityMergedEvent: identity_merged_mapper,
IdentityEmailCleared: cleared_identity_email_mapper,
}
TestEventDispatcher ¶
Bases: EventDispatcher
Event dispatcher for testing purposes. It will store all the dispatched events in a list.
Source code in components/authentication/internal/infrastructure/event_dispatcher.py
cleared_identity_email_mapper ¶
Source code in components/authentication/internal/infrastructure/event_dispatcher.py
email_changed_mapper ¶
Source code in components/authentication/internal/infrastructure/event_dispatcher.py
identity_created_mapper ¶
Source code in components/authentication/internal/infrastructure/event_dispatcher.py
identity_merged_mapper ¶
Source code in components/authentication/internal/infrastructure/event_dispatcher.py
password_reset_email_sent_mapper ¶
Source code in components/authentication/internal/infrastructure/event_dispatcher.py
flask_auth ¶
create_mfa ¶
Source code in components/authentication/internal/infrastructure/flask_auth.py
refresh_auth
module-attribute
¶
refresh_auth = CookieTokenAuth(
verify_token_callback=_verify_refresh_token,
cookie_name="refresh_token",
)
refresh_mobile_auth
module-attribute
¶
refresh_mobile_auth = HTTPTokenAuth(
verify_token_callback=_verify_refresh_token,
scheme="Refresh",
)
identity_provider ¶
AuthIdentity ¶
DevIdentity ¶
DevIdentity(
id,
email,
language,
first_name,
last_name,
email_verified=True,
mfa_enabled=False,
mfa_required=False,
)
Bases: AuthIdentity
Source code in components/authentication/internal/infrastructure/identity_provider.py
check_password ¶
clear_password ¶
delete ¶
has_password ¶
logout_all_sessions ¶
set_email ¶
set_first_and_last_names ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_first_name ¶
set_language ¶
set_last_name ¶
set_mfa_enabled ¶
set_mfa_required ¶
set_password ¶
DevIdentityProvider ¶
Bases: IdentityProvider
A stubbed identity provider for the dev environment. Cases to test: - Standard login with email: http://localhost:4001/login ⧉ - Company creation: http://localhost:4001/fr-company-discovery/share?contractCoverOption=coverChildren&ccnCode=1486&participation=50&healthProduct=green&choosePrevoyance=true&hasLegacyHealthContract=true&hasLegacyPrevoyanceContract=true ⧉ - Fixture: http://localhost:8001/admin_tools/test_data_generator/new?fixture=LSBjb21wYW55Og%3D%3D ⧉ - User auth login: http://localhost:8002/auth/login?next=%2Foauth2%2Fauthorize%3Fresponse_type%3Dcode%26client_id%3Dmind_dev%26redirect_uri%3Djourapp%3A%252F%252Fauthcallback%252Falan%26scope%3Dopenid%2520email%26state%3D9dc9c12d-0d3b-44f1-af8f-c3b8e829b1eb ⧉ - Freelancer signup: http://localhost:4001/freelancer-signup ⧉
Source code in components/authentication/internal/infrastructure/identity_provider.py
create_new_identity ¶
create_new_identity(
email,
language,
first_name,
last_name,
is_email_verified=True,
mfa_enabled=False,
mfa_required=False,
realm=RealmName.ALAN,
)
Source code in components/authentication/internal/infrastructure/identity_provider.py
exchange_token_for_user ¶
This provides a fake exchanged token for the scenario where the backend issues Keycloak tokens on behalf of the user.
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to exchange token with |
email |
str
|
Email of the user to exchange token for |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity_id_from_token ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
generate_password_reset_email ¶
Generate a password reset email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a password reset |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing password reset |
Source code in components/authentication/internal/infrastructure/identity_provider.py
generate_verification_email ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity_id ¶
healthcheck ¶
refresh_exchanged_token ¶
This provides a fake exchanged refresh tokens for the scenario where the backend issues Keycloak tokens on behalf of the user.
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to refresh token with |
refresh_token |
str
|
The refresh token to use |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing refreshed access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
IdentityProvider ¶
create_new_identity ¶
create_new_identity(
email,
language,
first_name,
last_name,
is_email_verified=True,
mfa_enabled=False,
mfa_required=False,
realm=RealmName.ALAN,
)
Source code in components/authentication/internal/infrastructure/identity_provider.py
exchange_token_for_user ¶
Exchange token for a given user using service account
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to exchange token with |
email |
str
|
Email of the user to exchange token for |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity ¶
find_identity_id_from_token ¶
generate_password_reset_email ¶
Generate a password reset email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a password reset |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing password reset |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Source code in components/authentication/internal/infrastructure/identity_provider.py
generate_verification_email ¶
Generate a verification email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a verification |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing verification |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity ¶
get_identity_id ¶
healthcheck ¶
refresh_exchanged_token ¶
Refresh an exchanged token using service account
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to refresh token with |
refresh_token |
str
|
The refresh token to use |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing refreshed access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
IdentityProviderType ¶
KeycloakIdentity ¶
Bases: AuthIdentity
Source code in components/authentication/internal/infrastructure/identity_provider.py
check_password ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
clear_password ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
client
instance-attribute
¶
client = OAuth2Session(
client_id=get("KEYCLOAK_CLIENT_ID"),
token_endpoint=f"{keycloak_host}/realms/{keycloak_realm}/protocol/openid-connect/token",
)
delete ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
has_password ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
logout_all_sessions ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_email ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_first_and_last_names ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_first_name ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_language ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_last_name ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_mfa_enabled ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_mfa_required ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_password ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
update_pending_deletion ¶
KeycloakIdentityProvider ¶
Bases: IdentityProvider
Source code in components/authentication/internal/infrastructure/identity_provider.py
create_new_identity ¶
create_new_identity(
email,
language,
first_name,
last_name,
is_email_verified=True,
mfa_enabled=False,
mfa_required=False,
realm=RealmName.ALAN,
)
Source code in components/authentication/internal/infrastructure/identity_provider.py
exchange_token_for_user ¶
Exchange token for a user using Keycloak service account
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to exchange token with |
email |
str
|
Email of the user to exchange token for |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity_id_from_token ¶
generate_password_reset_email ¶
Generate a password reset email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a password reset |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing password reset |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Source code in components/authentication/internal/infrastructure/identity_provider.py
generate_verification_email ¶
Generate a verification email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a verification |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing verification |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity_id ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
healthcheck ¶
This healthcheck is checking Keycloak service account has the right permissions so eventually making sure Keycloak is working as expected
Source code in components/authentication/internal/infrastructure/identity_provider.py
refresh_exchanged_token ¶
Refresh an exchanged token using Keycloak service account
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to refresh token with |
refresh_token |
str
|
The refresh token to use |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing refreshed access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity_provider ¶
get_identity_provider_type ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
should_use_keycloak ¶
warn_because_not_available ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
idp_session_transport ¶
httpOnly-cookie session transport for the web BFF /auth/idp flow.
Web keeps the Keycloak token in httpOnly + Secure + SameSite cookies (XSS-safe;
CSRF via SameSite). Stateless — the Keycloak token is the session, no backend
RefreshToken. Mobile uses native OIDC + SecureStore and never touches these
endpoints, so there is no body/bearer transport here.
CookieTransport ¶
Issues / reads / clears the Keycloak IdP session via httpOnly cookies.
attach ¶
Set the session cookies on an arbitrary response (e.g. a redirect).
Source code in components/authentication/internal/infrastructure/idp_session_transport.py
clear ¶
Source code in components/authentication/internal/infrastructure/idp_session_transport.py
clear_state ¶
issue ¶
Return a JSON response carrying the session cookies.
read_id_token ¶
read_refresh_token ¶
read_state ¶
set_state_cookie ¶
Bind the in-flight OAuth state to this browser.
SameSite=Lax (NOT Strict): the callback is a cross-site top-level redirect from Keycloak, on which a Strict cookie would not be sent.
Source code in components/authentication/internal/infrastructure/idp_session_transport.py
keycloak ¶
KeycloakAdminWithErrorHandling ¶
Bases: KeycloakAdmin
Overrides KeycloakAdmin methods to handle errors. The admin client raises exceptions after fetching the server using a generic function So we can't use the decorator directly on core methods for fetching data, we need to override each high-level method we use.
KeycloakBusinessError ¶
Bases: BaseErrorCode
These errors are expected to occur due to user actions in normal application operations, and do not constitute technical errors requiring specific attention/remediation by Alan Eng. HTTP_ERRORS: list of Keycloak server http statuses that we can map as Keycloak Business Error
These errors:
- don't trigger Sentry. See: https://github.com/alan-eu/alan-apps/blob/538fb56cf374fc1a0719668e0d70e5359edbde91/backend/shared/helpers/sentry/setup.py#L71 ⧉
- Are caught by our Flask controllers => views will return an HTTP 4XX (and not a 500), see https://github.com/alan-eu/alan-apps/blob/538fb56cf374fc1a0719668e0d70e5359edbde91/backend/shared/api/helpers.py#L132 ⧉
- NB: You can pass http_code=<your_code> to additional_args to change the HTTP status code returned to the client.
Source code in components/authentication/internal/infrastructure/keycloak.py
KeycloakUser ¶
build_login_url ¶
Build a login URL depending on client ID. It uses either the front end URL or deep link URL as base URL. :param client_id: a str representing the Keycloak client :param email: a str representing the email address for login :return: the login URL
Source code in components/authentication/internal/infrastructure/keycloak.py
get_admin_client_for_realm ¶
Return the Keycloak admin client for realm, cached per-request.
Each (app, realm) pair has a dedicated service account + secret — separate
rotation per realm. Defaults to RealmName.ALAN, our overwhelming use
case; callers targeting another realm (HP creation, alaner lifecycle)
pass it explicitly.
The SDK makes a call to Keycloak when being instantiated, so we cache the
client in Flask g to instantiate only once per request per realm.
Source code in components/authentication/internal/infrastructure/keycloak.py
get_openid_client_for_realm ¶
Return the confidential KeycloakOpenID client for realm, cached per-request.
Used by the BFF login flow (code exchange / refresh / logout) and by the
token validator (certs() + decode_token). Mirrors
get_admin_client_for_realm but yields a KeycloakOpenID (OIDC) rather
than a KeycloakAdmin (service-account) client.
Source code in components/authentication/internal/infrastructure/keycloak.py
get_user_from_access_token ¶
Source code in components/authentication/internal/infrastructure/keycloak.py
with_keycloak_error_handling ¶
Source code in components/authentication/internal/infrastructure/keycloak.py
keycloak_jwks ¶
Infrastructure adapter: decode a Keycloak access token against a realm's JWKS.
Pure I/O concern — fetches (and caches) the realm's signing keys and verifies the
token's signature + iss/exp via python-keycloak's decode_token. Passing
key= makes the lib skip its internal (uncached) public_key() fetch, so
there's no Keycloak round-trip on the hot path. Authorization policy (which
realms/audiences are acceptable) lives in the domain layer; the
verify_keycloak_access_token use-case composes that policy with this decode.
decode_token_for_realm ¶
Verify signature + iss/exp against realm's JWKS; return the claims.
Raises (JWException/KeycloakError/ValueError) on signature, claim,
or key failure — the caller decides how to react (e.g. refetch on rotation).
Source code in components/authentication/internal/infrastructure/keycloak_jwks.py
keycloak_oidc_client ¶
Infrastructure adapter for the server-side Keycloak OIDC (BFF) client.
Pure I/O: token-endpoint interactions (code exchange, refresh, backchannel
logout) via python-keycloak's KeycloakOpenID, discovery lookups
(authorization / end-session endpoints), and the one-time flow-state store
(delegated to the authorization_state_repository). The flow orchestration
(PKCE generation, authorize-URL assembly, pop→exchange sequencing) lives in the
application layer (idp_login_flow).
Realm-parameterized so members can adopt the same flow later; doctor realm
(alan-health-professionals) is the first consumer. The OIDC client is a
confidential client (the backend holds the secret) — the OAuth 2.0 BFF
pattern.
authorization_endpoint ¶
The realm's OIDC authorization endpoint (from discovery).
build_end_session_url ¶
Build the KC end-session URL (front-channel SSO-cookie cleanup).
id_token_hint lets Keycloak identify the session and skip its logout
confirmation page, redirecting straight to post_logout_redirect_uri.
Source code in components/authentication/internal/infrastructure/keycloak_oidc_client.py
exchange_code ¶
Exchange an authorization code for tokens (confidential client + PKCE).
Source code in components/authentication/internal/infrastructure/keycloak_oidc_client.py
oidc_client_id ¶
The confidential BFF client id configured for realm.
pop_authorization_flow_state ¶
Consume (one-time) the stashed flow state for state. None if absent/expired.
Source code in components/authentication/internal/infrastructure/keycloak_oidc_client.py
refresh_tokens ¶
Refresh tokens at the realm token endpoint (BFF-mediated).
Source code in components/authentication/internal/infrastructure/keycloak_oidc_client.py
revoke_session ¶
Backchannel logout — revoke the Keycloak session server-side.
Source code in components/authentication/internal/infrastructure/keycloak_oidc_client.py
stash_authorization_flow_state ¶
Store the flow state under state with a TTL, for the callback to consume.
Source code in components/authentication/internal/infrastructure/keycloak_oidc_client.py
mfa_auth ¶
BadNonce ¶
DictMFAStorage ¶
Bases: MFAStorage
Source code in components/authentication/internal/infrastructure/mfa_auth.py
get ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
get_by_user ¶
Return all non-expired pending operations for a user.
Source code in components/authentication/internal/infrastructure/mfa_auth.py
put ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
update ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
DictMFAStorageEntry
module-attribute
¶
DictNotifier ¶
EmailNotifier ¶
Bases: Notifier
Source code in components/authentication/internal/infrastructure/mfa_auth.py
name ¶
notify ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
InvalidUser ¶
IosSimulatorJsonNotifier ¶
Bases: Notifier
name ¶
notify ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
MFA ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
get_operation_status ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
get_pending_operations_for_user ¶
Return all pending MFA operations for a user.
Source code in components/authentication/internal/infrastructure/mfa_auth.py
mfa_required ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
register_notifier ¶
send_email ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
update_status ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
validate_or_reject ¶
validate_or_reject(
operation_id,
validation_code=None,
authenticated=False,
authenticated_user=None,
reject=False,
)
Source code in components/authentication/internal/infrastructure/mfa_auth.py
MFAError ¶
MfaRequestOrigin ¶
MfaRequiredSchema ¶
Bases: Schema
Schema for MFA required decorator arguments.
refresh_token_type
class-attribute
instance-attribute
¶
refresh_token_type = Str(
required=True,
error_messages={
"required": "type of the refresh token: web or mobile"
},
)
NotifierType ¶
Bases: AlanBaseEnum
OperationExpired ¶
OperationRejected ¶
OperationValidated ¶
PendingOperation
dataclass
¶
PushNotificationSender
module-attribute
¶
PushNotifier ¶
Bases: Notifier
Source code in components/authentication/internal/infrastructure/mfa_auth.py
name ¶
notify ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
RedisMFAStorage ¶
Bases: MFAStorage
Source code in components/authentication/internal/infrastructure/mfa_auth.py
get ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
get_by_user ¶
Return all non-expired pending operations for a user.
Performance: 2 round trips (SMEMBERS + pipelined GETs). The SET is naturally small (1-2 entries, 5 min TTL) so SMEMBERS is safe here. Stale IDs are cleaned on read to keep the SET compact.
Source code in components/authentication/internal/infrastructure/mfa_auth.py
mfa_operations_by_user_redis_id
staticmethod
¶
pending_operation_redis_id
staticmethod
¶
put ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
update ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
ValidationStatus ¶
create_mfa_storage ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
repository ¶
AuthenticationIdentityMapper ¶
Mapper between AuthenticationIdentity (domain dataclass) and AuthenticationIdentityModel (SQLAlchemy model).
AuthenticationRepository ¶
Bases: BaseAuthenticationRepository
Source code in components/authentication/internal/infrastructure/repository.py
delete ¶
Source code in components/authentication/internal/infrastructure/repository.py
get_by_id ¶
Source code in components/authentication/internal/infrastructure/repository.py
get_by_keycloak_id ¶
Source code in components/authentication/internal/infrastructure/repository.py
get_by_profile_id ¶
Source code in components/authentication/internal/infrastructure/repository.py
save ¶
BaseAuthenticationRepository ¶
Bases: ABC
delete
abstractmethod
¶
get_by_id
abstractmethod
¶
get_by_keycloak_id
abstractmethod
¶
get_by_profile_id
abstractmethod
¶
get_or_raise_by_id ¶
Source code in components/authentication/internal/infrastructure/repository.py
get_or_raise_by_keycloak_id ¶
Source code in components/authentication/internal/infrastructure/repository.py
get_or_raise_by_profile_id ¶
Source code in components/authentication/internal/infrastructure/repository.py
InMemoryAuthenticationRepository ¶
Bases: BaseAuthenticationRepository
AuthenticationRepository using an in-memory dictionary, there are no transactions to manage.
This is useful for testing purposes.
Source code in components/authentication/internal/infrastructure/repository.py
delete ¶
get_by_id ¶
get_by_keycloak_id ¶
Source code in components/authentication/internal/infrastructure/repository.py
get_by_profile_id ¶
Source code in components/authentication/internal/infrastructure/repository.py
retro_compatibility_repository ¶
RetroCompatibilityAuthenticationRepository ¶
Bases: BaseAuthenticationRepository
This class is a retro-compatibility layer for the authentication repository. It uses the country users to link a profile id to an authentication identity. ⚠️ Cannot work in 🇨🇦 that doesn't import all models from all components.
Source code in components/authentication/internal/infrastructure/retro_compatibility_repository.py
delete ¶
Source code in components/authentication/internal/infrastructure/retro_compatibility_repository.py
get_by_id ¶
get_by_keycloak_id ¶
Source code in components/authentication/internal/infrastructure/retro_compatibility_repository.py
get_by_profile_id ¶
Source code in components/authentication/internal/infrastructure/retro_compatibility_repository.py
save ¶
Source code in components/authentication/internal/infrastructure/retro_compatibility_repository.py
unit_of_work ¶
InMemoryUnitOfWork ¶
Bases: UnitOfWork
UnitOfWork using an in-memory dictionary, there are no transactions to manage.
This is useful for testing purposes.
Source code in components/authentication/internal/infrastructure/unit_of_work.py
SQLAlchemyUnitOfWork ¶
SQLAlchemyUnitOfWork(
session=None,
commit_at_end=False,
dispatch_at_end=True,
event_dispatcher=None,
authentication_repository_factory=None,
)
Bases: UnitOfWork
Source code in components/authentication/internal/infrastructure/unit_of_work.py
__enter__ ¶
Source code in components/authentication/internal/infrastructure/unit_of_work.py
authentication_repository_factory
instance-attribute
¶
authentication_repository_factory = (
authentication_repository_factory
or AuthenticationRepository
)
close ¶
commit ¶
rollback ¶
UnitOfWork ¶
Bases: ABC
Source code in components/authentication/internal/infrastructure/unit_of_work.py
__enter__ ¶
__exit__ ¶
Source code in components/authentication/internal/infrastructure/unit_of_work.py
close
abstractmethod
¶
commit
abstractmethod
¶
dispatch ¶
Source code in components/authentication/internal/infrastructure/unit_of_work.py
event_dispatcher
instance-attribute
¶
flush_events ¶
Flush events from unit of work and return them.
Additionally, it stores them internally to be dispatched later.
Source code in components/authentication/internal/infrastructure/unit_of_work.py
mailers ¶
account_compromise ¶
send_account_compromised_after_credential_stuffing_email ¶
Send notification email to user about account compromise after credential stuffing attack.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str
|
identifier of the user to notify as a string |
required |
Returns:
| Type | Description |
|---|---|
LangTemplateMailerParams
|
LangTemplateMailerParams for the email to be sent |
Source code in components/authentication/internal/mailers/account_compromise.py
async_mailer ¶
async_mailer ¶
async_mailer(
category,
priority,
email_queue_name,
delivery=DEFAULT_DELIVERY,
job_timeout=None,
enqueue=True,
redacted_args=None,
)
Source code in components/authentication/internal/mailers/async_mailer.py
models ¶
authentication_identity ¶
AuthenticationIdentityModel ¶
Bases: BaseModel
__table_args__
class-attribute
instance-attribute
¶
__table_args__ = (
Index(
"ix_authentication_identity_profile_id_realm",
"profile_id",
"realm",
unique=True,
),
Index(
"ix_authentication_identity_keycloak_id_realm",
"keycloak_id",
"realm",
unique=True,
),
{"schema": AUTHENTICATION_SCHEMA_NAME},
)
keycloak_id
class-attribute
instance-attribute
¶
profile_id
class-attribute
instance-attribute
¶
realm
class-attribute
instance-attribute
¶
helpers ¶
sso_domain_config ¶
SsoDomainConfigModel ¶
Bases: BaseModel
Maps email domains to enterprise SSO identity providers.
When a user's email domain matches a row (with enabled=True), the login flow redirects to Keycloak with the configured idp_hint.
components.authentication.observability ¶
components.authentication.public ¶
api ¶
AuthenticationService ¶
Entry point to interact with the identity provider
This service is a CRUD api to interact with the identity provider.
Instantiates the ProfileService
Default values are provided for target production use, you may need to override them.
Source code in components/authentication/public/api.py
change_identity_email ¶
Request an email change for an identity.
This method handles complex email change scenarios: 1. Approved: Email is available and gets updated successfully 2. Denied: Email conflicts with existing identity (raises error) 3. Merged: Email belongs to another identity - triggers identity merge
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to change email for |
required |
email
|
str
|
New email address (will be normalized) |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Raises:
| Type | Description |
|---|---|
BaseErrorCode
|
If the email change is denied due to conflicts |
Events Emitted
IdentityEmailChangedEvent: When email is successfully changed IdentityMergedEvent: When identities are merged due to email conflict
Examples:
>>> try:
... authentication_service.change_identity_email(
... identity_id=identity_id,
... email="new-email@example.com"
... )
... print("Email changed successfully")
... except BaseErrorCode:
... print("Email change denied - conflict with existing identity")
Note
Email merging happens when the target email already belongs to another identity. In this case, the two identities are merged and the old identity is marked for deletion.
Source code in components/authentication/public/api.py
change_identity_first_name ¶
Update the first name of an identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to update |
required |
first_name
|
str | None
|
New first name, or None to clear the existing name |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Events Emitted
IdentityFirstNameChanged: When the first name is updated
Examples:
Set a first name:
>>> authentication_service.change_identity_first_name(
... identity_id=identity_id,
... first_name="Jane"
... )
Clear the first name:
>>> authentication_service.change_identity_first_name(
... identity_id=identity_id,
... first_name=None
... )
Note
This method will eventually be replaced by a subscription to profile events (IdentityInformationChanged) to maintain data consistency.
Source code in components/authentication/public/api.py
change_identity_language ¶
Update the preferred language of an identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to update |
required |
language
|
Lang
|
New preferred language (ISO639 language code) |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Events Emitted
IdentityLanguageChanged: When the language preference is updated
Examples:
>>> authentication_service.change_identity_language(
... identity_id=identity_id,
... language=Lang.FRENCH
... )
Note
This method will eventually be replaced by a subscription to profile events (PreferredLanguageChanged) to maintain data consistency.
Source code in components/authentication/public/api.py
change_identity_last_name ¶
Update the last name of an identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to update |
required |
last_name
|
str | None
|
New last name, or None to clear the existing name |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Events Emitted
IdentityLastNameChanged: When the last name is updated
Examples:
Set a last name:
>>> authentication_service.change_identity_last_name(
... identity_id=identity_id,
... last_name="Smith"
... )
Clear the last name:
>>> authentication_service.change_identity_last_name(
... identity_id=identity_id,
... last_name=None
... )
Note
This method will eventually be replaced by a subscription to profile events (IdentityInformationChanged) to maintain data consistency.
Source code in components/authentication/public/api.py
change_keycloak_id ¶
Update the Keycloak ID associated with a profile.
This method updates the link between a profile and its Keycloak identity. It's primarily used during migration scenarios or when reassigning identities between Keycloak instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile_id
|
UUID
|
UUID of the profile to update the Keycloak link for |
required |
new_keycloak_id
|
UUID | None
|
New Keycloak identity ID, or None to unlink |
required |
realm
|
RealmName
|
Keycloak realm to scope the operation to. Defaults to RealmName.ALAN. |
ALAN
|
Examples:
Link profile to new Keycloak identity:
>>> authentication_service.change_keycloak_id(
... profile_id=profile_id,
... new_keycloak_id=new_identity_id
... )
Unlink profile from Keycloak (temporary state):
>>> authentication_service.change_keycloak_id(
... profile_id=profile_id,
... new_keycloak_id=None
... )
Use Cases
- Keycloak instance migrations
- Identity consolidation after mergers
- Fixing broken identity links
- Temporary unlinking during maintenance
Source code in components/authentication/public/api.py
change_mfa_status ¶
Update the Multi-Factor Authentication settings for an identity.
This method allows independent control of two MFA settings: - mfa_enabled: Whether the user has MFA configured/activated - mfa_required: Whether MFA is mandatory for this identity
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to update |
required |
mfa_enabled
|
bool | None
|
Whether MFA is enabled/configured (None = no change) |
None
|
mfa_required
|
bool | None
|
Whether MFA is required for login (None = no change) |
None
|
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Examples:
Require MFA for a high-privilege user:
>>> authentication_service.change_mfa_status(
... identity_id=admin_identity_id,
... mfa_required=True
... )
User successfully configured MFA:
>>> authentication_service.change_mfa_status(
... identity_id=identity_id,
... mfa_enabled=True
... )
Disable MFA requirement (but keep it configured):
>>> authentication_service.change_mfa_status(
... identity_id=identity_id,
... mfa_required=False # mfa_enabled unchanged
... )
MFA States
- Required + Enabled: User must use MFA and has it configured ✅
- Required + Not Enabled: User must configure MFA before login ⚠️
- Not Required + Enabled: User can optionally use MFA
- Not Required + Not Enabled: Standard password-only login
Source code in components/authentication/public/api.py
check_identity_has_password ¶
Check if an identity has a password configured.
This is useful for determining if an identity can use password-based authentication or if it relies solely on external identity providers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to check |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the identity has a password set, False otherwise (also returns False if identity doesn't exist) |
Examples:
>>> if authentication_service.check_identity_has_password(identity_id):
... print("Password authentication available")
... else:
... print("No password set - external auth required")
Source code in components/authentication/public/api.py
check_identity_password ¶
Verify if the provided password is correct for an identity.
This method performs password verification against the identity's stored credentials in Keycloak. The password should be pre-hashed according to the system's hashing requirements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to authenticate |
required |
prehashed_password
|
str
|
The password after client-side hashing |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the password is correct, False otherwise (also returns False if identity doesn't exist or has no password) |
Examples:
Typical login flow:
>>> if not authentication_service.check_identity_has_password(identity_id):
... return "No password set for this identity"
>>> if authentication_service.check_identity_password(
... identity_id=identity_id,
... prehashed_password=hashed_password
... ):
... return "Authentication successful"
... else:
... return "Invalid credentials"
Security Note
Failed password attempts are logged with warnings for security monitoring.
Source code in components/authentication/public/api.py
clear_identity_email ¶
Replace an identity's email with an invalidated placeholder email.
This method is used to effectively "clear" an email while maintaining database constraints that require email uniqueness. The original email is replaced with an invalidated version that won't conflict with future registrations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to clear the email for |
required |
invalidated_email
|
str
|
Invalidated email format to replace the original (e.g., "invalidated-{timestamp}@domain.com") |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Events Emitted
IdentityEmailCleared: When the email is successfully invalidated
Examples:
>>> import time
>>> timestamp = int(time.time())
>>> invalidated = f"invalidated-{timestamp}@example.com"
>>> authentication_service.clear_identity_email(
... identity_id=identity_id,
... invalidated_email=invalidated
... )
Use Cases
- GDPR compliance (email anonymization)
- Freeing up email for re-registration
- Deactivating accounts while preserving audit trails
- Handling bounced/invalid email addresses
Note
The invalidated email should follow a consistent pattern to avoid conflicts and maintain traceability for audit purposes.
Source code in components/authentication/public/api.py
create
classmethod
¶
Create a new instance of the AuthenticationService with the default parameters.
Source code in components/authentication/public/api.py
create_identity ¶
create_identity(
*,
email,
language,
first_name=None,
last_name=None,
profile_id=None,
mfa_required=None,
realm=RealmName.ALAN
)
Create a new identity in the identity provider (Keycloak).
This method creates a new authentication identity and links it to a profile if provided. The identity is created in Keycloak and a corresponding record is stored in the authentication_identity table to maintain the link with the profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
email
|
str
|
Valid email address for the identity (will be normalized) |
required |
language
|
Lang
|
ISO639 language code for the identity's preferred language |
required |
first_name
|
str | None
|
Optional first name of the user -> will be used in email sent by keycloak |
None
|
last_name
|
str | None
|
Optional last name of the user -> will be used in email sent by keycloak |
None
|
profile_id
|
UUID | None
|
Optional UUID of the associated profile (can be linked later) |
None
|
mfa_required
|
bool | None
|
Whether MFA is required for this identity (None = use default) |
None
|
realm
|
RealmName
|
Keycloak realm to provision the identity in. Defaults to RealmName.ALAN. |
ALAN
|
Returns:
| Name | Type | Description |
|---|---|---|
UUID |
UUID
|
The Keycloak identity ID of the newly created identity |
Raises:
| Type | Description |
|---|---|
conflict
|
If an identity with this email already exists |
missing_resource
|
If identity creation fails |
Events Emitted
IdentityCreatedEvent: When the identity is successfully created
Examples:
Create a new identity with all details:
>>> authentication_service = AuthenticationService.create()
>>> identity_id = authentication_service.create_identity(
... email="user@example.com",
... language=Lang.ENGLISH,
... first_name="John",
... last_name="Doe",
... profile_id=profile_id,
... mfa_required=False
... )
Create minimal identity without profile:
>>> identity_id = authentication_service.create_identity(
... email="minimal@example.com",
... language=Lang.FRENCH
... )
Source code in components/authentication/public/api.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
delete_identity ¶
Mark an identity for deletion.
This method prepares an identity for complete removal from both Keycloak and the local authentication_identity table. The actual deletion occurs when the database transaction commits.
⚠️ IMPORTANT: This operation is transactional - if the session is rolled back, the identity will not be deleted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to delete |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Examples:
>>> try:
... authentication_service.delete_identity(identity_id)
... # Other operations...
... # If everything succeeds, identity will be deleted on commit
... except Exception:
... print("Identity deletion prevented by rollback")
Use Cases
- Account deactivation/closure
- GDPR compliance (right to be forgotten)
- Cleaning up test/duplicate identities
Note
Consider clearing or anonymizing related data before deletion to maintain referential integrity across the system.
Source code in components/authentication/public/api.py
delete_identity_credentials ¶
Remove the credentials (email and password) from an identity.
This effectively disables password-based authentication for the identity, forcing it to rely on external identity providers for authentication.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to remove credentials from |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Examples:
>>> authentication_service.delete_identity_credentials(identity_id)
>>> has_password = authentication_service.check_identity_has_password(identity_id)
>>> print(f"Has password: {has_password}") # False
Use Cases
- Migrating from password to external authentication
- Security incident response (disable compromised credentials)
- Enforcing external authentication policies
Source code in components/authentication/public/api.py
exchange_token_for_user ¶
Exchange a service account token for a user token.
This method uses the service account's privileges to generate access and refresh tokens on behalf of a user. This is typically used for server-to-server authentication scenarios where you need to act as a specific user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_client_id
|
str
|
The Keycloak client ID to generate tokens for |
required |
email
|
str
|
Email address of the user to impersonate |
required |
realm
|
RealmName
|
Keycloak realm the user lives in. Defaults to RealmName.ALAN. |
ALAN
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Dictionary containing 'access_token' and 'refresh_token' keys |
Raises:
| Type | Description |
|---|---|
missing_resource
|
If no identity exists for the email |
Examples:
>>> tokens = authentication_service.exchange_token_for_user(
... target_client_id="mobile-app",
... email="user@example.com",
... realm=RealmName.ALAN
... )
>>> access_token = tokens['access_token']
>>> refresh_token = tokens['refresh_token']
>>> headers = {'Authorization': f'Bearer {access_token}'}
Security Note
This is a privileged operation that should only be used in trusted server-side contexts. Never expose this functionality to client-side code.
Source code in components/authentication/public/api.py
get_identity_by_email ¶
Retrieve an identity by its email address.
The email is automatically normalized before lookup to ensure consistent formatting across the system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
email
|
str
|
Email address to search for (will be normalized) |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Returns:
| Type | Description |
|---|---|
AuthIdentity | None
|
AuthIdentity | None: The identity with this email if found, None otherwise |
Examples:
Email is automatically normalized:
>>> identity = authentication_service.get_identity_by_email("User@Example.COM", realm=RealmName.ALAN)
>>> if identity:
... print(f"Normalized email: {identity.email}") # user@example.com
... print(f"Has password: {identity.has_password}")
Source code in components/authentication/public/api.py
get_keycloak_identity ¶
Retrieve an identity directly by its Keycloak ID.
This method queries Keycloak directly using the identity ID to retrieve the full identity information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keycloak_id
|
UUID
|
UUID of the identity in Keycloak |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Returns:
| Type | Description |
|---|---|
AuthIdentity | None
|
AuthIdentity | None: The identity data if found in Keycloak, None otherwise |
Examples:
>>> identity = authentication_service.get_keycloak_identity(identity_id)
>>> if identity:
... print(f"Identity email: {identity.email}")
... print(f"Language: {identity.language}")
Source code in components/authentication/public/api.py
get_keycloak_identity_by_profile_id ¶
Retrieve an identity by its associated profile_id.
This method looks up the authentication_identity table to find the Keycloak ID associated with the given profile_id, then retrieves the full identity data from Keycloak.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile_id
|
UUID
|
UUID of the profile to find the associated identity for |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Returns:
| Type | Description |
|---|---|
AuthIdentity | None
|
AuthIdentity | None: The identity data if found, None if no identity is linked to this profile or if the identity doesn't exist in Keycloak |
Examples:
Retrieve identity for a profile:
>>> identity = authentication_service.get_keycloak_identity_by_profile_id(profile_id)
>>> if identity:
... print(f"Found identity: {identity.email}")
... print(f"MFA required: {identity.mfa_required}")
... else:
... print("No identity found for this profile")
Source code in components/authentication/public/api.py
get_or_raise_keycloak_identity ¶
Retrieve an identity by its Keycloak ID or raise an error if not found.
This is a convenience method for cases where the identity must exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity in Keycloak |
required |
Returns:
| Name | Type | Description |
|---|---|---|
AuthIdentity |
AuthIdentity
|
The identity data |
Raises:
| Type | Description |
|---|---|
login_error
|
If the identity is not found |
Examples:
>>> try:
... identity = authentication_service.get_or_raise_keycloak_identity(identity_id)
... print(f"Found identity: {identity.email}")
... except BaseErrorCode:
... print("Identity not found - login error")
Source code in components/authentication/public/api.py
logout_identity_from_all_sessions ¶
Force logout of an identity from all active sessions.
This method invalidates all active sessions for the specified identity across all clients and devices. The user will need to re-authenticate for any further requests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity to logout from all sessions |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Examples:
>>> authentication_service.logout_identity_from_all_sessions(identity_id)
>>> print("User logged out from all sessions")
Use Cases
- Security incident response (compromised account)
- Password changes requiring re-authentication
- Account suspension/deactivation
- Administrative logout for policy enforcement
- User-requested "logout everywhere" feature
Note
This affects all active sessions including web browsers, mobile apps, and API tokens. The logout is immediate and cannot be undone.
Source code in components/authentication/public/api.py
message_bus
instance-attribute
¶
message_bus = message_bus or MessageBus(
unit_of_work,
injected_event_handlers,
injected_command_handlers,
)
refresh_exchanged_token ¶
Refresh an exchanged token to get a new access token.
This method uses a refresh token (obtained from exchange_token_for_user) to generate a new access token and refresh token pair. This extends the user session without requiring re-authentication.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
refresh_token
|
str
|
The refresh token from a previous token exchange |
required |
target_client_id
|
str
|
The Keycloak client ID the tokens are for |
required |
realm
|
RealmName
|
Keycloak realm the user lives in. Defaults to RealmName.ALAN. |
ALAN
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Dictionary containing new 'access_token' and 'refresh_token' |
Examples:
>>> initial_tokens = authentication_service.exchange_token_for_user(
... target_client_id="mobile-app",
... email="user@example.com",
... realm=RealmName.ALAN
... )
>>> # Later, when access token expires
>>> refreshed_tokens = authentication_service.refresh_exchanged_token(
... refresh_token=initial_tokens['refresh_token'],
... target_client_id="mobile-app",
... realm=RealmName.ALAN
... )
>>> new_access_token = refreshed_tokens['access_token']
Token Lifecycle
- exchange_token_for_user() → initial tokens
- Use access_token for API calls
- When access_token expires → refresh_exchanged_token()
- Repeat step 3 until refresh_token expires
Source code in components/authentication/public/api.py
send_password_reset_email ¶
Send a password reset email to an identity.
This triggers Keycloak to send a password reset email to the specified identity. The email parameter is used for verification to ensure the request is legitimate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity requesting password reset |
required |
email
|
str
|
Email address of the identity (for verification) |
required |
client_id
|
str
|
The client ID for the reset flow |
required |
redirect_uri
|
str | None
|
Optional URI to redirect to after reset completion |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Events Emitted
PasswordResetEmailSentEvent: When the reset email is successfully sent
Examples:
>>> authentication_service.send_password_reset_email(
... identity_id=identity_id,
... email="user@example.com",
... client_id="web-app",
... redirect_uri="https://app.example.com/reset-complete"
... )
Security Note
The email parameter serves as a verification step - the identity must own the email address to receive the reset link.
Source code in components/authentication/public/api.py
send_verification_email ¶
send_verification_email(
*,
client_id,
redirect_uri,
identity_id=None,
email=None,
realm=RealmName.ALAN
)
Send an email verification message to an identity.
This triggers Keycloak to send a verification email to the user. Either identity_id or email must be provided. If both are given, identity_id takes precedence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
The client ID for the verification flow |
required |
redirect_uri
|
str | None
|
Optional URI to redirect to after verification |
required |
identity_id
|
UUID | None
|
UUID of the identity to send verification to (preferred) |
None
|
email
|
str | None
|
Email address to send verification to (alternative) |
None
|
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Raises:
| Type | Description |
|---|---|
missing_resource
|
If neither identity_id nor email is provided, or if the specified identity/email is not found |
Examples:
Send verification by identity ID (preferred):
>>> authentication_service.send_verification_email(
... identity_id=identity_id,
... client_id="web-app",
... redirect_uri="https://app.example.com/verify-success"
... )
Send verification by email (fallback):
>>> authentication_service.send_verification_email(
... email="user@example.com",
... client_id="web-app",
... redirect_uri=None # Use default redirect
... )
Note
The actual email sending is handled by Keycloak's email verification system.
Source code in components/authentication/public/api.py
set_identity_credentials ¶
set_identity_credentials(
identity_id,
*,
email,
prehashed_password,
is_email_verified=True,
mfa_required=None,
realm=RealmName.ALAN
)
Set or update the credentials (email and password) for an existing identity.
⚠️ IMPORTANT: The identity must already exist. Use create_identity() first if you need to create a new identity.
This method handles several scenarios: 1. Same email: Updates password for existing identity 2. New available email: Updates both email and password 3. Email conflict: Raises error if email belongs to different identity
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the existing identity to update |
required |
email
|
str
|
Email address to set (will be normalized) |
required |
prehashed_password
|
str
|
Pre-hashed password to set |
required |
is_email_verified
|
bool
|
Whether the email has been verified |
True
|
mfa_required
|
bool | None
|
MFA requirement setting (None = no change) |
None
|
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Raises:
| Type | Description |
|---|---|
missing_resource
|
If the identity doesn't exist |
conflict
|
If email is already used by different identity |
Examples:
Set initial credentials for new identity:
>>> authentication_service.set_identity_credentials(
... identity_id=identity_id,
... email="user@example.com",
... prehashed_password=hashed_password,
... is_email_verified=True,
... mfa_required=False
... )
Update password for existing identity:
>>> authentication_service.set_identity_credentials(
... identity_id=identity_id,
... email="user@example.com", # same email
... prehashed_password=new_hashed_password,
... is_email_verified=True
... )
Source code in components/authentication/public/api.py
verify_identity_email ¶
Verify the email address for an existing identity without requiring a password.
This method is useful when you want to verify an email address before the user has set a password (e.g., during initial account setup).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_id
|
UUID
|
UUID of the identity whose email should be verified |
required |
realm
|
RealmName
|
Keycloak realm the identity lives in. Defaults to RealmName.ALAN. |
ALAN
|
Raises:
| Type | Description |
|---|---|
missing_resource
|
If the identity doesn't exist |
Examples:
>>> authentication_service.verify_identity_email(identity_id)
>>> identity = authentication_service.get_identity(identity_id)
>>> print(f"Email verified: {identity.email_verified}") # True
Source code in components/authentication/public/api.py
verify_keycloak_token ¶
Validate a Keycloak access token and resolve its identity.
Stateless: the realm is derived from the token iss claim, the
signature is verified locally against that realm's JWKS, and the
(keycloak_id, realm) pair is mapped to a profile via the local
authentication_identity table — no Keycloak round-trip, no backend
session. This is the validation core for the bearer_idp/cookie_idp
authentication paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The raw Keycloak access token (JWT). |
required |
Returns:
| Type | Description |
|---|---|
tuple[UUID, UUID, UUID] | None
|
|
Source code in components/authentication/public/api.py
blueprints ¶
blueprint ¶
AuthBlueprint ¶
Bases: CustomBlueprint
Base blueprint for authentication.
Initialize the blueprint.
Source code in components/authentication/public/blueprints/blueprint.py
log_api_call
classmethod
¶
Log the API call.
Source code in components/authentication/public/blueprints/blueprint.py
register_mfa_notifier ¶
route ¶
Route decorator that logs the API call.
Source code in components/authentication/public/blueprints/blueprint.py
CheckMfaPostJsonSchema ¶
CheckSsoPostJsonSchema ¶
Bases: Schema
Schema for SSO domain check endpoint.
DeduceCountriesPostJsonSchema ¶
Bases: Schema
Schema for deduce countries endpoint.
EnableDisableMfaPatchJsonSchema ¶
Bases: Schema
Schema for enable/disable MFA endpoint.
ExchangeTokenPostJsonSchema ¶
IdpAuthorizeGetQuerySchema ¶
Bases: Schema
Query args for starting Keycloak login.
IdpCallbackGetQuerySchema ¶
Bases: Schema
Query args Keycloak appends when redirecting to the BFF callback.
Two mutually-exclusive shapes (RFC 6749 §4.1.2,
https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2 ⧉): the success leg
carries code, the error leg carries error (+ optional error_description)
and no code. Both always carry state.
code
class-attribute
instance-attribute
¶
error
class-attribute
instance-attribute
¶
error_description
class-attribute
instance-attribute
¶
state
class-attribute
instance-attribute
¶
validate_code_xor_error ¶
Exactly one of code / error must be present (success vs error leg).
Source code in components/authentication/public/blueprints/blueprint.py
IdpLogoutDeleteQuerySchema ¶
IdpRefreshPostJsonSchema ¶
Bases: Schema
Body for the BFF token-refresh endpoint (refresh token read from cookie).
LogoutDeleteJsonSchema ¶
PasswordChangePostJsonSchema ¶
Bases: Schema
Schema for password change endpoint.
current_prehashed_password
class-attribute
instance-attribute
¶
password_change_reason
class-attribute
instance-attribute
¶
password_change_reason = Str(
required=False,
load_default="weak_password",
validate=OneOf(["weak_password", "requested_by_user"]),
)
validate_password_required_if_enabled ¶
Require password when password strength validation feature flag is on.
Source code in components/authentication/public/blueprints/blueprint.py
PasswordResetPostJsonSchema ¶
Bases: Schema
Schema for password reset endpoint.
validate_password_required_if_enabled ¶
Require password when password strength validation feature flag is on.
Source code in components/authentication/public/blueprints/blueprint.py
RefreshTokenExchangePostJsonSchema ¶
Bases: Schema
Schema for refresh token exchange endpoint.
RejectMfaPostJsonSchema ¶
Bases: _MfaOperationPostJsonSchema
Schema for reject MFA endpoint.
SendMfaEmailPostJsonSchema ¶
ValidateMfaPostJsonSchema ¶
VerifyEmailPostJsonSchema ¶
Bases: Schema
Schema for verify email endpoint.
create_auth_blueprint ¶
Create an auth blueprint.
Source code in components/authentication/public/blueprints/blueprint.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 | |
is_password_strength_validation_enabled ¶
Check if password strength validation is enabled.
Source code in components/authentication/public/blueprints/blueprint.py
blueprint_with_password_reset_request ¶
PasswordResetRequestPostJsonSchema ¶
Bases: Schema
Schema for password reset request endpoint.
create_auth_blueprint_with_password_reset_request ¶
create_auth_blueprint_with_password_reset_request(
token_auth, user_password_changed=None, enable_mfa=False
)
Create an auth blueprint from AuthBlueprint with a password reset request endpoint.
Source code in components/authentication/public/blueprints/blueprint_with_password_reset_request.py
is_global_password_reset_enabled ¶
Check if global password reset is enabled for the given email.
Source code in components/authentication/public/blueprints/blueprint_with_password_reset_request.py
email ¶
extract_domain_from_email ¶
Extract the lowercased domain from an email address.
Uses rsplit to handle RFC 5322 emails with quoted local parts containing '@' (e.g. "user@org"@example.com). Cf. https://datatracker.ietf.org/doc/html/rfc5322#section-3.4.1 ⧉
There is no need to check if the domain is valid as we just want to match with the database, and invalid domains won't match any rows anyway.
Source code in components/authentication/internal/business_logic/queries/check_sso_domain.py
entities ¶
AuthIdentity
dataclass
¶
AuthIdentity(
id,
first_name,
last_name,
email,
language,
email_verified,
mfa_enabled,
mfa_required=False,
)
Dataclass to isolate the component internal identity and its logic from the public one.
__eq__ ¶
__hash__ ¶
from_domain
classmethod
¶
Mapper from the domain identity to the public one.
Source code in components/authentication/public/entities.py
events ¶
component_events ¶
IdentityCreatedEvent
dataclass
¶
Bases: Message
Identity successfully created in Keycloak.
Emitted by: AuthenticationService.create_identity()
IdentityEmailChangedEvent
dataclass
¶
IdentityEmailCleared
dataclass
¶
IdentityMergedEvent
dataclass
¶
Bases: Message
Two identities merged due to email conflict.
Emitted by: AuthenticationService.change_identity_email() when target email already belongs to another identity, triggering automatic merge
PasswordResetEmailSentEvent
dataclass
¶
subscription ¶
subscribe_to_events ¶
All event subscriptions for the authentication component are here
Source code in components/authentication/public/events/subscription.py
identity_provider ¶
AuthIdentity ¶
DevIdentity ¶
DevIdentity(
id,
email,
language,
first_name,
last_name,
email_verified=True,
mfa_enabled=False,
mfa_required=False,
)
Bases: AuthIdentity
Source code in components/authentication/internal/infrastructure/identity_provider.py
check_password ¶
clear_password ¶
delete ¶
has_password ¶
logout_all_sessions ¶
set_email ¶
set_first_and_last_names ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_first_name ¶
set_language ¶
set_last_name ¶
set_mfa_enabled ¶
set_mfa_required ¶
set_password ¶
DevIdentityProvider ¶
Bases: IdentityProvider
A stubbed identity provider for the dev environment. Cases to test: - Standard login with email: http://localhost:4001/login ⧉ - Company creation: http://localhost:4001/fr-company-discovery/share?contractCoverOption=coverChildren&ccnCode=1486&participation=50&healthProduct=green&choosePrevoyance=true&hasLegacyHealthContract=true&hasLegacyPrevoyanceContract=true ⧉ - Fixture: http://localhost:8001/admin_tools/test_data_generator/new?fixture=LSBjb21wYW55Og%3D%3D ⧉ - User auth login: http://localhost:8002/auth/login?next=%2Foauth2%2Fauthorize%3Fresponse_type%3Dcode%26client_id%3Dmind_dev%26redirect_uri%3Djourapp%3A%252F%252Fauthcallback%252Falan%26scope%3Dopenid%2520email%26state%3D9dc9c12d-0d3b-44f1-af8f-c3b8e829b1eb ⧉ - Freelancer signup: http://localhost:4001/freelancer-signup ⧉
Source code in components/authentication/internal/infrastructure/identity_provider.py
create_new_identity ¶
create_new_identity(
email,
language,
first_name,
last_name,
is_email_verified=True,
mfa_enabled=False,
mfa_required=False,
realm=RealmName.ALAN,
)
Source code in components/authentication/internal/infrastructure/identity_provider.py
exchange_token_for_user ¶
This provides a fake exchanged token for the scenario where the backend issues Keycloak tokens on behalf of the user.
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to exchange token with |
email |
str
|
Email of the user to exchange token for |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity_id_from_token ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
generate_password_reset_email ¶
Generate a password reset email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a password reset |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing password reset |
Source code in components/authentication/internal/infrastructure/identity_provider.py
generate_verification_email ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity_id ¶
healthcheck ¶
refresh_exchanged_token ¶
This provides a fake exchanged refresh tokens for the scenario where the backend issues Keycloak tokens on behalf of the user.
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to refresh token with |
refresh_token |
str
|
The refresh token to use |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing refreshed access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
IdentityProvider ¶
create_new_identity ¶
create_new_identity(
email,
language,
first_name,
last_name,
is_email_verified=True,
mfa_enabled=False,
mfa_required=False,
realm=RealmName.ALAN,
)
Source code in components/authentication/internal/infrastructure/identity_provider.py
exchange_token_for_user ¶
Exchange token for a given user using service account
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to exchange token with |
email |
str
|
Email of the user to exchange token for |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity ¶
find_identity_id_from_token ¶
generate_password_reset_email ¶
Generate a password reset email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a password reset |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing password reset |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Source code in components/authentication/internal/infrastructure/identity_provider.py
generate_verification_email ¶
Generate a verification email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a verification |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing verification |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity ¶
get_identity_id ¶
healthcheck ¶
refresh_exchanged_token ¶
Refresh an exchanged token using service account
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to refresh token with |
refresh_token |
str
|
The refresh token to use |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing refreshed access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
IdentityProviderType ¶
KeycloakIdentity ¶
Bases: AuthIdentity
Source code in components/authentication/internal/infrastructure/identity_provider.py
check_password ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
clear_password ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
client
instance-attribute
¶
client = OAuth2Session(
client_id=get("KEYCLOAK_CLIENT_ID"),
token_endpoint=f"{keycloak_host}/realms/{keycloak_realm}/protocol/openid-connect/token",
)
delete ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
has_password ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
logout_all_sessions ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_email ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_first_and_last_names ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_first_name ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_language ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_last_name ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_mfa_enabled ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_mfa_required ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
set_password ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
update_pending_deletion ¶
KeycloakIdentityProvider ¶
Bases: IdentityProvider
Source code in components/authentication/internal/infrastructure/identity_provider.py
create_new_identity ¶
create_new_identity(
email,
language,
first_name,
last_name,
is_email_verified=True,
mfa_enabled=False,
mfa_required=False,
realm=RealmName.ALAN,
)
Source code in components/authentication/internal/infrastructure/identity_provider.py
exchange_token_for_user ¶
Exchange token for a user using Keycloak service account
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to exchange token with |
email |
str
|
Email of the user to exchange token for |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
find_identity_id_from_token ¶
generate_password_reset_email ¶
Generate a password reset email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a password reset |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing password reset |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Source code in components/authentication/internal/infrastructure/identity_provider.py
generate_verification_email ¶
Generate a verification email in our identity provider
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The email address of the user to trigger a verification |
client_id |
str
|
Identity provider client ID (e.g. "alan-mobile-prod", "fr-web-prod") |
redirect_uri |
str | None
|
The URI to redirect to after performing verification |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
get_identity_id ¶
Source code in components/authentication/internal/infrastructure/identity_provider.py
healthcheck ¶
This healthcheck is checking Keycloak service account has the right permissions so eventually making sure Keycloak is working as expected
Source code in components/authentication/internal/infrastructure/identity_provider.py
refresh_exchanged_token ¶
Refresh an exchanged token using Keycloak service account
Attributes:
| Name | Type | Description |
|---|---|---|
target_client_id |
str
|
The target client ID to refresh token with |
refresh_token |
str
|
The refresh token to use |
realm |
RealmName
|
Keycloak realm the identity lives in. |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing refreshed access and refresh tokens |
Source code in components/authentication/internal/infrastructure/identity_provider.py
inject_authentication_service ¶
inject_authentication_service ¶
Dependency injection decorator for AuthenticationService.
Automatically injects an AuthenticationService instance into functions that have an 'authentication_service' parameter. If the function doesn't have this parameter, the decorator becomes a no-op.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Callable[..., T]
|
The function to decorate |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., T]
|
The original function or a wrapped function with automatic service injection |
Examples:
Basic usage:
>>> @inject_authentication_service
... def create_user_session(user_id: int, authentication_service: AuthenticationService) -> str:
... return authentication_service.create_session_token(user_id)
>>> token = create_user_session(user_id=123) # Service injected automatically
Function without injection (no-op):
>>> @inject_authentication_service
... def simple_function(value: str) -> str:
... return value.upper()
>>> result = simple_function("hello") # Returns "HELLO", no injection needed
Source code in components/authentication/public/inject_authentication_service.py
keycloak ¶
Public Keycloak surface for cross-component consumers.
Narrow re-exports of the symbols actually used outside the authentication
component. Internal helpers (KeycloakAdminWithErrorHandling,
KeycloakBusinessError, KeycloakUser, with_keycloak_error_handling,
get_user_from_access_token) stay private to the implementation.
build_login_url ¶
Build a login URL depending on client ID. It uses either the front end URL or deep link URL as base URL. :param client_id: a str representing the Keycloak client :param email: a str representing the email address for login :return: the login URL
Source code in components/authentication/internal/infrastructure/keycloak.py
get_admin_client_for_realm ¶
Return the Keycloak admin client for realm, cached per-request.
Each (app, realm) pair has a dedicated service account + secret — separate
rotation per realm. Defaults to RealmName.ALAN, our overwhelming use
case; callers targeting another realm (HP creation, alaner lifecycle)
pass it explicitly.
The SDK makes a call to Keycloak when being instantiated, so we cache the
client in Flask g to instantiate only once per request per realm.
Source code in components/authentication/internal/infrastructure/keycloak.py
mfa_auth ¶
DictNotifier ¶
EmailNotifier ¶
Bases: Notifier
Source code in components/authentication/internal/infrastructure/mfa_auth.py
name ¶
notify ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
IosSimulatorJsonNotifier ¶
Bases: Notifier
name ¶
notify ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
MFA ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
get_operation_status ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
get_pending_operations_for_user ¶
Return all pending MFA operations for a user.
Source code in components/authentication/internal/infrastructure/mfa_auth.py
mfa_required ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
register_notifier ¶
send_email ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
update_status ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
validate_or_reject ¶
validate_or_reject(
operation_id,
validation_code=None,
authenticated=False,
authenticated_user=None,
reject=False,
)
Source code in components/authentication/internal/infrastructure/mfa_auth.py
PushNotificationSender
module-attribute
¶
PushNotifier ¶
Bases: Notifier
Source code in components/authentication/internal/infrastructure/mfa_auth.py
name ¶
notify ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
create_mfa_storage ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
password_reset ¶
PasswordResetStorage ¶
Storage backend for password reset data using Redis.
Handles storing and retrieving password reset tokens and associated data.
Source code in components/authentication/public/password_reset.py
delete ¶
Delete a password reset item from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_id
|
str
|
The storage identifier to delete |
required |
Source code in components/authentication/public/password_reset.py
get ¶
Retrieve a password reset item from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_id
|
str
|
The storage identifier |
required |
Returns:
| Type | Description |
|---|---|
PasswordResetStorageItem | None
|
PasswordResetStorageItem | None: The stored reset item if found, None otherwise |
Source code in components/authentication/public/password_reset.py
init_app ¶
Initialize the storage with a Flask app and Redis connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
Flask application instance |
required | |
redis_connection
|
Redis connection instance |
required |
Source code in components/authentication/public/password_reset.py
set ¶
Store a password reset item with expiration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_id
|
str
|
The storage identifier |
required |
item
|
PasswordResetStorageItem
|
The reset item to store |
required |
Source code in components/authentication/public/password_reset.py
PasswordResetStorageItem
dataclass
¶
generate_password_reset_token ¶
Generate a password reset token for the given auth identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth_identity
|
AuthIdentity
|
The authentication identity for which to generate the reset token. |
required |
Returns:
| Type | Description |
|---|---|
str | bytes
|
str | bytes: A signed token containing the email and a nonce for password reset verification. |
Source code in components/authentication/public/password_reset.py
verify_password_reset_token_and_verify_email ¶
Verify a password reset token and mark the email as verified.
This function verifies the token (same as password reset) but only marks the email as verified without resetting the password. This is useful when a user is creating their password for the first time and we want to verify their email at the same time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The password reset token to verify |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DomainAuthIdentity |
AuthIdentity | AuthIdentity
|
The authentication identity whose email was verified |
Raises:
| Type | Description |
|---|---|
BaseErrorCode
|
If the token is expired or invalid |
Source code in components/authentication/public/password_reset.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
verify_token_and_reset_password ¶
Verify a password reset token and update the user's password if valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The password reset token to verify |
required |
prehashed_password_string
|
str
|
The new pre-hashed password to set |
required |
password_string
|
str
|
The new plain-text password to validate strength (optional) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
DomainAuthIdentity |
AuthIdentity | AuthIdentity
|
The authentication identity whose password was reset |
Raises:
| Type | Description |
|---|---|
BaseErrorCode
|
If the token is expired or invalid |
Source code in components/authentication/public/password_reset.py
rules ¶
is_login_credentials_change_allowed ¶
Check if email or password change is allowed for a given profile.