Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add ACCOUNT_CHANGE_EMAIL_REQUESTED event (#13233)
SzymJa937b5b9701a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0931c88c73..bf98b8e39d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -49,7 +49,8 @@ All notable, unreleased changes to this project will be documented in this file.- Add missing descriptions to Account module. - #13155 by @fowczarek- Add `ACCOUNT_CONFIRMATION_REQUESTED` async event - #13162 by @SzymJ- Add `ACCOUNT_DELETE_REQUESTED` async event - #13170 by @SzymJ--+- Add `ACCOUNT_CHANGE_EMAIL_REQUESTED` async event - #13233 by @SzymJ+# 3.14.0### Breaking changesdiff --git a/saleor/graphql/account/mutations/account/request_email_change.py b/saleor/graphql/account/mutations/account/request_email_change.pyindex 905a5f8095..633a60c152 100644--- a/saleor/graphql/account/mutations/account/request_email_change.py+++ b/saleor/graphql/account/mutations/account/request_email_change.py@@ -1,4 +1,5 @@from typing import cast+from urllib.parse import urlencodeimport graphenefrom django.conf import settings@@ -7,7 +8,7 @@ from django.core.exceptions import ValidationErrorfrom .....account import models, notificationsfrom .....account.error_codes import AccountErrorCodefrom .....core.jwt import create_token-from .....core.utils.url import validate_storefront_url+from .....core.utils.url import prepare_url, validate_storefront_urlfrom .....permission.auth_filters import AuthorizationFiltersfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....channel.utils import clean_channel@@ -102,6 +103,9 @@ class RequestEmailChange(BaseMutation):}token = create_token(token_payload, settings.JWT_TTL_REQUEST_EMAIL_CHANGE)manager = get_plugin_manager_promise(info.context).get()+ params = urlencode({"token": token})++ # Notifications will be deprecated in the futurenotifications.send_request_user_change_email_notification(redirect_url,user,@@ -110,4 +114,14 @@ class RequestEmailChange(BaseMutation):manager,channel_slug=channel_slug,)++ cls.call_event(+ manager.account_change_email_requested,+ user,+ channel_slug,+ token,+ prepare_url(params, redirect_url),+ new_email,+ )+return RequestEmailChange(user=user)diff --git a/saleor/graphql/account/tests/mutations/account/test_account_request_deletion.py b/saleor/graphql/account/tests/mutations/account/test_account_request_deletion.pyindex 430983a459..986e663f1d 100644--- a/saleor/graphql/account/tests/mutations/account/test_account_request_deletion.py+++ b/saleor/graphql/account/tests/mutations/account/test_account_request_deletion.py@@ -58,6 +58,36 @@ def test_account_request_deletion()+@patch("saleor.account.notifications.account_delete_token_generator.make_token")+@patch("saleor.plugins.manager.PluginsManager.account_delete_requested")+def test_account_request_deletion_send_account_delete_requested_event(+ account_delete_requested_mock,+ mocked_token,+ user_api_client,+ channel_PLN,+ site_settings,+):+ mocked_token.return_value = "token"+ user = user_api_client.user+ redirect_url = "https://www.example.com"+ variables = {"redirectUrl": redirect_url, "channel": channel_PLN.slug}+ response = user_api_client.post_graphql(+ ACCOUNT_REQUEST_DELETION_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["accountRequestDeletion"]+ assert not data["errors"]+ params = urlencode({"token": "token"})+ delete_url = prepare_url(params, redirect_url)++ account_delete_requested_mock.assert_called_once_with(+ user,+ channel_PLN.slug,+ "token",+ delete_url,+ )++@freeze_time("2018-05-31 12:00:01")@patch("saleor.plugins.manager.PluginsManager.notify")def test_account_request_deletion_token_validation(diff --git a/saleor/graphql/account/tests/mutations/account/test_request_email_change.py b/saleor/graphql/account/tests/mutations/account/test_request_email_change.pyindex 4cd293839a..2ddafdb7c6 100644--- a/saleor/graphql/account/tests/mutations/account/test_request_email_change.py+++ b/saleor/graphql/account/tests/mutations/account/test_request_email_change.py@@ -158,3 +158,35 @@ def test_request_email_change_with_invalid_password(user_api_client, customer_usassert not data["user"]assert data["errors"][0]["code"] == AccountErrorCode.INVALID_CREDENTIALS.nameassert data["errors"][0]["field"] == "password"+++@patch("saleor.graphql.account.mutations.account.request_email_change.create_token")+@patch("saleor.plugins.manager.PluginsManager.account_change_email_requested")+def test_request_email_change_send_event(+ account_change_email_requested_mock,+ create_token_mock,+ user_api_client,+ customer_user,+ channel_PLN,+):+ create_token_mock.return_value = "token"+ redirect_url = "http://www.example.com"+ new_email = "[email protected]"+ variables = {+ "password": "password",+ "new_email": new_email,+ "redirect_url": redirect_url,+ "channel": channel_PLN.slug,+ }++ response = user_api_client.post_graphql(REQUEST_EMAIL_CHANGE_QUERY, variables)+ content = get_graphql_content(response)+ data = content["data"]["requestEmailChange"]+ assert data["user"]["email"] == customer_user.email++ params = urlencode({"token": "token"})+ change_email_url = prepare_url(params, redirect_url)++ account_change_email_requested_mock.assert_called_once_with(+ customer_user, channel_PLN.slug, "token", change_email_url, new_email+ )diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex f10fae0b13..62ef715d94 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1700,6 +1700,9 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""An account confirmation is requested."""ACCOUNT_CONFIRMATION_REQUESTED+ """Account email change is requested."""+ ACCOUNT_CHANGE_EMAIL_REQUESTED+"""An account delete is requested."""ACCOUNT_DELETE_REQUESTED@@ -2337,6 +2340,9 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""An account confirmation is requested."""ACCOUNT_CONFIRMATION_REQUESTED+ """Account email change is requested."""+ ACCOUNT_CHANGE_EMAIL_REQUESTED+"""An account delete is requested."""ACCOUNT_DELETE_REQUESTED@@ -3339,6 +3345,7 @@ scalar JSONString"""An enumeration."""enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {ACCOUNT_CONFIRMATION_REQUESTED+ ACCOUNT_CHANGE_EMAIL_REQUESTEDACCOUNT_DELETE_REQUESTEDADDRESS_CREATEDADDRESS_UPDATED@@ -28373,6 +28380,43 @@ type AccountConfirmationRequested implements Event @doc(category: "Users") {shop: Shop}+"""+Event sent when account change email is requested.++Added in Saleor 3.15.+"""+type AccountChangeEmailRequested implements Event @doc(category: "Users") {+ """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 the user wants to change to."""+ newEmail: String+}+"""Event sent when account delete is requested.diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex 45191b6a4c..3b38baa5b9 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -36,6 +36,9 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: ("An account confirmation is requested."),+ WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED: (+ "Account email change is requested."+ ),WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED: "An account delete is requested.",WebhookEventAsyncType.ADDRESS_CREATED: "A new address created.",WebhookEventAsyncType.ADDRESS_UPDATED: "An address updated.",diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 545c7811b6..dbc4ad29e4 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -187,6 +187,25 @@ class AccountConfirmationRequested(SubscriptionObjectType, AccountOperationBase))+class AccountChangeEmailRequested(SubscriptionObjectType, AccountOperationBase):+ new_email = graphene.String(+ description="The new email address the user wants to change to.",+ )++ class Meta:+ root_type = "User"+ enable_dry_run = False+ interfaces = (Event,)+ description = (+ "Event sent when account change email is requested." + ADDED_IN_315+ )++ @staticmethod+ def resolve_new_email(root, _info: ResolveInfo):+ _, data = root+ return data["new_email"]++class AccountDeleteRequested(SubscriptionObjectType, AccountOperationBase):class Meta:root_type = "User"@@ -2106,6 +2125,7 @@ class ThumbnailCreated(SubscriptionObjectType):WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: AccountConfirmationRequested,+ WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED: AccountChangeEmailRequested,WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED: AccountDeleteRequested,WebhookEventAsyncType.ADDRESS_CREATED: AddressCreated,WebhookEventAsyncType.ADDRESS_UPDATED: AddressUpdated,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 92f20316ff..cd7901c974 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -157,6 +157,12 @@ class BasePlugin:["User", str, str, Optional[str], None], None]+ # Trigger when account change email is requested.+ #+ # Overwrite this method if you need to trigger specific logic after an account+ # change email is requested.+ account_change_email_requested: Callable[["User", str, str, str, str, 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 2925aeb615..e10e5a3eea 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1074,6 +1074,25 @@ class PluginsManager(PaymentInterface):redirect_url=redirect_url,)+ def account_change_email_requested(+ self,+ user: "User",+ channel_slug: str,+ token: str,+ redirect_url: str,+ new_email: str,+ ):+ default_value = None+ return self.__run_method_on_plugins(+ "account_change_email_requested",+ default_value,+ user,+ channel_slug,+ token=token,+ redirect_url=redirect_url,+ new_email=new_email,+ )+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 44a0577e2e..dc27a34c6e 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -151,26 +151,30 @@ class WebhookPlugin(BasePlugin):)def _trigger_account_event(- self, event_type, user, channel_slug, token, redirect_url+ self, event_type, user, channel_slug, token, redirect_url, new_email=None):if webhooks := get_webhooks_for_event(event_type):- payload = self._serialize_payload(- {- "id": graphene.Node.to_global_id("User", user.id),- "token": token,- "redirect_url": redirect_url,- }- )+ raw_payload = {+ "id": graphene.Node.to_global_id("User", user.id),+ "token": token,+ "redirect_url": redirect_url,+ }+ data = {+ "user": user,+ "channel_slug": channel_slug,+ "token": token,+ "redirect_url": redirect_url,+ }++ if new_email:+ raw_payload["new_email"] = new_email+ data["new_email"] = new_email+trigger_webhooks_async(- payload,+ self._serialize_payload(raw_payload),event_type,webhooks,- {- "user": user,- "channel_slug": channel_slug,- "token": token,- "redirect_url": redirect_url,- },+ data,self.requestor,)@@ -192,6 +196,26 @@ class WebhookPlugin(BasePlugin):redirect_url,)+ def account_change_email_requested(+ self,+ user: "User",+ channel_slug: str,+ token: str,+ redirect_url: str,+ new_email: str,+ previous_value: None,+ ) -> None:+ if not self.active:+ return previous_value+ self._trigger_account_event(+ WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED,+ user,+ channel_slug,+ token,+ redirect_url,+ new_email,+ )+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 e8ba605fef..4e34802654 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py@@ -28,6 +28,14 @@ def subscription_account_confirmation_requested_webhook(subscription_webhook):)+def subscription_account_change_email_requested_webhook(subscription_webhook):+ return subscription_webhook(+ queries.ACCOUNT_CHANGE_EMAIL_REQUESTED,+ WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED,+ )++@pytest.fixturedef subscription_account_delete_requested_webhook(subscription_webhook):return subscription_webhook(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.pyindex 2abec6a245..3b44b08ce2 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py@@ -8,23 +8,24 @@ from .....graphql.attribute.enums import AttributeInputTypeEnum, AttributeTypeEnfrom .....product.models import Product-def generate_account_events_payload(customer_user, channel):- return json.dumps(- {- **generate_customer_payload(customer_user),- **{- "token": "token",- "redirectUrl": "http://www.mirumee.com?token=token",- "channel": {- "slug": channel.slug,- "id": graphene.Node.to_global_id("Channel", channel.id),- },- "shop": {- "domain": {"host": "mirumee.com", "url": "http://mirumee.com/"}- },+def generate_account_events_payload(customer_user, channel, new_email=None):+ payload = {+ **generate_customer_payload(customer_user),+ **{+ "token": "token",+ "redirectUrl": "http://www.mirumee.com?token=token",+ "channel": {+ "slug": channel.slug,+ "id": graphene.Node.to_global_id("Channel", channel.id),},- }- )+ "shop": {"domain": {"host": "mirumee.com", "url": "http://mirumee.com/"}},+ },+ }++ if new_email:+ payload["newEmail"] = new_email++ return json.dumps(payload)def generate_app_payload(app, app_global_id):diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex e0234d9262..1d3aa319af 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -28,6 +28,35 @@ ACCOUNT_CONFIRMATION_REQUESTED = ()+ACCOUNT_CHANGE_EMAIL_REQUESTED = (+ fragments.CUSTOMER_DETAILS+ + """+ subscription{+ event{+ ...on AccountChangeEmailRequested{+ user{+ ...CustomerDetails+ }+ token+ redirectUrl+ channel{+ slug+ id+ }+ shop{+ domain{+ host+ url+ }+ }+ newEmail+ }+ }+ }+"""+)++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 1fe393a8c0..b764204773 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@@ -106,6 +106,36 @@ def test_account_confirmation_requested(assert deliveries[0].webhook == webhooks[0]+def test_account_change_email_requested(+ customer_user, channel_USD, subscription_account_change_email_requested_webhook+):+ # given+ webhooks = [subscription_account_change_email_requested_webhook]+ event_type = WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED+ new_email = "[email protected]"++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type,+ {+ "user": customer_user,+ "channel_slug": channel_USD.slug,+ "token": "token",+ "new_email": new_email,+ "redirect_url": "http://www.mirumee.com?token=token",+ },+ webhooks,+ )++ # then+ expected_payload = generate_account_events_payload(+ customer_user, channel_USD, new_email=new_email+ )+ 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 10837b4890..b959cb4ba0 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -20,6 +20,7 @@ class WebhookEventAsyncType:ANY = "any_events"ACCOUNT_CONFIRMATION_REQUESTED = "account_confirmation_requested"+ ACCOUNT_CHANGE_EMAIL_REQUESTED = "account_change_email_requested"ACCOUNT_DELETE_REQUESTED = "account_delete_requested"ADDRESS_CREATED = "address_created"@@ -176,6 +177,7 @@ class WebhookEventAsyncType:DISPLAY_LABELS = {ANY: "Any events",ACCOUNT_CONFIRMATION_REQUESTED: "Account confirmation requested",+ ACCOUNT_CHANGE_EMAIL_REQUESTED: "Account change email requested",ACCOUNT_DELETE_REQUESTED: "Account delete requested",ADDRESS_CREATED: "Address created",ADDRESS_UPDATED: "Address updated",@@ -303,6 +305,10 @@ class WebhookEventAsyncType:ACCOUNT_CONFIRMATION_REQUESTED,DISPLAY_LABELS[ACCOUNT_CONFIRMATION_REQUESTED],),+ (+ ACCOUNT_CHANGE_EMAIL_REQUESTED,+ DISPLAY_LABELS[ACCOUNT_CHANGE_EMAIL_REQUESTED],+ ),(ACCOUNT_DELETE_REQUESTED, DISPLAY_LABELS[ACCOUNT_DELETE_REQUESTED]),(ADDRESS_CREATED, DISPLAY_LABELS[ADDRESS_CREATED]),(ADDRESS_UPDATED, DISPLAY_LABELS[ADDRESS_UPDATED]),@@ -437,6 +443,7 @@ class WebhookEventAsyncType:PERMISSIONS = {ACCOUNT_CONFIRMATION_REQUESTED: AccountPermissions.MANAGE_USERS,+ ACCOUNT_CHANGE_EMAIL_REQUESTED: AccountPermissions.MANAGE_USERS,ACCOUNT_DELETE_REQUESTED: AccountPermissions.MANAGE_USERS,ADDRESS_CREATED: AccountPermissions.MANAGE_USERS,ADDRESS_UPDATED: AccountPermissions.MANAGE_USERS,