Skip to content

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

Migrate account emails to plugin (#6296)

Maciej Korycinskia59a8449d383
diff --git a/saleor/account/emails.py b/saleor/account/emails.py
deleted file mode 100644
index 9bfd978e65..0000000000
--- a/saleor/account/emails.py
+++ /dev/null
@@ -1,160 +0,0 @@
-from urllib.parse import urlencode
-
-from django.contrib.auth.tokens import default_token_generator
-from templated_email import send_templated_mail
-
-from ..account import events as account_events
-from ..celeryconf import app
-from ..core.emails import get_email_context
-from ..core.utils.url import prepare_url
-
-REQUEST_EMAIL_CHANGE_TEMPLATE = "account/request_email_change"
-EMAIL_CHANGED_NOTIFICATION_TEMPLATE = "account/email_changed_notification"
-ACCOUNT_DELETE_TEMPLATE = "account/account_delete"
-PASSWORD_RESET_TEMPLATE = "account/password_reset"
-
-
-def send_user_password_reset_email_with_url(redirect_url, user):
- """Trigger sending a password reset email for the given user."""
- token = default_token_generator.make_token(user)
- _send_password_reset_email_with_url.delay(user.email, redirect_url, user.pk, token)
-
-
-def send_account_confirmation_email(user, redirect_url):
- """Trigger sending an account confirmation email for the given user."""
- token = default_token_generator.make_token(user)
- _send_account_confirmation_email.delay(user.email, token, redirect_url)
-
-
-def _send_account_confirmation_email(email, token, redirect_url):
- params = urlencode({"email": email, "token": token})
- confirm_url = prepare_url(params, redirect_url)
- send_kwargs, ctx = get_email_context()
- ctx["confirm_url"] = confirm_url
- send_templated_mail(
- template_name="account/confirm",
- recipient_list=[email],
- context=ctx,
- **send_kwargs,
- )
-
-
-def _send_password_reset_email_with_url(recipient_email, redirect_url, user_id, token):
- params = urlencode({"email": recipient_email, "token": token})
- reset_url = prepare_url(params, redirect_url)
- _send_password_reset_email(recipient_email, reset_url, user_id)
-
-
-def _send_password_reset_email(recipient_email, reset_url, user_id):
- send_kwargs, ctx = get_email_context()
- ctx["reset_url"] = reset_url
- send_templated_mail(
- template_name="account/password_reset",
- recipient_list=[recipient_email],
- context=ctx,
- **send_kwargs,
- )
- account_events.customer_password_reset_link_sent_event(user_id=user_id)
-
-
-def send_user_change_email_url(redirect_url, user, new_email, token):
- """Trigger sending a email change email for the given user."""
- event_parameters = {"old_email": user.email, "new_email": new_email}
- _send_request_email_change_email.delay(
- new_email, redirect_url, user.pk, token, event_parameters
- )
-
-
-def _send_request_email_change_email(
- recipient_email, redirect_url, user_id, token, event_parameters
-):
- params = urlencode({"token": token})
- redirect_url = prepare_url(params, redirect_url)
- send_kwargs, ctx = get_email_context()
- ctx["redirect_url"] = redirect_url
- send_templated_mail(
- template_name=REQUEST_EMAIL_CHANGE_TEMPLATE,
- recipient_list=[recipient_email],
- context=ctx,
- **send_kwargs,
- )
- account_events.customer_email_change_request_event(
- user_id=user_id, parameters=event_parameters
- )
-
-
-def send_user_change_email_notification(recipient_email):
- """Trigger sending a email change notification email for the given user."""
- _send_user_change_email_notification.delay(recipient_email)
-
-
-def _send_user_change_email_notification(recipient_email):
- send_kwargs, ctx = get_email_context()
- send_templated_mail(
- template_name=EMAIL_CHANGED_NOTIFICATION_TEMPLATE,
- recipient_list=[recipient_email],
- context=ctx,
- **send_kwargs,
- )
-
-
-def send_account_delete_confirmation_email_with_url(redirect_url, user):
- """Trigger sending a account delete email for the given user."""
- token = default_token_generator.make_token(user)
- _send_account_delete_confirmation_email_with_url.delay(
- user.email, redirect_url, token
- )
-
-
-def _send_account_delete_confirmation_email_with_url(
- recipient_email, redirect_url, token
-):
- params = urlencode({"token": token})
- delete_url = prepare_url(params, redirect_url)
- _send_delete_confirmation_email(recipient_email, delete_url)
-
-
-def _send_delete_confirmation_email(recipient_email, delete_url):
- send_kwargs, ctx = get_email_context()
- ctx["delete_url"] = delete_url
- send_templated_mail(
- template_name=ACCOUNT_DELETE_TEMPLATE,
- recipient_list=[recipient_email],
- context=ctx,
- **send_kwargs,
- )
-
-
-def send_set_password_email_with_url(redirect_url, user, staff=False):
- """Trigger sending a set password email for the given customer/staff."""
- template_type = "staff" if staff else "customer"
- template = f"dashboard/{template_type}/set_password"
- token = default_token_generator.make_token(user)
- _send_set_user_password_email_with_url.delay(
- user.email, redirect_url, token, template
- )
-
-
-def _send_set_user_password_email_with_url(
- recipient_email, redirect_url, token, template_name
-):
- params = urlencode({"email": recipient_email, "token": token})
- password_set_url = prepare_url(params, redirect_url)
- _send_set_password_email(recipient_email, password_set_url, template_name)
-
-
-def _send_set_password_email(recipient_email, password_set_url, template_name):
- send_kwargs, ctx = get_email_context()
- ctx["password_set_url"] = password_set_url
- send_templated_mail(
- template_name=template_name,
- recipient_list=[recipient_email],
- context=ctx,
- **send_kwargs,
- )
diff --git a/saleor/account/notifications.py b/saleor/account/notifications.py
new file mode 100644
index 0000000000..55b0c89f59
--- /dev/null
+++ b/saleor/account/notifications.py
@@ -0,0 +1,92 @@
+from django.contrib.auth.tokens import default_token_generator
+
+from ..core.notify_events import NotifyEventType
+from .models import User
+
+
+def get_default_user_payload(user: User):
+ return {
+ "id": user.id,
+ "email": user.email,
+ "first_name": user.first_name,
+ "last_name": user.last_name,
+ "is_staff": user.is_staff,
+ "is_active": user.is_active,
+ "private_metadata": user.private_metadata,
+ "metadata": user.metadata,
+ }
+
+
+def send_user_password_reset_notification(redirect_url, user, manager):
+ """Trigger sending a password reset notification for the given user."""
+ user_payload = get_default_user_payload(user)
+ user_payload.update(
+ {
+ "token": default_token_generator.make_token(user),
+ "redirect_url": redirect_url,
+ }
+ )
+ manager.notify(NotifyEventType.ACCOUNT_PASSWORD_RESET, payload=user_payload)
+
+
+def send_account_confirmation(user, redirect_url, manager):
+ """Trigger sending an account confirmation notification for the given user."""
+ user_payload = get_default_user_payload(user)
+ user_payload.update(
+ {
+ "token": default_token_generator.make_token(user),
+ "redirect_url": redirect_url,
+ }
+ )
+ manager.notify(NotifyEventType.ACCOUNT_CONFIRMATION, payload=user_payload)
+
+
+def send_request_user_change_email_notification(
+ redirect_url, user, new_email, token, manager
+):
+ """Trigger sending a notification change email for the given user."""
+ user_payload = get_default_user_payload(user)
+ user_payload.update(
+ {
+ "old_email": user.email,
+ "new_email": new_email,
+ "redirect_url": redirect_url,
+ "token": token,
+ }
+ )
+ manager.notify(NotifyEventType.ACCOUNT_CHANGE_EMAIL_REQUEST, payload=user_payload)
+
+
+def send_user_change_email_notification(recipient_email, user, manager):
+ """Trigger sending a email change notification for the given user."""
+ user_payload = get_default_user_payload(user)
+ user_payload["old_email"] = recipient_email
+ manager.notify(NotifyEventType.ACCOUNT_CHANGE_EMAIL_CONFIRM, payload=user_payload)
+
+
+def send_account_delete_confirmation_notification(redirect_url, user, manager):
+ """Trigger sending a account delete notification for the given user."""
+ user_payload = get_default_user_payload(user)
+ user_payload.update(
+ {
+ "token": default_token_generator.make_token(user),
+ "redirect_url": redirect_url,
+ }
+ )
+ manager.notify(NotifyEventType.ACCOUNT_DELETE, payload=user_payload)
+
+
+def send_set_password_notification(redirect_url, user, manager, staff=False):
+ """Trigger sending a set password notification for the given customer/staff."""
+ user_payload = get_default_user_payload(user)
+ user_payload.update(
+ {
+ "token": default_token_generator.make_token(user),
+ "redirect_url": redirect_url,
+ }
+ )
+ if staff:
+ event = NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD
+ else:
+ event = NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD
+ manager.notify(event, payload=user_payload)
diff --git a/saleor/account/tests/test_emails.py b/saleor/account/tests/test_emails.py
deleted file mode 100644
index 13c446aaf5..0000000000
--- a/saleor/account/tests/test_emails.py
+++ /dev/null
@@ -1,85 +0,0 @@
-from unittest import mock
-
-from django.core import mail
-from templated_email import get_connection
-
-import saleor.account.emails as account_emails
-
-
-def test_send_set_password_email(staff_user, site_settings):
- password_set_url = "https://www.example.com"
- template_name = "dashboard/staff/set_password"
- recipient_email = staff_user.email
-
- account_emails._send_set_password_email(
- recipient_email, password_set_url, template_name
- )
-
- assert len(mail.outbox) == 1
- sended_message = mail.outbox[0].body
- assert password_set_url in sended_message
-
-
[email protected]("saleor.account.emails.send_templated_mail")
-def test_send_email_request_change(
- mocked_templated_email, site_settings, customer_user
-):
- new_email = "[email protected]"
- template = account_emails.REQUEST_EMAIL_CHANGE_TEMPLATE
- redirect_url = "localhost"
- token = "token_example"
- event_parameters = {"old_email": customer_user.email, "new_email": new_email}
-
- account_emails._send_request_email_change_email(
- new_email, redirect_url, customer_user.pk, token, event_parameters
- )
- ctx = {
- "domain": "mirumee.com",
- "redirect_url": "localhost?token=token_example",
- "site_name": "mirumee.com",
- }
- recipients = [new_email]
-
- expected_call_kwargs = {
- "context": ctx,
- "from_email": site_settings.default_from_email,
- "template_name": template,
- }
-
- # mocked_templated_email.assert_called_once()
- mocked_templated_email.assert_called_once_with(
- recipient_list=recipients, **expected_call_kwargs
- )
-
- # Render the email to ensure there is no error
- email_connection = get_connection()
- email_connection.get_email_message(to=recipients, **expected_call_kwargs)
-
-
[email protected]("saleor.account.emails.send_templated_mail")
-def test_send_email_changed_notification(
- mocked_templated_email, site_settings, customer_user
-):
- old_email = "[email protected]"
- template = account_emails.EMAIL_CHANGED_NOTIFICATION_TEMPLATE
- account_emails.send_user_change_email_notification(old_email)
- ctx = {
- "domain": "mirumee.com",
- "site_name": "mirumee.com",
- }
- recipients = [old_email]
-
- expected_call_kwargs = {
- "context": ctx,
- "from_email": site_settings.default_from_email,
- "template_name": template,
- }
-
- # mocked_templated_email.assert_called_once()
- mocked_templated_email.assert_called_once_with(
- recipient_list=recipients, **expected_call_kwargs
- )
-
- # Render the email to ensure there is no error
- email_connection = get_connection()
- email_connection.get_email_message(to=recipients, **expected_call_kwargs)
diff --git a/saleor/account/tests/test_notifications.py b/saleor/account/tests/test_notifications.py
new file mode 100644
index 0000000000..fdd68c857e
--- /dev/null
+++ b/saleor/account/tests/test_notifications.py
@@ -0,0 +1,51 @@
+from unittest import mock
+
+from freezegun import freeze_time
+
+from ...core.notify_events import UserNotifyEvent
+from ...plugins.manager import get_plugins_manager
+from .. import notifications
+from ..notifications import get_default_user_payload
+
+
+@freeze_time("2018-05-31 12:00:01")
[email protected]("saleor.plugins.manager.PluginsManager.notify")
+def test_send_email_request_change(mocked_notify, site_settings, customer_user):
+ new_email = "[email protected]"
+ redirect_url = "localhost"
+ token = "token_example"
+
+ manager = get_plugins_manager()
+ notifications.send_request_user_change_email_notification(
+ redirect_url, customer_user, new_email, token, manager
+ )
+
+ expected_payload = get_default_user_payload(customer_user)
+ expected_payload.update(
+ {
+ "old_email": customer_user.email,
+ "new_email": new_email,
+ "redirect_url": redirect_url,
+ "token": token,
+ }
+ )
+
+ mocked_notify.assert_called_once_with(
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST, payload=expected_payload
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.notify")
+def test_send_email_changed_notification(mocked_notify, site_settings, customer_user):
+ old_email = "[email protected]"
+
+ notifications.send_user_change_email_notification(
+ old_email, customer_user, get_plugins_manager()
+ )
+
+ expected_payload = get_default_user_payload(customer_user)
+ expected_payload.update({"old_email": old_email})
+
+ mocked_notify.assert_called_once_with(
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM, payload=expected_payload
+ )
diff --git a/saleor/core/notify_events.py b/saleor/core/notify_events.py
new file mode 100644
index 0000000000..41d003106c
--- /dev/null
+++ b/saleor/core/notify_events.py
@@ -0,0 +1,25 @@
+class UserNotifyEvent:
+ ACCOUNT_CONFIRMATION = "account_confirmation"
+ ACCOUNT_PASSWORD_RESET = "account_password_reset"
+ ACCOUNT_CHANGE_EMAIL_REQUEST = "account_change_email_request"
+ ACCOUNT_CHANGE_EMAIL_CONFIRM = "account_change_email_confirm"
+ ACCOUNT_DELETE = "account_delete"
+ ACCOUNT_SET_CUSTOMER_PASSWORD = "account_set_customer_password"
+
+ CHOICES = [
+ ACCOUNT_CONFIRMATION,
+ ACCOUNT_PASSWORD_RESET,
+ ACCOUNT_CHANGE_EMAIL_REQUEST,
+ ACCOUNT_CHANGE_EMAIL_CONFIRM,
+ ACCOUNT_DELETE,
+ ACCOUNT_SET_CUSTOMER_PASSWORD,
+ ]
+
+
+class AdminNotifyEvent:
+ ACCOUNT_SET_STAFF_PASSWORD = "account_set_staff_password"
+ CHOICES = [ACCOUNT_SET_STAFF_PASSWORD]
+
+
+class NotifyEventType(UserNotifyEvent, AdminNotifyEvent):
+ CHOICES = UserNotifyEvent.CHOICES + AdminNotifyEvent.CHOICES
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 7418c4883f..590345063a 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -5,7 +5,7 @@ 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 emails, events as account_events, models, utils
+from ....account import events as account_events, models, notifications, utils
from ....account.error_codes import AccountErrorCode
from ....checkout import AddressType
from ....core.jwt import create_token, jwt_decode
@@ -99,7 +99,9 @@ class AccountRegister(ModelMutation):
if settings.ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL:
user.is_active = False
user.save()
- emails.send_account_confirmation_email(user, cleaned_input["redirect_url"])
+ notifications.send_account_confirmation(
+ user, cleaned_input["redirect_url"], info.context.plugins
+ )
else:
user.save()
account_events.customer_account_created_event(user=user)
@@ -173,7 +175,9 @@ class AccountRequestDeletion(BaseMutation):
raise ValidationError(
{"redirect_url": error}, code=AccountErrorCode.INVALID
)
- emails.send_account_delete_confirmation_email_with_url(redirect_url, user)
+ notifications.send_account_delete_confirmation_notification(
+ redirect_url, user, info.context.plugins
+ )
return AccountRequestDeletion()
@@ -416,7 +420,9 @@ class RequestEmailChange(BaseMutation):
"user_pk": user.pk,
}
token = create_token(token_payload, JWT_TTL_REQUEST_EMAIL_CHANGE)
- emails.send_user_change_email_url(redirect_url, user, new_email, token)
+ notifications.send_request_user_change_email_notification(
+ redirect_url, user, new_email, token, info.context.plugins
+ )
return RequestEmailChange(user=user)
@@ -472,7 +478,9 @@ class ConfirmEmailChange(BaseMutation):
user.email = new_email
user.save(update_fields=["email"])
- emails.send_user_change_email_notification(old_email)
+ notifications.send_user_change_email_notification(
+ old_email, user, info.context.plugins
+ )
event_parameters = {"old_email": old_email, "new_email": new_email}
account_events.customer_email_changed_event(
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 190821c8ae..07564fd14b 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -5,11 +5,11 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
from ....account import events as account_events, models
-from ....account.emails import (
- send_set_password_email_with_url,
- send_user_password_reset_email_with_url,
-)
from ....account.error_codes import AccountErrorCode
+from ....account.notifications import (
+ send_set_password_notification,
+ send_user_password_reset_notification,
+)
from ....core.exceptions import PermissionDenied
from ....core.permissions import AccountPermissions
from ....core.utils.url import validate_storefront_url
@@ -139,7 +139,7 @@ class RequestPasswordReset(BaseMutation):
)
}
)
- send_user_password_reset_email_with_url(redirect_url, user)
+ send_user_password_reset_notification(redirect_url, user, info.context.plugins)
return RequestPasswordReset()
@@ -428,8 +428,8 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
account_events.customer_account_created_event(user=instance)
if cleaned_input.get("redirect_url"):
- send_set_password_email_with_url(
- cleaned_input.get("redirect_url"), instance
+ send_set_password_notification(
+ cleaned_input.get("redirect_url"), instance, info.context.plugins
)
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index 8903764938..71ce374a4f 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -6,8 +6,8 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from ....account import events as account_events, models, utils
-from ....account.emails import send_set_password_email_with_url
from ....account.error_codes import AccountErrorCode
+from ....account.notifications import send_set_password_notification
from ....account.thumbnails import create_user_avatar_thumbnails
from ....account.utils import remove_staff_member
from ....checkout import AddressType
@@ -241,8 +241,11 @@ class StaffCreate(ModelMutation):
def save(cls, info, user, cleaned_input):
user.save()
if cleaned_input.get("redirect_url"):
- send_set_password_email_with_url(
- redirect_url=cleaned_input.get("redirect_url"), user=user, staff=True
+ send_set_password_notification(
+ redirect_url=cleaned_input.get("redirect_url"),
+ user=user,
+ manager=info.context.plugins,
+ staff=True,
)
@classmethod
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index 21bdf676c2..399b1abeb7 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -2,7 +2,7 @@ import re
import uuid
from collections import defaultdict
from datetime import timedelta
-from unittest.mock import ANY, MagicMock, Mock, patch
+from unittest.mock import MagicMock, Mock, patch
import graphene
import pytest
@@ -10,7 +10,6 @@ from django.contrib.auth.models import Group
from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import ValidationError
from django.core.files import File
-from django.core.validators import URLValidator
from django.test import override_settings
from freezegun import freeze_time
from prices import Money
@@ -18,8 +17,10 @@ from prices import Money
from ....account import events as account_events
from ....account.error_codes import AccountErrorCode
from ....account.models import Address, User
+from ....account.notifications import get_default_user_payload
from ....checkout import AddressType
from ....core.jwt import create_token
+from ....core.notify_events import NotifyEventType
from ....core.permissions import AccountPermissions, OrderPermissions
from ....order.models import FulfillmentStatus, Order
from ....product.tests.utils import create_image
@@ -708,8 +709,10 @@ ACCOUNT_REGISTER_MUTATION = """
@override_settings(
ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=True, ALLOWED_CLIENT_HOSTS=["localhost"]
)
-@patch("saleor.account.emails._send_account_confirmation_email")
-def test_customer_register(send_account_confirmation_email_mock, api_client):
+@patch("saleor.account.notifications.default_token_generator.make_token")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_customer_register(mocked_notify, mocked_generator, api_client):
+ mocked_generator.return_value = "token"
variables = {
"email": email,
@@ -718,12 +721,21 @@ def test_customer_register(send_account_confirmation_email_mock, api_client):
}
query = ACCOUNT_REGISTER_MUTATION
mutation_name = "accountRegister"
+
response = api_client.post_graphql(query, variables)
+
+ new_user = User.objects.get(email=email)
content = get_graphql_content(response)
data = content["data"][mutation_name]
+
+ expected_payload = get_default_user_payload(new_user)
+ expected_payload["token"] = "token"
+ expected_payload["redirect_url"] = "http://localhost:3000"
+
assert not data["accountErrors"]
- assert send_account_confirmation_email_mock.delay.call_count == 1
- new_user = User.objects.get(email=email)
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_CONFIRMATION, payload=expected_payload
+ )
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
@@ -738,29 +750,29 @@ def test_customer_register(send_account_confirmation_email_mock, api_client):
@override_settings(ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=False)
-@patch("saleor.account.emails._send_account_confirmation_email")
-def test_customer_register_disabled_email_confirmation(
- send_account_confirmation_email_mock, api_client
-):
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_customer_register_disabled_email_confirmation(mocked_notify, api_client):
variables = {"email": email, "password": "Password"}
response = api_client.post_graphql(ACCOUNT_REGISTER_MUTATION, variables)
errors = response.json()["data"]["accountRegister"]["accountErrors"]
assert errors == []
- send_account_confirmation_email_mock.delay.assert_not_called()
+ created_user = User.objects.get()
+ expected_payload = get_default_user_payload(created_user)
+ expected_payload["token"] = "token"
+ expected_payload["redirect_url"] = "http://localhost:3000"
+ mocked_notify.assert_not_called()
@override_settings(ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=True)
-@patch("saleor.account.emails._send_account_confirmation_email")
-def test_customer_register_no_redirect_url(
- send_account_confirmation_email_mock, api_client
-):
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_customer_register_no_redirect_url(mocked_notify, api_client):
variables = {"email": "[email protected]", "password": "Password"}
response = api_client.post_graphql(ACCOUNT_REGISTER_MUTATION, variables)
errors = response.json()["data"]["accountRegister"]["accountErrors"]
assert "redirectUrl" in map(lambda error: error["field"], errors)
- assert send_account_confirmation_email_mock.delay.call_count == 0
+ mocked_notify.assert_not_called()
CUSTOMER_CREATE_MUTATION = """
@@ -805,10 +817,12 @@ CUSTOMER_CREATE_MUTATION = """
"""
-@patch("saleor.account.emails._send_set_password_email")
+@patch("saleor.account.notifications.default_token_generator.make_token")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_customer_create(
- _send_set_password_email_mock, staff_api_client, address, permission_manage_users
+ mocked_notify, mocked_generator, staff_api_client, address, permission_manage_users
):
+ mocked_generator.return_value = "token"
first_name = "api_first_name"
last_name = "api_last_name"
@@ -849,8 +863,12 @@ def test_customer_create(
assert not data["user"]["isStaff"]
assert data["user"]["isActive"]
- _send_set_password_email_mock.assert_called_once_with(
- new_customer.email, ANY, "dashboard/customer/set_password"
+ new_user = User.objects.get(email=email)
+ expected_payload = get_default_user_payload(new_user)
+ expected_payload["token"] = "token"
+ expected_payload["redirect_url"] = "https://www.example.com"
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD, payload=expected_payload
)
customer_creation_event = account_events.CustomerEvent.objects.get()
@@ -858,13 +876,12 @@ def test_customer_create(
assert customer_creation_event.user == new_customer
-@freeze_time("2018-05-31 12:00:01")
-@patch("saleor.account.emails._send_set_user_password_email_with_url.delay")
+@patch("saleor.account.notifications.default_token_generator.make_token")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_customer_create_send_password_with_url(
- _send_set_user_password_email_with_url_mock,
- staff_api_client,
- permission_manage_users,
+ mocked_notify, mocked_generator, staff_api_client, permission_manage_users,
):
+ mocked_generator.return_value = "token"
variables = {"email": email, "redirect_url": "https://www.example.com"}
@@ -878,9 +895,11 @@ def test_customer_create_send_password_with_url(
new_customer = User.objects.get(email=email)
assert new_customer
- token = default_token_generator.make_token(new_customer)
- _send_set_user_password_email_with_url_mock.assert_called_once_with(
- new_customer.email, ANY, token, "dashboard/customer/set_password"
+ expected_payload = get_default_user_payload(new_customer)
+ expected_payload["redirect_url"] = "https://www.example.com"
+ expected_payload["token"] = "token"
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD, payload=expected_payload
)
@@ -1207,8 +1226,10 @@ ACCOUNT_REQUEST_DELETION_MUTATION = """
"""
-@patch("saleor.account.emails._send_delete_confirmation_email")
-def test_account_request_deletion(send_delete_confirmation_email_mock, user_api_client):
+@patch("saleor.account.notifications.default_token_generator.make_token")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_account_request_deletion(mocked_notify, mocked_token, user_api_client):
+ mocked_token.return_value = "token"
user = user_api_client.user
variables = {"redirectUrl": "https://www.example.com"}
response = user_api_client.post_graphql(
@@ -1217,17 +1238,18 @@ def test_account_request_deletion(send_delete_confirmation_email_mock, user_api_
content = get_graphql_content(response)
data = content["data"]["accountRequestDeletion"]
assert not data["errors"]
- send_delete_confirmation_email_mock.assert_called_once_with(user.email, ANY)
- url = send_delete_confirmation_email_mock.mock_calls[0][1][1]
- url_validator = URLValidator()
- url_validator(url)
+ expected_payload = get_default_user_payload(user)
+ expected_payload["redirect_url"] = "https://www.example.com"
+ expected_payload["token"] = "token"
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_DELETE, payload=expected_payload
+ )
@freeze_time("2018-05-31 12:00:01")
-@patch("saleor.account.emails._send_account_delete_confirmation_email_with_url.delay")
-def test_account_request_deletion_token_validation(
- send_account_delete_confirmation_email_with_url_mock, user_api_client
-):
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_account_request_deletion_token_validation(mocked_notify, user_api_client):
user = user_api_client.user
token = default_token_generator.make_token(user)
variables = {"redirectUrl": "https://www.example.com"}
@@ -1237,27 +1259,27 @@ def test_account_request_deletion_token_validation(
content = get_graphql_content(response)
data = content["data"]["accountRequestDeletion"]
assert not data["errors"]
- send_account_delete_confirmation_email_with_url_mock.assert_called_once_with(
- user.email, ANY, token
+
+ expected_payload = get_default_user_payload(user)
+ expected_payload["redirect_url"] = "https://www.example.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_DELETE, payload=expected_payload
)
- url = send_account_delete_confirmation_email_with_url_mock.mock_calls[0][1][1]
- url_validator = URLValidator()
- url_validator(url)
-@patch("saleor.account.emails._send_account_delete_confirmation_email_with_url.delay")
-def test_account_request_deletion_anonymous_user(
- send_account_delete_confirmation_email_with_url_mock, api_client
-):
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_account_request_deletion_anonymous_user(mocked_notify, api_client):
variables = {"redirectUrl": "https://www.example.com"}
response = api_client.post_graphql(ACCOUNT_REQUEST_DELETION_MUTATION, variables)
assert_no_permission(response)
- send_account_delete_confirmation_email_with_url_mock.assert_not_called()
+ mocked_notify.assert_not_called()
-@patch("saleor.account.emails._send_account_delete_confirmation_email_with_url.delay")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_request_deletion_storefront_hosts_not_allowed(
- send_account_delete_confirmation_email_with_url_mock, user_api_client
+ mocked_notify, user_api_client
):
variables = {"redirectUrl": "https://www.fake.com"}
response = user_api_client.post_graphql(
@@ -1270,13 +1292,13 @@ def test_account_request_deletion_storefront_hosts_not_allowed(
"field": "redirectUrl",
"code": AccountErrorCode.INVALID.name,
}
- send_account_delete_confirmation_email_with_url_mock.assert_not_called()
+ mocked_notify.assert_not_called()
@freeze_time("2018-05-31 12:00:01")
-@patch("saleor.account.emails._send_account_delete_confirmation_email_with_url.delay")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_request_deletion_all_storefront_hosts_allowed(
- send_account_delete_confirmation_email_with_url_mock, user_api_client, settings
+ mocked_notify, user_api_client, settings
):
user = user_api_client.user
token = default_token_generator.make_token(user)
@@ -1288,19 +1310,19 @@ def test_account_request_deletion_all_storefront_hosts_allowed(
content = get_graphql_content(response)
data = content["data"]["accountRequestDeletion"]
assert not data["errors"]
- send_account_delete_confirmation_email_with_url_mock.assert_called_once_with(
- user.email, ANY, token
+
+ expected_payload = get_default_user_payload(user)
+ expected_payload["redirect_url"] = "https://www.test.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_DELETE, payload=expected_payload
)
- url = send_account_delete_confirmation_email_with_url_mock.mock_calls[0][1][1]
- url_validator = URLValidator()
- url_validator(url)
@freeze_time("2018-05-31 12:00:01")
-@patch("saleor.account.emails._send_account_delete_confirmation_email_with_url.delay")
-def test_account_request_deletion_subdomain(
- send_account_delete_confirmation_email_with_url_mock, user_api_client, settings
-):
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_account_request_deletion_subdomain(mocked_notify, user_api_client, settings):
user = user_api_client.user
token = default_token_generator.make_token(user)
settings.ALLOWED_CLIENT_HOSTS = [".example.com"]
@@ -1311,12 +1333,13 @@ def test_account_request_deletion_subdomain(
content = get_graphql_content(response)
data = content["data"]["accountRequestDeletion"]
assert not data["errors"]
- send_account_delete_confirmation_email_with_url_mock.assert_called_once_with(
- user.email, ANY, token
+ expected_payload = get_default_user_payload(user)
+ expected_payload["redirect_url"] = "https://sub.example.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_DELETE, payload=expected_payload
)
- url = send_account_delete_confirmation_email_with_url_mock.mock_calls[0][1][1]
- url_validator = URLValidator()
- url_validator(url)
ACCOUNT_DELETE_MUTATION = """
@@ -1485,9 +1508,10 @@ STAFF_CREATE_MUTATION = """
"""
-@patch("saleor.account.emails._send_set_password_email")
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_staff_create(
- _send_set_password_email_mock,
+ mocked_notify,
staff_api_client,
staff_user,
media_root,
@@ -1535,8 +1559,13 @@ def test_staff_create(
assert len(groups) == 1
assert {perm["code"].lower() for perm in groups[0]["permissions"]} == expected_perms
- _send_set_password_email_mock.assert_called_once_with(
- staff_user.email, ANY, "dashboard/staff/set_password"
+ token = default_token_generator.make_token(staff_user)
+ expected_payload = get_default_user_payload(staff_user)
+ expected_payload["redirect_url"] = "https://www.example.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD, payload=expected_payload
)
@@ -1566,9 +1595,10 @@ def test_staff_create_app_no_permission(
assert_no_permission(response)
-@patch("saleor.account.emails._send_set_password_email")
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_staff_create_out_of_scope_group(
- _send_set_password_email_mock,
+ mocked_notify,
staff_api_client,
superuser_api_client,
media_root,
@@ -1610,7 +1640,7 @@ def test_staff_create_out_of_scope_group(
assert errors[0] == expected_error
- _send_set_password_email_mock.assert_not_called()
+ mocked_notify.assert_not_called()
# for superuser
response = superuser_api_client.post_graphql(STAFF_CREATE_MUTATION, variables)
@@ -1651,18 +1681,20 @@ def test_staff_create_out_of_scope_group(
for group in expected_groups:
assert group in groups
- _send_set_password_email_mock.assert_called_once_with(
- staff_user.email, ANY, "dashboard/staff/set_password"
+ token = default_token_generator.make_token(staff_user)
+ expected_payload = get_default_user_payload(staff_user)
+ expected_payload["redirect_url"] = "https://www.example.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD, payload=expected_payload
)
@freeze_time("2018-05-31 12:00:01")
-@patch("saleor.account.emails._send_set_user_password_email_with_url.delay")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_staff_create_send_password_with_url(
- _send_set_user_password_email_with_url_mock,
- staff_api_client,
- media_root,
- permission_manage_staff,
+ mocked_notify, staff_api_client, media_root, permission_manage_staff,
):
variables = {"email": email, "redirect_url": "https://www.example.com"}
@@ -1678,8 +1710,12 @@ def test_staff_create_send_password_with_url(
assert staff_user.is_staff
token = default_token_generator.make_token(staff_user)
- _send_set_user_password_email_with_url_mock.assert_called_once_with(
- staff_user.email, ANY, token, "dashboard/staff/set_password"
+ expected_payload = get_default_user_payload(staff_user)
+ expected_payload["redirect_url"] = "https://www.example.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD, payload=expected_payload
)
@@ -2956,22 +2992,22 @@ CONFIRM_ACCOUNT_MUTATION = """
"""
-@patch("saleor.account.emails._send_password_reset_email")
-def test_account_reset_password(
- send_password_reset_email_mock, user_api_client, customer_user
-):
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_account_reset_password(mocked_notify, user_api_client, customer_user):
variables = {"email": customer_user.email, "redirectUrl": "https://www.example.com"}
response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- assert send_password_reset_email_mock.called
- send_password_reset_email_mock.assert_called_once_with(
- user_api_client.user.email, ANY, user_api_client.user.pk
+ token = default_token_generator.make_token(customer_user)
+ expected_payload = get_default_user_payload(customer_user)
+ expected_payload["redirect_url"] = "https://www.example.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_PASSWORD_RESET, payload=expected_payload
)
- url = send_password_reset_email_mock.mock_calls[0][1][1]
- url_validator = URLValidator()
- url_validator(url)
@freeze_time("2018-05-31 12:00:01")
@@ -3029,29 +3065,27 @@ def test_account_confirmation_invalid_token(
match_orders_with_new_user_mock.assert_not_called()
-@patch("saleor.account.emails._send_password_reset_email")
-def test_request_password_reset_email_for_staff(
- send_password_reset_email_mock, staff_api_client
-):
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_request_password_reset_email_for_staff(mocked_notify, staff_api_client):
redirect_url = "https://www.example.com"
variables = {"email": staff_api_client.user.email, "redirectUrl": redirect_url}
response = staff_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- assert send_password_reset_email_mock.call_count == 1
- send_password_reset_email_mock.assert_called_once_with(
- staff_api_client.user.email, ANY, staff_api_client.user.pk
+ token = default_token_generator.make_token(staff_api_client.user)
+ expected_payload = get_default_user_payload(staff_api_client.user)
+ expected_payload["redirect_url"] = "https://www.example.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_PASSWORD_RESET, payload=expected_payload
)
- url = send_password_reset_email_mock.mock_calls[0][1][1]
- url_validator = URLValidator()
- url_validator(url)
-@patch("saleor.account.emails._send_password_reset_email")
-def test_account_reset_password_invalid_email(
- send_password_reset_email_mock, user_api_client
-):
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_account_reset_password_invalid_email(mocked_notify, user_api_client):
variables = {
"email": "[email protected]",
"redirectUrl": "https://www.example.com",
@@ -3060,12 +3094,12 @@ def test_account_reset_password_invalid_email(
content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert len(data["errors"]) == 1
- assert not send_password_reset_email_mock.called
+ mocked_notify.assert_not_called()
-@patch("saleor.account.emails._send_password_reset_email")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_storefront_hosts_not_allowed(
- send_password_reset_email_mock, user_api_client, customer_user
+ mocked_notify, user_api_client, customer_user
):
variables = {"email": customer_user.email, "redirectUrl": "https://www.fake.com"}
response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
@@ -3073,12 +3107,13 @@ def test_account_reset_password_storefront_hosts_not_allowed(
data = content["data"]["requestPasswordReset"]
assert len(data["errors"]) == 1
assert data["errors"][0]["field"] == "redirectUrl"
- assert not send_password_reset_email_mock.called
+ mocked_notify.assert_not_called()
-@patch("saleor.account.emails._send_password_reset_email")
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_all_storefront_hosts_allowed(
- send_password_reset_email_mock, user_api_client, customer_user, settings
+ mocked_notify, user_api_client, customer_user, settings
):
settings.ALLOWED_CLIENT_HOSTS = ["*"]
variables = {"email": customer_user.email, "redirectUrl": "https://www.test.com"}
@@ -3086,18 +3121,21 @@ def test_account_reset_password_all_storefront_hosts_allowed(
content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- assert send_password_reset_email_mock.called
- send_password_reset_email_mock.assert_called_once_with(
- user_api_client.user.email, ANY, user_api_client.user.pk
+
+ token = default_token_generator.make_token(customer_user)
+ expected_payload = get_default_user_payload(customer_user)
+ expected_payload["redirect_url"] = "https://www.test.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_PASSWORD_RESET, payload=expected_payload
)
- url = send_password_reset_email_mock.mock_calls[0][1][1]
- url_validator = URLValidator()
- url_validator(url)
-@patch("saleor.account.emails._send_password_reset_email")
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_subdomain(
- send_password_reset_email_mock, user_api_client, customer_user, settings
+ mocked_notify, user_api_client, customer_user, settings
):
settings.ALLOWED_CLIENT_HOSTS = [".example.com"]
variables = {"email": customer_user.email, "redirectUrl": "https://sub.example.com"}
@@ -3105,13 +3143,15 @@ def test_account_reset_password_subdomain(
content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- assert send_password_reset_email_mock.called
- send_password_reset_email_mock.assert_called_once_with(
- user_api_client.user.email, ANY, user_api_client.user.pk
+
+ token = default_token_generator.make_token(customer_user)
+ expected_payload = get_default_user_payload(customer_user)
+ expected_payload["redirect_url"] = "https://sub.example.com"
+ expected_payload["token"] = token
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_PASSWORD_RESET, payload=expected_payload
)
- url = send_password_reset_email_mock.mock_calls[0][1][1]
- url_validator = URLValidator()
- url_validator(url)
ACCOUNT_ADDRESS_CREATE_MUTATION = """
diff --git a/saleor/plugins/admin_emails/__init__.py b/saleor/plugins/admin_emails/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 3d63d9d66d..ddcc87ad6e 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -17,6 +17,7 @@ from .models import PluginConfiguration
if TYPE_CHECKING:
# flake8: noqa
+ from ..core.notify_events import NotifyEventType
from ..core.taxes import TaxType
from ..checkout.models import Checkout, CheckoutLine
from ..discount import DiscountInfo
@@ -71,6 +72,13 @@ class BasePlugin:
"""
return NotImplemented
+ def notify(self, event: "NotifyEventType", payload: dict, previous_value):
+ """Handle notification request.
+
+ Overwrite this method if the plugin is responsible for sending notifications.
+ """
+ return NotImplemented
+
def change_user_address(
self,
address: "Address",
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index a06087bf8e..a7b9271437 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -19,6 +19,7 @@ from .models import PluginConfiguration
if TYPE_CHECKING:
# flake8: noqa
from .base_plugin import BasePlugin
+ from .notify_events import NotifyEvent
from ..checkout.models import Checkout, CheckoutLine
from ..product.models import Product, ProductType
from ..account.models import Address, User
@@ -513,6 +514,10 @@ class PluginsManager(PaymentInterface):
plugin, "webhook", default_value, request, path
)
+ def notify(self, event: "NotifyEvent", payload: dict):
+ default_value = None
+ return self.__run_method_on_plugins("notify", default_value, event, payload)
+
def get_plugins_manager(
manager_path: str = None, plugins: List[str] = None
diff --git a/saleor/plugins/user_email/__init__.py b/saleor/plugins/user_email/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/plugins/user_email/emails.py b/saleor/plugins/user_email/emails.py
new file mode 100644
index 0000000000..f3287cb894
--- /dev/null
+++ b/saleor/plugins/user_email/emails.py
@@ -0,0 +1,64 @@
+from ...account.models import User
+from .tasks import (
+ send_account_confirmation_email_task,
+ send_account_delete_confirmation_email_task,
+ send_password_reset_email_task,
+ send_request_email_change_email_task,
+ send_set_user_password_email_task,
+ send_user_change_email_notification_task,
+)
+
+REQUEST_EMAIL_CHANGE_TEMPLATE = "account/request_email_change"
+EMAIL_CHANGED_NOTIFICATION_TEMPLATE = "account/email_changed_notification"
+ACCOUNT_DELETE_TEMPLATE = "account/account_delete"
+PASSWORD_RESET_TEMPLATE = "account/password_reset"
+
+
+def get_default_user_payload(user: User):
+ return {
+ "email": user.email,
+ "first_name": user.first_name,
+ "last_name": user.last_name,
+ "is_staff": user.is_staff,
+ "is_active": user.is_active,
+ "private_metadata": user.private_metadata,
+ "metadata": user.metadata,
+ }
+
+
+def handle_account_password_reset_event(payload):
+ send_password_reset_email_task.delay(
+ payload["email"], payload["redirect_url"], payload["id"], payload["token"]
+ )
+
+
+def handle_account_confirmation(payload):
+ send_account_confirmation_email_task.delay(
+ payload["email"], payload["token"], payload["redirect_url"]
+ )
+
+
+def handle_account_change_email_request(payload):
+ send_request_email_change_email_task.delay(
+ payload["new_email"],
+ payload["old_email"],
+ payload["redirect_url"],
+ payload["id"],
+ payload["token"],
+ )
+
+
+def handle_account_change_email_confirm(payload):
+ send_user_change_email_notification_task.delay(payload["old_email"])
+
+
+def handle_account_delete(payload):
+ send_account_delete_confirmation_email_task.delay(
+ payload["email"], payload["redirect_url"], payload["token"]
+ )
+
+
+def handle_account_set_customer_password(payload):
+ send_set_user_password_email_task.delay(
+ payload["email"], payload["redirect_url"], payload["token"]
+ )
diff --git a/saleor/plugins/user_email/plugin.py b/saleor/plugins/user_email/plugin.py
new file mode 100644
index 0000000000..460e1f62e6
--- /dev/null
+++ b/saleor/plugins/user_email/plugin.py
@@ -0,0 +1,69 @@
+import logging
+from dataclasses import dataclass
+
+from ...core.notify_events import NotifyEventType, UserNotifyEvent
+from ..base_plugin import BasePlugin
+from .emails import (
+ handle_account_change_email_confirm,
+ handle_account_change_email_request,
+ handle_account_confirmation,
+ handle_account_delete,
+ handle_account_password_reset_event,
+ handle_account_set_customer_password,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class UserEmailConfig:
+ account_confirmation_template: str
+ account_password_reset_template: str
+
+
+event_map = {
+ UserNotifyEvent.ACCOUNT_CONFIRMATION: handle_account_confirmation,
+ UserNotifyEvent.ACCOUNT_SET_CUSTOMER_PASSWORD: handle_account_set_customer_password,
+ UserNotifyEvent.ACCOUNT_DELETE: handle_account_delete,
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM: handle_account_change_email_confirm,
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST: handle_account_change_email_request,
+ UserNotifyEvent.ACCOUNT_PASSWORD_RESET: handle_account_password_reset_event,
+}
+
+
+class UserEmailPlugin(BasePlugin):
+ PLUGIN_ID = "mirumee.notifications.user_email"
+ PLUGIN_NAME = "User emails"
+ # TODO the configuration will be implemented in separate pull request
+
+ # DEFAULT_CONFIGURATION = [
+ # {"name": "account-confirmation_template", "value": None},
+ # {"name": "account-password-reset-template", "value": None},
+ # ]
+ #
+ # CONFIG_STRUCTURE = {
+ # "account-confirmation_template": {
+ # "type": ConfigurationTypeField.SECRET,
+ # "help_text": "",
+ # "label": "Account confirmation template",
+ # },
+ # "account-password-reset-template": {
+ # "type": ConfigurationTypeField.SECRET,
+ # "help_text": "",
+ # "label": "Account password reset template",
+ # },
+ # }
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.active = True
+
+ def notify(self, event: NotifyEventType, payload: dict, previous_value):
+ if not self.active:
+ return previous_value
+ if event not in UserNotifyEvent.CHOICES:
+ return previous_value
+ if event not in event_map:
+ logger.warning(f"Missing handler for event {event}")
+ return previous_value
+ event_map[event](payload) # type: ignore
diff --git a/saleor/plugins/user_email/tasks.py b/saleor/plugins/user_email/tasks.py
new file mode 100644
index 0000000000..4bba37d281
--- /dev/null
+++ b/saleor/plugins/user_email/tasks.py
@@ -0,0 +1,112 @@
+from urllib.parse import urlencode
+
+from templated_email import send_templated_mail
+
+from ...account import events as account_events
+from ...celeryconf import app
+from ...core.emails import get_email_context
+from ...core.utils.url import prepare_url
+
+REQUEST_EMAIL_CHANGE_TEMPLATE = "account/request_email_change"
+EMAIL_CHANGED_NOTIFICATION_TEMPLATE = "account/email_changed_notification"
+ACCOUNT_DELETE_TEMPLATE = "account/account_delete"
+PASSWORD_RESET_TEMPLATE = "account/password_reset"
+
+
+def send_account_confirmation_email_task(email, token, redirect_url):
+ params = urlencode({"email": email, "token": token})
+ confirm_url = prepare_url(params, redirect_url)
+ send_kwargs, ctx = get_email_context()
+ ctx["confirm_url"] = confirm_url
+ send_templated_mail(
+ template_name="account/confirm",
+ recipient_list=[email],
+ context=ctx,
+ **send_kwargs,
+ )
+
+
+def send_password_reset_email_task(recipient_email, redirect_url, user_id, token):
+ params = urlencode({"email": recipient_email, "token": token})
+ reset_url = prepare_url(params, redirect_url)
+ _send_password_reset_email(recipient_email, reset_url, user_id)
+
+
+def _send_password_reset_email(recipient_email, reset_url, user_id):
+ send_kwargs, ctx = get_email_context()
+ ctx["reset_url"] = reset_url
+ send_templated_mail(
+ template_name="account/password_reset",
+ recipient_list=[recipient_email],
+ context=ctx,
+ **send_kwargs,
+ )
+ account_events.customer_password_reset_link_sent_event(user_id=user_id)
+
+
+def send_request_email_change_email_task(
+ new_email, old_email, redirect_url, user_id, token
+):
+ params = urlencode({"token": token})
+ redirect_url = prepare_url(params, redirect_url)
+ send_kwargs, ctx = get_email_context()
+ ctx["redirect_url"] = redirect_url
+ send_templated_mail(
+ template_name=REQUEST_EMAIL_CHANGE_TEMPLATE,
+ recipient_list=[new_email],
+ context=ctx,
+ **send_kwargs,
+ )
+ account_events.customer_email_change_request_event(
+ user_id=user_id, parameters={"old_email": old_email, "new_email": new_email}
+ )
+
+
+def send_user_change_email_notification_task(recipient_email):
+ send_kwargs, ctx = get_email_context()
+ send_templated_mail(
+ template_name=EMAIL_CHANGED_NOTIFICATION_TEMPLATE,
+ recipient_list=[recipient_email],
+ context=ctx,
+ **send_kwargs,
+ )
+
+
+def send_account_delete_confirmation_email_task(recipient_email, redirect_url, token):
+ params = urlencode({"token": token})
+ delete_url = prepare_url(params, redirect_url)
+ _send_delete_confirmation_email(recipient_email, delete_url)
+
+
+def _send_delete_confirmation_email(recipient_email, delete_url):
+ send_kwargs, ctx = get_email_context()
+ ctx["delete_url"] = delete_url
+ send_templated_mail(
+ template_name=ACCOUNT_DELETE_TEMPLATE,
+ recipient_list=[recipient_email],
+ context=ctx,
+ **send_kwargs,
+ )
+
+
+def send_set_user_password_email_task(recipient_email, redirect_url, token):
+ params = urlencode({"email": recipient_email, "token": token})
+ password_set_url = prepare_url(params, redirect_url)
+ _send_set_password_email(recipient_email, password_set_url)
+
+
+def _send_set_password_email(recipient_email, password_set_url):
+ send_kwargs, ctx = get_email_context()
+ ctx["password_set_url"] = password_set_url
+ send_templated_mail(
+ template_name="dashboard/customer/set_password",
+ recipient_list=[recipient_email],
+ context=ctx,
+ **send_kwargs,
+ )
diff --git a/saleor/plugins/user_email/tests/__init__.py b/saleor/plugins/user_email/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/plugins/user_email/tests/conftests.py b/saleor/plugins/user_email/tests/conftests.py
new file mode 100644
index 0000000000..1b45a6644f
--- /dev/null
+++ b/saleor/plugins/user_email/tests/conftests.py
@@ -0,0 +1,18 @@
+import pytest
+
+from ...manager import get_plugins_manager
+from ..plugin import UserEmailPlugin
+
+
+def user_email_plugin(settings):
+ def fun():
+ settings.PLUGINS += ["saleor.plugins.user_email.plugin.UserEmailPlugin"]
+ manager = get_plugins_manager()
+ manager.save_plugin_configuration(
+ UserEmailPlugin.PLUGIN_ID, {"active": True, "configuration": []}
+ )
+ manager = get_plugins_manager()
+ return manager.plugins[0]
+
+ return fun