Skip to content

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

Mutation to change user email

Krzysztof Świątek8e875bfb5bf3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9fcee09253..b3fc68f832 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add address query - #5148 by @kswiatek92
- Add `checkout_quantity_changed` webhook - #5042 by @derenio
- Remove unnecessary manage_orders permission - #5142 by @kswiatek92
+- Mutation to change user email - #5076 by @kswiatek92
## 2.9.0
diff --git a/saleor/account/__init__.py b/saleor/account/__init__.py
index ffd3a77857..8524800b49 100755
--- a/saleor/account/__init__.py
+++ b/saleor/account/__init__.py
@@ -9,6 +9,8 @@ class CustomerEvents:
PASSWORD_RESET_LINK_SENT = "password_reset_link_sent"
PASSWORD_RESET = "password_reset"
PASSWORD_CHANGED = "password_changed"
+ EMAIL_CHANGE_REQUEST = "email_changed_request"
+ EMAIL_CHANGED = "email_changed"
# Order related events
PLACED_ORDER = "placed_order" # created an order
@@ -26,7 +28,7 @@ class CustomerEvents:
ACCOUNT_CREATED,
pgettext_lazy(
"Event from a customer that got their account created",
- "The account account was created",
+ "The account was created",
),
),
(
@@ -43,6 +45,27 @@ class CustomerEvents:
"The account password was reset",
),
),
+ (
+ EMAIL_CHANGE_REQUEST,
+ pgettext_lazy(
+ "Event from a customer that requested email address change",
+ "The user requested to change the account's email address.",
+ ),
+ ),
+ (
+ PASSWORD_CHANGED,
+ pgettext_lazy(
+ "Event from a customer that changed their password",
+ "The account password was changed",
+ ),
+ ),
+ (
+ EMAIL_CHANGED,
+ pgettext_lazy(
+ "Event from a customer that changed their email address",
+ "The account email address was changed",
+ ),
+ ),
(
PLACED_ORDER,
pgettext_lazy(
diff --git a/saleor/account/emails.py b/saleor/account/emails.py
index 549a76b90a..1884da302d 100644
--- a/saleor/account/emails.py
+++ b/saleor/account/emails.py
@@ -7,6 +7,11 @@ from ..account import events as account_events
from ..celeryconf import app
from ..core.emails import get_email_context, 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."""
@@ -33,6 +38,49 @@ def _send_password_reset_email(recipient_email, reset_url, user_id):
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)
@@ -57,7 +105,7 @@ 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/account_delete",
+ template_name=ACCOUNT_DELETE_TEMPLATE,
recipient_list=[recipient_email],
context=ctx,
**send_kwargs,
diff --git a/saleor/account/events.py b/saleor/account/events.py
index 43c43373ad..49d7ec7c1d 100644
--- a/saleor/account/events.py
+++ b/saleor/account/events.py
@@ -29,6 +29,22 @@ def customer_password_changed_event(*, user: UserType) -> Optional[CustomerEvent
return CustomerEvent.objects.create(user=user, type=CustomerEvents.PASSWORD_CHANGED)
+def customer_email_change_request_event(
+ *, user_id: UserType, parameters: dict
+) -> Optional[CustomerEvent]:
+ return CustomerEvent.objects.create(
+ user_id=user_id, type=CustomerEvents.EMAIL_CHANGE_REQUEST, parameters=parameters
+ )
+
+
+def customer_email_changed_event(
+ *, user: UserType, parameters: dict
+) -> Optional[CustomerEvent]:
+ return CustomerEvent.objects.create(
+ user=user, type=CustomerEvents.EMAIL_CHANGED, parameters=parameters
+ )
+
+
def customer_placed_order_event(
*, user: UserType, order: Order
) -> Optional[CustomerEvent]:
diff --git a/saleor/account/migrations/0037_auto_20191219_0944.py b/saleor/account/migrations/0037_auto_20191219_0944.py
new file mode 100644
index 0000000000..41aa3008dd
--- /dev/null
+++ b/saleor/account/migrations/0037_auto_20191219_0944.py
@@ -0,0 +1,33 @@
+# Generated by Django 2.2.6 on 2019-12-19 15:44
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("account", "0036_auto_20191209_0407")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="customerevent",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("ACCOUNT_CREATED", "account_created"),
+ ("PASSWORD_RESET_LINK_SENT", "password_reset_link_sent"),
+ ("PASSWORD_RESET", "password_reset"),
+ ("EMAIL_CHANGED_REQUEST", "email_changed_request"),
+ ("PASSWORD_CHANGED", "password_changed"),
+ ("EMAIL_CHANGED", "email_changed"),
+ ("PLACED_ORDER", "placed_order"),
+ ("NOTE_ADDED_TO_ORDER", "note_added_to_order"),
+ ("DIGITAL_LINK_DOWNLOADED", "digital_link_downloaded"),
+ ("CUSTOMER_DELETED", "customer_deleted"),
+ ("NAME_ASSIGNED", "name_assigned"),
+ ("EMAIL_ASSIGNED", "email_assigned"),
+ ("NOTE_ADDED", "note_added"),
+ ],
+ max_length=255,
+ ),
+ )
+ ]
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index 24562933fc..a3fec1faea 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -1,9 +1,13 @@
import os
import random
+import jwt
from django.conf import settings
+from django.core.exceptions import ValidationError
from django.core.files import File
+from django.utils import timezone
+from ..account.error_codes import AccountErrorCode
from ..checkout import AddressType
from ..core.utils import create_thumbnails
from ..extensions.manager import get_extensions_manager
@@ -90,3 +94,29 @@ def remove_staff_member(staff):
staff.save()
else:
staff.delete()
+
+
+def create_jwt_token(token_data):
+ expiration_date = timezone.now() + timezone.timedelta(hours=1)
+ token_kwargs = {"exp": expiration_date}
+ token_kwargs.update(token_data)
+ token = jwt.encode(
+ token_kwargs, settings.JWT_TOKEN_SECRET, algorithm="HS256"
+ ).decode()
+ return token
+
+
+def decode_jwt_token(token):
+ try:
+ decoded_token = jwt.decode(
+ token.encode(), settings.JWT_TOKEN_SECRET, algorithms=["HS256"]
+ )
+ except jwt.PyJWTError:
+ raise ValidationError(
+ {
+ "token": ValidationError(
+ "Invalid or expired token.", code=AccountErrorCode.INVALID
+ )
+ }
+ )
+ return decoded_token
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 8d92ff9b52..afb102449c 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -4,6 +4,7 @@ from django.core.exceptions import ValidationError
from ....account import emails, events as account_events, models, utils
from ....account.error_codes import AccountErrorCode
+from ....account.utils import create_jwt_token, decode_jwt_token
from ....checkout import AddressType
from ....core.utils.url import validate_storefront_url
from ...account.enums import AddressTypeEnum
@@ -296,3 +297,110 @@ class AccountUpdateMeta(UpdateMetaBaseMutation):
@classmethod
def get_instance(cls, info, **data):
return info.context.user
+
+
+class RequestEmailChange(BaseMutation):
+ user = graphene.Field(User, description="A user instance.")
+
+ class Arguments:
+ password = graphene.String(required=True, description="User password.")
+ new_email = graphene.String(required=True, description="New user email.")
+ redirect_url = graphene.String(
+ required=True,
+ description=(
+ "URL of a view where users should be redirected to "
+ "update the email address. URL in RFC 1808 format."
+ ),
+ )
+
+ class Meta:
+ description = "Request email change of the logged in user."
+ error_type_class = AccountError
+ error_type_field = "account_errors"
+
+ @classmethod
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ user = info.context.user
+ password = data["password"]
+ new_email = data["new_email"]
+ redirect_url = data["redirect_url"]
+
+ if not user.check_password(password):
+ raise ValidationError(
+ {
+ "user_password": ValidationError(
+ "Password isn't valid.", code=AccountErrorCode.INVALID_PASSWORD
+ )
+ }
+ )
+ if models.User.objects.filter(email=new_email).exists():
+ raise ValidationError(
+ {
+ "new_email": ValidationError(
+ "Email is used by other user.", code=AccountErrorCode.UNIQUE
+ )
+ }
+ )
+ try:
+ validate_storefront_url(redirect_url)
+ except ValidationError as error:
+ raise ValidationError(
+ {"redirect_url": error}, code=AccountErrorCode.INVALID
+ )
+ token_kwargs = {
+ "old_email": user.email,
+ "new_email": new_email,
+ "user_pk": user.pk,
+ }
+ token = create_jwt_token(token_kwargs)
+ emails.send_user_change_email_url(redirect_url, user, new_email, token)
+ return RequestEmailChange(user=user)
+
+
+class ConfirmEmailChange(BaseMutation):
+ user = graphene.Field(User, description="A user instance with a new email.")
+
+ class Arguments:
+ token = graphene.String(
+ description="A one-time token required to change the email.", required=True
+ )
+
+ class Meta:
+ description = "Confirm the email change of the logged-in user."
+ error_type_class = AccountError
+ error_type_field = "account_errors"
+
+ @classmethod
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ user = info.context.user
+ token = data["token"]
+ decoded_token = decode_jwt_token(token)
+ new_email = decoded_token["new_email"]
+ old_email = decoded_token["old_email"]
+
+ if models.User.objects.filter(email=new_email).exists():
+ raise ValidationError(
+ {
+ "new_email": ValidationError(
+ "Email is used by other user.", code=AccountErrorCode.UNIQUE
+ )
+ }
+ )
+
+ user.email = new_email
+ user.save(update_fields=["email"])
+ emails.send_user_change_email_notification(old_email)
+ event_parameters = {"old_email": old_email, "new_email": new_email}
+
+ account_events.customer_email_changed_event(
+ user=user, parameters=event_parameters
+ )
+ return ConfirmEmailChange(user=user)
diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.py
index 40db11ba3c..db27a0385d 100644
--- a/saleor/graphql/account/schema.py
+++ b/saleor/graphql/account/schema.py
@@ -18,6 +18,8 @@ from .mutations.account import (
AccountSetDefaultAddress,
AccountUpdate,
AccountUpdateMeta,
+ ConfirmEmailChange,
+ RequestEmailChange,
)
from .mutations.base import (
PasswordChange,
@@ -183,6 +185,8 @@ class AccountMutations(graphene.ObjectType):
request_password_reset = RequestPasswordReset.Field()
set_password = SetPassword.Field()
password_change = PasswordChange.Field()
+ request_email_change = RequestEmailChange.Field()
+ confirm_email_change = ConfirmEmailChange.Field()
# Account mutations
account_address_create = AccountAddressCreate.Field()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 7f3ce8cee7..7a194d13ab 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1027,6 +1027,12 @@ enum ConfigurationTypeFieldEnum {
PASSWORD
}
+type ConfirmEmailChange {
+ errors: [Error!]
+ user: User
+ accountErrors: [AccountError!]
+}
+
enum CountryCode {
AF
AX
@@ -1333,6 +1339,9 @@ enum CustomerEventsEnum {
ACCOUNT_CREATED
PASSWORD_RESET_LINK_SENT
PASSWORD_RESET
+ EMAIL_CHANGED_REQUEST
+ PASSWORD_CHANGED
+ EMAIL_CHANGED
PLACED_ORDER
NOTE_ADDED_TO_ORDER
DIGITAL_LINK_DOWNLOADED
@@ -2261,6 +2270,8 @@ type Mutation {
requestPasswordReset(email: String!, redirectUrl: String!): RequestPasswordReset
setPassword(token: String!, email: String!, password: String!): SetPassword
passwordChange(newPassword: String!, oldPassword: String!): PasswordChange
+ requestEmailChange(newEmail: String!, password: String!, redirectUrl: String!): RequestEmailChange
+ confirmEmailChange(token: String!): ConfirmEmailChange
accountAddressCreate(input: AddressInput!, type: AddressTypeEnum): AccountAddressCreate
accountAddressUpdate(id: ID!, input: AddressInput!): AccountAddressUpdate
accountAddressDelete(id: ID!): AccountAddressDelete
@@ -3553,6 +3564,12 @@ enum ReportingPeriod {
THIS_MONTH
}
+type RequestEmailChange {
+ errors: [Error!]
+ user: User
+ accountErrors: [AccountError!]
+}
+
type RequestPasswordReset {
errors: [Error!]
accountErrors: [AccountError!]
diff --git a/saleor/settings.py b/saleor/settings.py
index d753d5a93a..b0032c8b5e 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -538,3 +538,6 @@ PLUGINS = [
# True to use DraftJS (JSON based), for the 2.0 dashboard
# False to use the old editor from dashboard 1.0
USE_JSON_CONTENT = get_bool_from_env("USE_JSON_CONTENT", False)
+JWT_TOKEN_SECRET = os.environ.get("JWT_TOKEN_SECRET", "saleor")
+if not DEBUG:
+ JWT_VERIFY_EXPIRATION = True
diff --git a/templates/templated_email/account/email_changed_notification.email b/templates/templated_email/account/email_changed_notification.email
new file mode 100644
index 0000000000..f2bcf16589
--- /dev/null
+++ b/templates/templated_email/account/email_changed_notification.email
@@ -0,0 +1,22 @@
+{% load i18n %}
+
+{% block subject %}
+ {% trans "Email change e-mail" context "Email change e-mail subject" %}
+{% endblock %}
+
+{% block plain %}
+{% include 'templated_email/shared/_header.email' %}
+{% blocktrans context "Email change e-mail text" %}
+
+You're receiving this e-mail because you or someone else has changed email for your user account at {{ domain }}.
+If you didn't request this change, please contact the administrator.
+{% endblocktrans %}
+
+{{ reset_url }}
+
+{% include 'templated_email/shared/_footer.email' %}
+{% endblock %}
+
+{% block html %}
+{% include 'templated_email/compiled/password_reset.html' %}
+{% endblock %}
diff --git a/templates/templated_email/account/request_email_change.email b/templates/templated_email/account/request_email_change.email
new file mode 100644
index 0000000000..9f6844addb
--- /dev/null
+++ b/templates/templated_email/account/request_email_change.email
@@ -0,0 +1,22 @@
+{% load i18n %}
+
+{% block subject %}
+ {% trans "Email change e-mail" context "Email change e-mail subject" %}
+{% endblock %}
+
+{% block plain %}
+{% include 'templated_email/shared/_header.email' %}
+{% blocktrans context "Email change e-mail text" %}
+
+You're receiving this e-mail because you or someone else has requested an email change for your user account at {{ domain }}.
+It can be safely ignored if you did not request an email change. Click the link below to confirm new email address.
+{% endblocktrans %}
+
+{{ redirect_url }}
+
+{% include 'templated_email/shared/_footer.email' %}
+{% endblock %}
+
+{% block html %}
+{% include 'templated_email/compiled/password_reset.html' %}
+{% endblock %}
diff --git a/templates/templated_email/source/email_changed_notification.mjml b/templates/templated_email/source/email_changed_notification.mjml
new file mode 100644
index 0000000000..c01c0a2581
--- /dev/null
+++ b/templates/templated_email/source/email_changed_notification.mjml
@@ -0,0 +1,30 @@
+<mjml>
+ <mj-head>
+ <mj-include path="./shared/styles.mjml" />
+ </mj-head>
+ <mj-body>
+ <mj-raw>
+ {% load i18n %}
+ </mj-raw>
+ <mj-include path="./shared/header.mjml" />
+ <mj-section>
+ <mj-column>
+ <mj-text font-size="16px">
+ {% trans "Hi!" context "Standard e-mail greeting" %}
+ </mj-text>
+ <mj-text>
+ {% blocktrans trimmed context "Email change e-mail text" %}
+ You're receiving this e-mail because you or someone else has changed email for your user account at {{ domain }}.<br/>
+ If you didn't request this change, please contact the administrator.
+ {% endblocktrans %}
+ </mj-text>
+ <mj-text>
+ <a href="{{ reset_url }}">
+ {{ reset_url }}
+ </a>
+ </mj-text>
+ </mj-column>
+ </mj-section>
+ <mj-include path="./shared/footer.mjml" />
+ </mj-body>
+</mjml>
diff --git a/templates/templated_email/source/request_email_change.mjml b/templates/templated_email/source/request_email_change.mjml
new file mode 100644
index 0000000000..8a970339f5
--- /dev/null
+++ b/templates/templated_email/source/request_email_change.mjml
@@ -0,0 +1,30 @@
+<mjml>
+ <mj-head>
+ <mj-include path="./shared/styles.mjml" />
+ </mj-head>
+ <mj-body>
+ <mj-raw>
+ {% load i18n %}
+ </mj-raw>
+ <mj-include path="./shared/header.mjml" />
+ <mj-section>
+ <mj-column>
+ <mj-text font-size="16px">
+ {% trans "Hi!" context "Standard e-mail greeting" %}
+ </mj-text>
+ <mj-text>
+ {% blocktrans trimmed context "Email change e-mail text" %}
+ You're receiving this e-mail because you or someone else has requested an email change for your user account at {{ domain }}.<br/>
+ It can be safely ignored if you did not request an email change. Click the link below to confirm new email address.
+ {% endblocktrans %}
+ </mj-text>
+ <mj-text>
+ <a href="{{ reset_url }}">
+ {{ redirect_url }}
+ </a>
+ </mj-text>
+ </mj-column>
+ </mj-section>
+ <mj-include path="./shared/footer.mjml" />
+ </mj-body>
+</mjml>
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index 29924daefe..55e937b137 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -15,7 +15,7 @@ from prices import Money
from saleor.account import events as account_events
from saleor.account.error_codes import AccountErrorCode
from saleor.account.models import Address, User
-from saleor.account.utils import get_random_avatar
+from saleor.account.utils import create_jwt_token, get_random_avatar
from saleor.checkout import AddressType
from saleor.graphql.account.mutations.base import INVALID_TOKEN
from saleor.graphql.account.mutations.staff import (
@@ -3052,3 +3052,134 @@ def test_address_query_as_anonymous_user(api_client, address_other_country):
variables = {"id": graphene.Node.to_global_id("Address", address_other_country.pk)}
response = api_client.post_graphql(ADDRESS_QUERY, variables)
assert_no_permission(response)
+
+
+REQUEST_EMAIL_CHANGE_QUERY = """
+mutation requestEmailChange(
+ $password: String!, $new_email: String!, $redirect_url: String!
+) {
+ requestEmailChange(
+ password: $password, newEmail: $new_email, redirectUrl: $redirect_url
+ ) {
+ user {
+ email
+ }
+ accountErrors {
+ code
+ message
+ field
+ }
+ }
+}
+"""
+
+
+def test_request_email_change(user_api_client, customer_user):
+ variables = {
+ "password": "password",
+ "new_email": "[email protected]",
+ "redirect_url": "http://www.example.com",
+ }
+
+ 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
+
+
+def test_request_email_change_to_existing_email(
+ user_api_client, customer_user, staff_user
+):
+ variables = {
+ "password": "password",
+ "new_email": staff_user.email,
+ "redirect_url": "http://www.example.com",
+ }
+
+ response = user_api_client.post_graphql(REQUEST_EMAIL_CHANGE_QUERY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["requestEmailChange"]
+ assert not data["user"]
+ assert data["accountErrors"] == [
+ {
+ "code": "UNIQUE",
+ "message": "Email is used by other user.",
+ "field": "newEmail",
+ }
+ ]
+
+
+def test_request_email_change_with_invalid_redirect_url(
+ user_api_client, customer_user, staff_user
+):
+ variables = {
+ "password": "password",
+ "new_email": "[email protected]",
+ "redirect_url": "www.example.com",
+ }
+
+ response = user_api_client.post_graphql(REQUEST_EMAIL_CHANGE_QUERY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["requestEmailChange"]
+ assert not data["user"]
+ assert data["accountErrors"] == [
+ {
+ "code": "INVALID",
+ "message": "Invalid URL. Please check if URL is in RFC 1808 format.",
+ "field": "redirectUrl",
+ }
+ ]
+
+
+EMAIL_UPDATE_QUERY = """
+mutation emailUpdate($token: String!) {
+ confirmEmailChange(token: $token){
+ user {
+ email
+ }
+ accountErrors {
+ code
+ message
+ field
+ }
+ }
+}
+"""
+
+
+def test_email_update(user_api_client, customer_user):
+ new_email = "[email protected]"
+ token_kwargs = {
+ "old_email": customer_user.email,
+ "new_email": new_email,
+ "user_pk": customer_user.pk,
+ }
+ token = create_jwt_token(token_kwargs)
+ variables = {"token": token}
+
+ response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["confirmEmailChange"]
+ assert data["user"]["email"] == new_email
+
+
+def test_email_update_to_existing_email(user_api_client, customer_user, staff_user):
+ token_kwargs = {
+ "old_email": customer_user.email,
+ "new_email": staff_user.email,
+ "user_pk": customer_user.pk,
+ }
+ token = create_jwt_token(token_kwargs)
+ variables = {"token": token}
+
+ response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["confirmEmailChange"]
+ assert not data["user"]
+ assert data["accountErrors"] == [
+ {
+ "code": "UNIQUE",
+ "message": "Email is used by other user.",
+ "field": "newEmail",
+ }
+ ]
diff --git a/tests/test_emails.py b/tests/test_emails.py
index 83dc2af211..0ed80b1683 100644
--- a/tests/test_emails.py
+++ b/tests/test_emails.py
@@ -292,3 +292,70 @@ def test_prepare_url():
params = urlencode({"param1": "abc", "param2": "xyz"})
result = prepare_url(params, redirect_url)
assert result == "https://www.example.com?param1=abc&param2=xyz"
+
+
[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",
+ "logo_url": "http://mirumee.com/static/images/logo-light.svg",
+ "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",
+ "logo_url": "http://mirumee.com/static/images/logo-light.svg",
+ "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)