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 ¶
flask_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
¶
ChangeIdentityFirstNameCommand
dataclass
¶
ChangeIdentityLanguageCommand
dataclass
¶
ChangeIdentityLastNameCommand
dataclass
¶
ChangeIdentityMfaStatusCommand
dataclass
¶
ClearIdentityEmail
dataclass
¶
DeleteIdentityCommand
dataclass
¶
DeleteIdentityCredentialsCommand
dataclass
¶
IdentityCreationCommand
dataclass
¶
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
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
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=False,
email_sent=False,
email_changed=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.
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 ¶
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 |
|---|---|
UUID | 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 ¶
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
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 ¶
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
infrastructure ¶
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,
)
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,
)
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 |
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 |
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 |
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 |
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,
)
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 |
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 |
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 |
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 |
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
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
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
mfa_required ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
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 | |
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 ¶
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
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 ¶
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
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
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
|
UUID
|
UUID of the user to notify |
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
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 |
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 |
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 |
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 |
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 |
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
|
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 |
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 |
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 |
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
)
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
|
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
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 | |
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 |
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 |
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 |
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"
... )
>>> 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 |
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")
>>> 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 |
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 |
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 |
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 |
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"
... )
>>> # Later, when access token expires
>>> refreshed_tokens = authentication_service.refresh_exchanged_token(
... refresh_token=initial_tokens['refresh_token'],
... target_client_id="mobile-app"
... )
>>> 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 |
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 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
|
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,
mfa_required=None
)
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 |
required |
mfa_required
|
bool | None
|
MFA requirement setting (None = no change) |
None
|
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
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.
register_mfa_notifier ¶
route ¶
Route decorator that logs the API call.
Source code in components/authentication/public/blueprints/blueprint.py
create_auth_blueprint ¶
Create an auth blueprint.
Source code in components/authentication/public/blueprints/blueprint.py
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 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 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 | |
blueprint_with_password_reset_request ¶
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
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
feature_flags ¶
use_authentication_table_for_keycloak_id ¶
Determine whether to use the authentication table or the user model to get a person's keycloak_id.
Source code in components/authentication/public/feature_flags.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,
)
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,
)
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 |
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 |
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 |
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 |
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,
)
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 |
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 |
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 |
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 |
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
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
mfa_required ¶
Source code in components/authentication/internal/infrastructure/mfa_auth.py
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 | |
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_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 |
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 |