Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `ACCOUNT_EMAIL_CHANGED` webhook event (#13537)
Artur349fe0c194a1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c45075ec39..b51d9babd6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -92,16 +92,17 @@ Shipping methods can be removed by the user after it has been assigned to a chec- Called when metadata is changed for the Shop object via the generic metadata API or the `shopSettingsUpdate` mutation.- Add `CHANNEL_METADATA_UPDATED` webhook - #13448, by @Air-t- Called when metadata is changed for the Channel object via the generic metadata API or the `channelUpdate` mutation.-- Add `ACCOUNT_CONFIRMED` webhook - #13471, by @Air-t- Called when user confirm an account with `confirmAccount` mutation.- Add `ACCOUNT_DELETED` webhook - #13471, by @Air-t- Called after account deletion is confirmed with `accountDelete` mutation.+- Add `ACCOUNT_EMAIL_CHANGED` webhook - #13537, by @Air-t+ - Called when `confirmEmailChange` mutation is triggered.### Other changes- Add possibility to log without confirming email - #13059 by @kadewu- New mutation `sendConfirmationEmail` to send an email with confirmation link- - New environment variable `CONFIRMATION_EMAIL_LOCK_TIME` to control lock time beetwen new email confirmations+ - New environment variable `CONFIRMATION_EMAIL_LOCK_TIME` to control lock time between new email confirmations- Type `User` gets new field `is_confirmed`- `CustomerInput` gets new field `is_confirmed`- Use public key thumbprint as KID in JWKS.json #13442 by @cmiaczdiff --git a/saleor/graphql/account/mutations/account/confirm_email_change.py b/saleor/graphql/account/mutations/account/confirm_email_change.pyindex ebea27c818..f7a613efcd 100644--- a/saleor/graphql/account/mutations/account/confirm_email_change.py+++ b/saleor/graphql/account/mutations/account/confirm_email_change.py@@ -50,6 +50,10 @@ class ConfirmEmailChange(BaseMutation):type=WebhookEventAsyncType.NOTIFY_USER,description="A notification that account email change was confirmed.",),+ WebhookEventInfo(+ type=WebhookEventAsyncType.ACCOUNT_EMAIL_CHANGED,+ description="An account email was changed.",+ ),]@classmethod@@ -91,14 +95,19 @@ class ConfirmEmailChange(BaseMutation):user.email = new_emailuser.search_document = search.prepare_user_search_document_value(user)user.save(update_fields=["email", "search_document", "updated_at"])-channel_slug = clean_channel(channel, error_class=AccountErrorCode).slug- assign_user_gift_cards(user)- match_orders_with_new_user(user)+ cls.post_save_action(info, user, channel_slug, old_email)++ return ConfirmEmailChange(user=user)++ @classmethod+ def post_save_action(cls, info: ResolveInfo, instance, channel_slug, old_email):+ assign_user_gift_cards(instance)+ match_orders_with_new_user(instance)manager = get_plugin_manager_promise(info.context).get()notifications.send_user_change_email_notification(- old_email, user, manager, channel_slug=channel_slug+ old_email, instance, manager, channel_slug=channel_slug)- cls.call_event(manager.customer_updated, user)- return ConfirmEmailChange(user=user)+ cls.call_event(manager.customer_updated, instance)+ cls.call_event(manager.account_email_changed, instance)diff --git a/saleor/graphql/account/tests/mutations/account/test_account_delete.py b/saleor/graphql/account/tests/mutations/account/test_account_delete.pyindex f91744c957..9d591bb6f9 100644--- a/saleor/graphql/account/tests/mutations/account/test_account_delete.py+++ b/saleor/graphql/account/tests/mutations/account/test_account_delete.py@@ -142,3 +142,30 @@ def test_account_delete_other_customer_token(user_api_client):assert data["errors"][0]["message"] == "Invalid or expired token."assert User.objects.filter(pk=user.id).exists()assert User.objects.filter(pk=other_user.id).exists()+++@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+@freeze_time("2018-05-31 12:00:01")+def test_account_delete_webhook_event_triggered(+ mocked_trigger_webhooks_async,+ settings,+ user_api_client,+ subscription_account_deleted_webhook,+):+ # given+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ user = user_api_client.user+ user.last_login = timezone.now()+ user.save(update_fields=["last_login"])++ token = account_delete_token_generator.make_token(user)+ variables = {"token": token}++ # when+ user_api_client.post_graphql(ACCOUNT_DELETE_MUTATION, variables)++ # then+ assert not User.objects.filter(pk=user.id).exists()++ mocked_trigger_webhooks_async.assert_called()diff --git a/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py b/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.pyindex 07786b2126..01ae190c95 100644--- a/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py+++ b/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py@@ -26,7 +26,9 @@ mutation emailUpdate($token: String!, $channel: String) {@patch("saleor.graphql.account.mutations.account.confirm_email_change.assign_user_gift_cards")+@patch("saleor.plugins.manager.PluginsManager.account_email_changed")def test_email_update(+ mocked_account_email_changed,assign_gift_cards_mock,assign_orders_mock,user_api_client,@@ -43,7 +45,6 @@ def test_email_update(token = create_token(payload, timedelta(hours=1))variables = {"token": token, "channel": channel_PLN.slug}-response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)content = get_graphql_content(response)data = content["data"]["confirmEmailChange"]@@ -52,6 +53,7 @@ def test_email_update(assert new_email in user.search_documentassign_gift_cards_mock.assert_called_once_with(customer_user)assign_orders_mock.assert_called_once_with(customer_user)+ mocked_account_email_changed.assert_called_once_with(user)def test_email_update_to_existing_email(user_api_client, customer_user, staff_user):@@ -74,3 +76,36 @@ def test_email_update_to_existing_email(user_api_client, customer_user, staff_us"field": "newEmail",}]+++@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_account_email_changed_webhook_event_triggered(+ mocked_trigger_webhooks_async,+ settings,+ customer_user,+ user_api_client,+ subscription_account_email_changed_webhook,+ channel_PLN,+):+ # given+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ new_email = "[email protected]"+ payload = {+ "old_email": customer_user.email,+ "new_email": new_email,+ "user_pk": customer_user.pk,+ }+ user = user_api_client.user++ token = create_token(payload, timedelta(hours=1))+ variables = {"token": token, "channel": channel_PLN.slug}++ # when+ user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)++ # then+ user.refresh_from_db()+ assert new_email in user.search_document++ mocked_trigger_webhooks_async.assert_called()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 01cb1fb6bb..f38a1ff90a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1722,9 +1722,12 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""An account confirmation is requested."""ACCOUNT_CONFIRMATION_REQUESTED- """Account email change is requested."""+ """An account email change is requested."""ACCOUNT_CHANGE_EMAIL_REQUESTED+ """An account email was changed"""+ ACCOUNT_EMAIL_CHANGED+"""An account is confirmed."""ACCOUNT_CONFIRMED@@ -2375,9 +2378,12 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""An account confirmation is requested."""ACCOUNT_CONFIRMATION_REQUESTED- """Account email change is requested."""+ """An account email change is requested."""ACCOUNT_CHANGE_EMAIL_REQUESTED+ """An account email was changed"""+ ACCOUNT_EMAIL_CHANGED+"""An account is confirmed."""ACCOUNT_CONFIRMED@@ -3386,6 +3392,7 @@ scalar JSONStringenum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {ACCOUNT_CONFIRMATION_REQUESTEDACCOUNT_CHANGE_EMAIL_REQUESTED+ ACCOUNT_EMAIL_CHANGEDACCOUNT_CONFIRMEDACCOUNT_DELETE_REQUESTEDACCOUNT_DELETED@@ -18005,6 +18012,7 @@ type Mutation {Triggers the following webhook events:- CUSTOMER_UPDATED (async): A customer account was updated.- NOTIFY_USER (async): A notification that account email change was confirmed.+ - ACCOUNT_EMAIL_CHANGED (async): An account email was changed."""confirmEmailChange("""@@ -18014,7 +18022,7 @@ type Mutation {"""A one-time token required to change the email."""token: String!- ): ConfirmEmailChange @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_UPDATED, NOTIFY_USER], syncEvents: [])+ ): ConfirmEmailChange @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_UPDATED, NOTIFY_USER, ACCOUNT_EMAIL_CHANGED], syncEvents: [])"""Create a new address for the customer.@@ -28210,8 +28218,9 @@ Requires one of the following permissions: AUTHENTICATED_USER.Triggers the following webhook events:- CUSTOMER_UPDATED (async): A customer account was updated.- NOTIFY_USER (async): A notification that account email change was confirmed.+- ACCOUNT_EMAIL_CHANGED (async): An account email was changed."""-type ConfirmEmailChange @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_UPDATED, NOTIFY_USER], syncEvents: []) {+type ConfirmEmailChange @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_UPDATED, NOTIFY_USER, ACCOUNT_EMAIL_CHANGED], syncEvents: []) {"""A user instance with a new email."""user: UseraccountErrors: [AccountError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")@@ -29181,6 +29190,43 @@ type AccountChangeEmailRequested implements Event @doc(category: "Users") {newEmail: String}+"""+Event sent when account email is changed.++Added in Saleor 3.15.+"""+type AccountEmailChanged implements Event {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The URL to redirect the user after he accepts the request."""+ redirectUrl: String++ """The user the event relates to."""+ user: User++ """The channel data."""+ channel: Channel++ """The token required to confirm request."""+ token: String++ """Shop data."""+ shop: Shop++ """The new email address."""+ newEmail: String+}+"""Event sent when account is confirmed.diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex 4a06b2ccc2..dd5cf43a5f 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -38,8 +38,9 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: ("An account confirmation is requested."),+ WebhookEventAsyncType.ACCOUNT_EMAIL_CHANGED: "An account email was changed",WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED: (- "Account email change is requested."+ "An account email change is requested."),WebhookEventAsyncType.ACCOUNT_CONFIRMED: "An account is confirmed.",WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED: "An account delete is requested.",diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 7ef0d1878c..59de7dcbf2 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -214,6 +214,18 @@ class AccountChangeEmailRequested(SubscriptionObjectType, AccountOperationBase):return data["new_email"]+class AccountEmailChanged(SubscriptionObjectType, AccountOperationBase):+ new_email = graphene.String(+ description="The new email address.",+ )++ class Meta:+ root_type = None+ enable_dry_run = False+ interfaces = (Event,)+ description = "Event sent when account email is changed." + ADDED_IN_315++class AccountDeleteRequested(SubscriptionObjectType, AccountOperationBase):class Meta:root_type = "User"@@ -2149,6 +2161,7 @@ class ThumbnailCreated(SubscriptionObjectType):WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: AccountConfirmationRequested,WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED: AccountChangeEmailRequested,+ WebhookEventAsyncType.ACCOUNT_EMAIL_CHANGED: AccountEmailChanged,WebhookEventAsyncType.ACCOUNT_CONFIRMED: AccountConfirmed,WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED: AccountDeleteRequested,WebhookEventAsyncType.ACCOUNT_DELETED: AccountDeleted,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 3ffa8bb731..b8bc67df34 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -177,6 +177,12 @@ class BasePlugin:# delete is confirmed.account_deleted: Callable[["User", None], None]+ # Trigger when account email is changed.+ #+ # Overwrite this method if you need to trigger specific logic after an account+ # email is changed.+ account_email_changed: Callable[["User", None], None]+# Trigger when account delete is requested.## Overwrite this method if you need to trigger specific logic after an accountdiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex ab14c7e6b2..d77570d4e7 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1088,6 +1088,17 @@ class PluginsManager(PaymentInterface):new_email=new_email,)+ def account_email_changed(+ self,+ user: "User",+ ):+ default_value = None+ return self.__run_method_on_plugins(+ "account_email_changed",+ default_value,+ user,+ )+def account_delete_requested(self, user: "User", channel_slug: str, token: str, redirect_url: str):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex c8704f72d9..9446424f2e 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -239,6 +239,18 @@ class WebhookPlugin(BasePlugin):new_email,)+ def account_email_changed(+ self,+ user: "User",+ previous_value: None,+ ) -> None:+ if not self.active:+ return previous_value+ self._trigger_account_event(+ WebhookEventAsyncType.ACCOUNT_EMAIL_CHANGED,+ user,+ )+def account_delete_requested(self,user: "User",diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.pyindex c8af6519e2..6ee8864dee 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py@@ -44,6 +44,14 @@ def subscription_account_change_email_requested_webhook(subscription_webhook):)+def subscription_account_email_changed_webhook(subscription_webhook):+ return subscription_webhook(+ queries.ACCOUNT_EMAIL_CHANGED,+ WebhookEventAsyncType.ACCOUNT_EMAIL_CHANGED,+ )++@pytest.fixturedef subscription_account_delete_requested_webhook(subscription_webhook):return subscription_webhook(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex 2a585b9ff2..21caae97ea 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -72,6 +72,22 @@ ACCOUNT_CHANGE_EMAIL_REQUESTED = ()+ACCOUNT_EMAIL_CHANGED = (+ fragments.CUSTOMER_DETAILS+ + """+ subscription{+ event{+ ...on AccountEmailChanged{+ user{+ ...CustomerDetails+ }+ }+ }+ }+"""+)++ACCOUNT_DELETE_REQUESTED = (fragments.CUSTOMER_DETAILS+ """diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex 302788551f..b7ce898690 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -159,6 +159,25 @@ def test_account_change_email_requested(assert deliveries[0].webhook == webhooks[0]+def test_account_email_changed(+ customer_user, subscription_account_email_changed_webhook+):+ # given+ webhooks = [subscription_account_email_changed_webhook]+ event_type = WebhookEventAsyncType.ACCOUNT_EMAIL_CHANGED++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, {"user": customer_user}, webhooks+ )++ # then+ expected_payload = generate_account_events_payload(customer_user)+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]++def test_account_delete_requested(customer_user, channel_USD, subscription_account_delete_requested_webhook):diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 4f8bc199d5..ac09618746 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -23,6 +23,7 @@ class WebhookEventAsyncType:ANY = "any_events"ACCOUNT_CONFIRMATION_REQUESTED = "account_confirmation_requested"+ ACCOUNT_EMAIL_CHANGED = "account_email_changed"ACCOUNT_CHANGE_EMAIL_REQUESTED = "account_change_email_requested"ACCOUNT_CONFIRMED = "account_confirmed"ACCOUNT_DELETE_REQUESTED = "account_delete_requested"@@ -190,6 +191,10 @@ class WebhookEventAsyncType:"name": "Account change email requested","permission": AccountPermissions.MANAGE_USERS,},+ ACCOUNT_EMAIL_CHANGED: {+ "name": "Account email changed",+ "permission": AccountPermissions.MANAGE_USERS,+ },ACCOUNT_CONFIRMED: {"name": "Account confirmed","permission": AccountPermissions.MANAGE_USERS,