Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add ACCOUNT_CONFIRMATION_REQUESTED event (#13162)

SzymJf129990d33d8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ac094f2276..cb86f0b491 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,8 @@ All notable, unreleased changes to this project will be documented in this file.
- Add missing descriptions to checkout module. - #13167 by @fowczarek
- Add missing descriptions to attribute module. - #13165 by @fowczarek
- Add missing descriptions to csv module. - #13184 by @fowczarek
+- Add missing descriptions to Account module. - #13155 by @fowczarek
+- Add `ACCOUNT_CONFIRMATION_REQUESTED` async event - #13162 by @SzymJ
# 3.14.0
diff --git a/saleor/account/notifications.py b/saleor/account/notifications.py
index 721b3bf14d..24db8b054d 100644
--- a/saleor/account/notifications.py
+++ b/saleor/account/notifications.py
@@ -63,9 +63,11 @@ def send_password_reset_notification(
manager.notify(event, payload=payload, channel_slug=channel_slug)
-def send_account_confirmation(user, redirect_url, manager, channel_slug):
+def send_account_confirmation(user, redirect_url, manager, channel_slug, token=None):
"""Trigger sending an account confirmation notification for the given user."""
- token = default_token_generator.make_token(user)
+
+ if not token:
+ token = default_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
confirm_url = prepare_url(params, redirect_url)
payload = {
diff --git a/saleor/graphql/account/mutations/account/account_register.py b/saleor/graphql/account/mutations/account/account_register.py
index 370f70acb2..9cb060b240 100644
--- a/saleor/graphql/account/mutations/account/account_register.py
+++ b/saleor/graphql/account/mutations/account/account_register.py
@@ -1,13 +1,16 @@
+from urllib.parse import urlencode
+
import graphene
from django.conf import settings
from django.contrib.auth import password_validation
+from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import ValidationError
from .....account import events as account_events
from .....account import models, notifications, search
from .....account.error_codes import AccountErrorCode
from .....core.tracing import traced_atomic_transaction
-from .....core.utils.url import validate_storefront_url
+from .....core.utils.url import prepare_url, validate_storefront_url
from ....channel.utils import clean_channel
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_USERS
@@ -131,18 +134,36 @@ class AccountRegister(ModelMutation):
)
manager = get_plugin_manager_promise(info.context).get()
site = get_site_promise(info.context).get()
+ token = default_token_generator.make_token(user)
+ redirect_url = cleaned_input.get("redirect_url")
with traced_atomic_transaction():
if site.settings.enable_account_confirmation_by_email:
user.is_active = False
user.save()
+
+ # Notifications will be deprecated in the future
notifications.send_account_confirmation(
user,
- cleaned_input["redirect_url"],
+ redirect_url,
manager,
channel_slug=cleaned_input["channel"],
+ token=token,
)
else:
user.save()
+
+ if redirect_url:
+ params = urlencode({"email": user.email, "token": token})
+ redirect_url = prepare_url(params, redirect_url)
+
+ cls.call_event(
+ manager.account_confirmation_requested,
+ user,
+ cleaned_input["channel"],
+ token,
+ redirect_url,
+ )
+
cls.call_event(manager.customer_created, user)
account_events.customer_account_created_event(user=user)
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index df79f3b5a1..525602df71 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -310,7 +310,7 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
# The instance is a new object in db, create an event
if is_creation:
- manager.customer_created(customer=instance)
+ cls.call_event(manager.customer_created, instance)
account_events.customer_account_created_event(user=instance)
else:
manager.customer_updated(instance)
@@ -325,6 +325,7 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
channel_slug = validate_channel(
channel_slug, error_class=AccountErrorCode
).slug
+
send_set_password_notification(
cleaned_input.get("redirect_url"),
instance,
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index 0bbba83ce6..c9292ff362 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -1617,6 +1617,44 @@ def test_customer_register(
assert customer_creation_event.user == new_user
+@override_settings(
+ ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=True, ALLOWED_CLIENT_HOSTS=["localhost"]
+)
+@patch("saleor.account.notifications.default_token_generator.make_token")
+@patch("saleor.plugins.manager.PluginsManager.account_confirmation_requested")
+def test_customer_register_send_account_confirmation_requested_event(
+ account_confirmation_requested_mock,
+ mocked_generator,
+ api_client,
+ channel_USD,
+):
+ # given
+ mocked_generator.return_value = "token"
+
+ email = "[email protected]"
+ redirect_url = "http://localhost:3000"
+ variables = {
+ "email": email,
+ "password": "Password",
+ "redirectUrl": redirect_url,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(ACCOUNT_REGISTER_MUTATION, variables)
+ errors = response.json()["data"]["accountRegister"]["errors"]
+
+ # then
+ assert errors == []
+ created_user = User.objects.get()
+ account_confirmation_requested_mock.assert_called_once_with(
+ created_user,
+ channel_USD.slug,
+ "token",
+ redirect_url + "?email=customer%40example.com&token=token",
+ )
+
+
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_customer_register_disabled_email_confirmation(
mocked_notify, api_client, site_settings
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 1e59f81324..bbdfb4c06c 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1688,6 +1688,9 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""All the events."""
ANY_EVENTS
+ """An account confirmation requested."""
+ ACCOUNT_CONFIRMATION_REQUESTED
+
"""A new address created."""
ADDRESS_CREATED
@@ -2319,6 +2322,9 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
"""All the events."""
ANY_EVENTS
+ """An account confirmation requested."""
+ ACCOUNT_CONFIRMATION_REQUESTED
+
"""A new address created."""
ADDRESS_CREATED
@@ -3317,6 +3323,7 @@ scalar JSONString
"""An enumeration."""
enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
+ ACCOUNT_CONFIRMATION_REQUESTED
ADDRESS_CREATED
ADDRESS_UPDATED
ADDRESS_DELETED
@@ -27427,6 +27434,40 @@ enum VolumeUnitsEnum {
ACRE_FT
}
+"""
+Event sent when account confirmation requested. This event is always sent. enableAccountConfirmationByEmail flag set to True is not required.
+
+Added in Saleor 3.15.
+"""
+type AccountConfirmationRequested 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
+}
+
"""
Event sent when new address is created.
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 62d457aeb9..cea1a18f4e 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -33,6 +33,9 @@ order_updated_event_enum_description = (
WEBHOOK_EVENT_DESCRIPTION = {
+ WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: (
+ "An account confirmation requested."
+ ),
WebhookEventAsyncType.ADDRESS_CREATED: "A new address created.",
WebhookEventAsyncType.ADDRESS_UPDATED: "An address updated.",
WebhookEventAsyncType.ADDRESS_DELETED: "An address deleted.",
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index c066ce68ef..77eeedbb06 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -6,8 +6,10 @@ from rx import Observable
from ... import __version__
from ...account.models import User
from ...attribute.models import AttributeTranslation, AttributeValueTranslation
+from ...channel.models import Channel
from ...core.prices import quantize_price
from ...discount.models import SaleTranslation, VoucherTranslation
+from ...graphql.shop.types import Shop
from ...menu.models import MenuItemTranslation
from ...order.utils import get_all_shipping_methods_for_order
from ...page.models import PageTranslation
@@ -39,6 +41,7 @@ from ..core.descriptions import (
ADDED_IN_312,
ADDED_IN_313,
ADDED_IN_314,
+ ADDED_IN_315,
PREVIEW_FEATURE,
)
from ..core.doc_category import (
@@ -131,6 +134,59 @@ class Event(graphene.Interface):
return info.context.requestor
+class AccountOperationBase(AbstractType):
+ redirect_url = graphene.String(
+ description="The URL to redirect the user after he accepts the request.",
+ required=False,
+ )
+ user = graphene.Field(
+ UserType,
+ description="The user the event relates to.",
+ )
+ channel = graphene.Field(
+ "saleor.graphql.channel.types.Channel",
+ description="The channel data.",
+ )
+ token = graphene.String(description="The token required to confirm request.")
+ shop = graphene.Field(Shop, description="Shop data.")
+
+ @staticmethod
+ def resolve_user(root, _info: ResolveInfo):
+ _, data = root
+ return data["user"]
+
+ @staticmethod
+ def resolve_redirect_url(root, _info: ResolveInfo):
+ _, data = root
+ return data.get("redirect_url")
+
+ @staticmethod
+ def resolve_channel(root, _info: ResolveInfo):
+ _, data = root
+ return Channel.objects.get(slug=data["channel_slug"])
+
+ @staticmethod
+ def resolve_token(root, _info: ResolveInfo):
+ _, data = root
+ return data["token"]
+
+ @staticmethod
+ def resolve_shop(root, _info: ResolveInfo):
+ return Shop()
+
+
+class AccountConfirmationRequested(SubscriptionObjectType, AccountOperationBase):
+ class Meta:
+ root_type = "User"
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when account confirmation requested. This event is always sent."
+ " enableAccountConfirmationByEmail flag set to True is not required."
+ + ADDED_IN_315
+ )
+
+
class AddressBase(AbstractType):
address = graphene.Field(
"saleor.graphql.account.types.Address",
@@ -2028,6 +2084,7 @@ class ThumbnailCreated(SubscriptionObjectType):
WEBHOOK_TYPES_MAP = {
+ WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: AccountConfirmationRequested,
WebhookEventAsyncType.ADDRESS_CREATED: AddressCreated,
WebhookEventAsyncType.ADDRESS_UPDATED: AddressUpdated,
WebhookEventAsyncType.ADDRESS_DELETED: AddressDeleted,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 81838bbb16..0524718f89 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -149,6 +149,14 @@ class BasePlugin:
def __str__(self):
return self.PLUGIN_NAME
+ # Trigger when account confirmation is requested.
+ #
+ # Overwrite this method if you need to trigger specific logic after an account
+ # confirmation is requested.
+ account_confirmation_requested: Callable[
+ ["User", str, str, Optional[str], None], None
+ ]
+
# Trigger when address is created.
#
# Overwrite this method if you need to trigger specific logic after an address is
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 7305bdbb92..8fb4afefa4 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -1061,6 +1061,19 @@ class PluginsManager(PaymentInterface):
"transaction_item_metadata_updated", default_value, transaction_item
)
+ def account_confirmation_requested(
+ self, user: "User", channel_slug: str, token: str, redirect_url: Optional[str]
+ ):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "account_confirmation_requested",
+ default_value,
+ user,
+ channel_slug,
+ token=token,
+ redirect_url=redirect_url,
+ )
+
def address_created(self, address: "Address"):
default_value = None
return self.__run_method_on_plugins("address_created", default_value, address)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 1106bf2b6d..5c39c825e2 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -168,6 +168,39 @@ class WebhookPlugin(BasePlugin):
payload, event_type, webhooks, address, self.requestor
)
+ def account_confirmation_requested(
+ self,
+ user: "User",
+ channel_slug: str,
+ token: str,
+ redirect_url: Optional[str],
+ previous_value: None,
+ ) -> None:
+ if not self.active:
+ return previous_value
+ if webhooks := get_webhooks_for_event(
+ WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED
+ ):
+ payload = self._serialize_payload(
+ {
+ "id": graphene.Node.to_global_id("User", user.id),
+ "token": token,
+ "redirect_url": redirect_url,
+ }
+ )
+ trigger_webhooks_async(
+ payload,
+ WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED,
+ webhooks,
+ {
+ "user": user,
+ "channel_slug": channel_slug,
+ "token": token,
+ "redirect_url": redirect_url,
+ },
+ self.requestor,
+ )
+
def address_created(self, address: "Address", previous_value: None) -> None:
if not self.active:
return previous_value
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index a38c919a9c..a0694af9a2 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -20,6 +20,14 @@ def subscription_webhook(webhook_app):
return fun
+def subscription_account_confirmation_requested_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.ACCOUNT_CONFIRMATION_REQUESTED,
+ WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED,
+ )
+
+
@pytest.fixture
def subscription_address_created_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.py
index 745182f624..66ab6a9d61 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -1,5 +1,33 @@
from .....graphql.tests.queries import fragments
+ACCOUNT_CONFIRMATION_REQUESTED = (
+ fragments.CUSTOMER_DETAILS
+ + """
+ subscription{
+ event{
+ ...on AccountConfirmationRequested{
+ user{
+ ...CustomerDetails
+ }
+ token
+ redirectUrl
+ channel{
+ slug
+ id
+ }
+ shop{
+ domain{
+ host
+ url
+ }
+ }
+ }
+ }
+ }
+"""
+)
+
+
ADDRESS_CREATED = (
fragments.ADDRESS_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.py
index 27fbc40ae5..927680c01e 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
@@ -78,6 +78,48 @@ def test_subscription_query_with_meta(
assert deliveries[0].webhook == webhooks[0]
+def test_account_confirmation_requested(
+ customer_user, channel_USD, subscription_account_confirmation_requested_webhook
+):
+ # given
+ webhooks = [subscription_account_confirmation_requested_webhook]
+ event_type = WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(
+ event_type,
+ {
+ "user": customer_user,
+ "channel_slug": channel_USD.slug,
+ "token": "token",
+ "redirect_url": "http://www.example.com?token=token",
+ },
+ webhooks,
+ )
+
+ # then
+ expected_payload = json.dumps(
+ {
+ **generate_customer_payload(customer_user),
+ **{
+ "token": "token",
+ "redirectUrl": "http://www.example.com?token=token",
+ "channel": {
+ "slug": channel_USD.slug,
+ "id": graphene.Node.to_global_id("Channel", channel_USD.id),
+ },
+ "shop": {
+ "domain": {"host": "mirumee.com", "url": "http://mirumee.com/"}
+ },
+ },
+ }
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_address_created(address, subscription_address_created_webhook):
# given
webhooks = [subscription_address_created_webhook]
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 6b0fc602e2..0cb34079a0 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -19,6 +19,8 @@ from ..permission.enums import (
class WebhookEventAsyncType:
ANY = "any_events"
+ ACCOUNT_CONFIRMATION_REQUESTED = "account_confirmation_requested"
+
ADDRESS_CREATED = "address_created"
ADDRESS_UPDATED = "address_updated"
ADDRESS_DELETED = "address_deleted"
@@ -172,6 +174,7 @@ class WebhookEventAsyncType:
DISPLAY_LABELS = {
ANY: "Any events",
+ ACCOUNT_CONFIRMATION_REQUESTED: "Account confirmation requested",
ADDRESS_CREATED: "Address created",
ADDRESS_UPDATED: "Address updated",
ADDRESS_DELETED: "Address deleted",
@@ -294,6 +297,10 @@ class WebhookEventAsyncType:
CHOICES = [
(ANY, DISPLAY_LABELS[ANY]),
+ (
+ ACCOUNT_CONFIRMATION_REQUESTED,
+ DISPLAY_LABELS[ACCOUNT_CONFIRMATION_REQUESTED],
+ ),
(ADDRESS_CREATED, DISPLAY_LABELS[ADDRESS_CREATED]),
(ADDRESS_UPDATED, DISPLAY_LABELS[ADDRESS_UPDATED]),
(ADDRESS_DELETED, DISPLAY_LABELS[ADDRESS_DELETED]),
@@ -426,6 +433,7 @@ class WebhookEventAsyncType:
ALL = [event[0] for event in CHOICES]
PERMISSIONS = {
+ ACCOUNT_CONFIRMATION_REQUESTED: AccountPermissions.MANAGE_USERS,
ADDRESS_CREATED: AccountPermissions.MANAGE_USERS,
ADDRESS_UPDATED: AccountPermissions.MANAGE_USERS,
ADDRESS_DELETED: AccountPermissions.MANAGE_USERS,