Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Base of account confirmation mechanism mutations
Tomasz Szymańskib523c21d7874
diff --git a/saleor/account/emails.py b/saleor/account/emails.pyindex 549a76b90a..b752413431 100644--- a/saleor/account/emails.py+++ b/saleor/account/emails.py@@ -1,11 +1,13 @@from urllib.parse import urlencodefrom django.contrib.auth.tokens import default_token_generator+from django.contrib.sites.models import Sitefrom templated_email import send_templated_mailfrom ..account import events as account_eventsfrom ..celeryconf import appfrom ..core.emails import get_email_context, prepare_url+from ..core.utils import build_absolute_uridef send_user_password_reset_email_with_url(redirect_url, user):@@ -14,6 +16,27 @@ def send_user_password_reset_email_with_url(redirect_url, user):_send_password_reset_email_with_url.delay(user.email, redirect_url, user.pk, token)++def send_account_confirmation_email(user):+ """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)+++def _send_account_confirmation_email(email, token):+ domain = Site.objects.get_current().domain+ confirm_url = f"https://{domain}/account/confirm?email={email}&token={token}"+ 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,+ )++@app.taskdef _send_password_reset_email_with_url(recipient_email, redirect_url, user_id, token):params = urlencode({"email": recipient_email, "token": token})diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.pyindex 8d92ff9b52..130d47dfa6 100644--- a/saleor/graphql/account/mutations/account.py+++ b/saleor/graphql/account/mutations/account.py@@ -46,7 +46,9 @@ class AccountRegister(ModelMutation):def save(cls, info, user, cleaned_input):password = cleaned_input["password"]user.set_password(password)+ user.is_active = Falseuser.save()+ emails.send_account_confirmation_email(user)account_events.customer_account_created_event(user=user)info.context.extensions.customer_created(customer=user)diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 34dc5bdf21..592d072f29 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -153,6 +153,43 @@ class RequestPasswordReset(BaseMutation):return RequestPasswordReset()+class ConfirmAccount(BaseMutation):+ class Arguments:+ token = graphene.String(+ description="A one-time token required to set the password.", required=True+ )+ email = graphene.String(+ description="E-mail of the user performing account confirmation.", required=True+ )++ class Meta:+ description = "Sends an email with the account confirmation link."++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ try:+ user = models.User.objects.get(email=data["email"])+ except ObjectDoesNotExist:+ raise ValidationError(+ {+ "email": ValidationError(+ "User with this email doesn't exist",+ code=AccountErrorCode.NOT_FOUND,+ )+ }+ )++ if not default_token_generator.check_token(user, data["token"]):+ raise ValidationError(+ {"token": ValidationError(INVALID_TOKEN, code=AccountErrorCode.INVALID)}+ )++ user.is_active = True+ user.save()++ return ConfirmAccount()++class PasswordChange(BaseMutation):user = graphene.Field(User, description="A user instance with a new password.")diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.pyindex 40db11ba3c..323d10bf1c 100644--- a/saleor/graphql/account/schema.py+++ b/saleor/graphql/account/schema.py@@ -22,6 +22,7 @@ from .mutations.account import (from .mutations.base import (PasswordChange,RequestPasswordReset,+ ConfirmAccount,SetPassword,UserClearMeta,UserUpdateMeta,@@ -181,6 +182,7 @@ class AccountQueries(graphene.ObjectType):class AccountMutations(graphene.ObjectType):# Base mutationsrequest_password_reset = RequestPasswordReset.Field()+ confirm_account = ConfirmAccount.Field()set_password = SetPassword.Field()password_change = PasswordChange.Field()diff --git a/templates/templated_email/account/confirm.email b/templates/templated_email/account/confirm.emailnew file mode 100644index 0000000000..981b9dba31--- /dev/null+++ b/templates/templated_email/account/confirm.email@@ -0,0 +1,21 @@+{% load i18n %}++{% block subject %}+ {% trans "Account confirmation e-mail" context "Account confirmation e-mail subject" %}+{% endblock %}++{% block plain %}+{% include 'templated_email/shared/_header.email' %}+{% blocktrans context "Account confirmation e-mail text" %}+In order to log into {{domain}}, you have to confirm your email address first.+Please click the link below to do so and log into your account.+{% endblocktrans %}++{{ confirm_url }}++{% include 'templated_email/shared/_footer.email' %}+{% endblock %}++{% block html %}+{% include 'templated_email/compiled/confirm.html' %}+{% endblock %}diff --git a/templates/templated_email/source/confirm.mjml b/templates/templated_email/source/confirm.mjmlnew file mode 100644index 0000000000..bece3c6da9--- /dev/null+++ b/templates/templated_email/source/confirm.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 "Account confirmation e-mail text" %}+ In order to log into {{domain}}, you have to confirm your email address first.+ Please click the link below to do so and log into your account.+ {% endblocktrans %}+ </mj-text>+ <mj-text>+ <a href="{{ confirm_url }}">+ {{ confirm_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.pyindex 29924daefe..098f1fa3a7 100644--- a/tests/api/test_account.py+++ b/tests/api/test_account.py@@ -578,7 +578,8 @@ ACCOUNT_REGISTER_MUTATION = """"""-def test_customer_register(user_api_client):+@patch("saleor.account.emails._send_account_confirmation_email")+def test_customer_register(send_account_confirmation_email_mock, user_api_client):email = "[email protected]"variables = {"email": email, "password": "Password"}query = ACCOUNT_REGISTER_MUTATION@@ -587,6 +588,7 @@ def test_customer_register(user_api_client):content = get_graphql_content(response)data = content["data"][mutation_name]assert not data["errors"]+ assert send_account_confirmation_email_mock.delay.call_count == 1new_user = User.objects.get(email=email)response = user_api_client.post_graphql(query, variables)@@ -2097,6 +2099,18 @@ REQUEST_PASSWORD_RESET_MUTATION = """"""+CONFIRM_ACCOUNT_MUTATION = """+ mutation ConfirmAccount($email: String!, $token: String!) {+ confirmAccount(email: $email, token: $token) {+ errors {+ field+ message+ }+ }+ }+"""++@patch("saleor.account.emails._send_password_reset_email")def test_account_reset_password(send_password_reset_email_mock, user_api_client, customer_user@@ -2115,6 +2129,22 @@ def test_account_reset_password(url_validator(url)+def test_account_confirmation(+ user_api_client, customer_user+):+ customer_user.is_active = False+ customer_user.save()+ token = default_token_generator.make_token(customer_user)++ variables = {"email": customer_user.email, "token": token}+ response = user_api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)+ content = get_graphql_content(response)++ customer_user.refresh_from_db()+ assert customer_user.is_active == True+++@patch("saleor.account.emails._send_password_reset_email")def test_request_password_reset_email_for_staff(send_password_reset_email_mock, staff_api_client