Skip to content

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

Add possibility to log in without confirming email (#13059)

Krzysztof Waliczek34f3aeb5e38f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d69a15ef08..e6e7515f2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -86,6 +86,11 @@ Shipping methods can be removed by the user after it has been assigned to a chec
- Called when metadata is changed for the Shop object via the generic metadata API or the `shopSettingsUpdate` mutation.
### Other changes
+- Add possibility to log without confirming email - #13059 by @kadewu
+ - New mutation `sendConfirmationEmail` to send an email with confirmation link
+ - New environment variable `CONFIRMATION_EMAIL_LOCK_TIME` to control lock time beetwen new email confirmations
+ - Type `User` gets new field `is_confirmed`
+ - `CustomerInput` gets new field `is_confirmed`
- Use public key thumbprint as KID in JWKS.json #13442 by @cmiacz
- Add POC of Core API tests - #13034 by @fowczarek
diff --git a/saleor/account/error_codes.py b/saleor/account/error_codes.py
index c5a10b62af..267f77008b 100644
--- a/saleor/account/error_codes.py
+++ b/saleor/account/error_codes.py
@@ -59,3 +59,10 @@ class PermissionGroupErrorCode(Enum):
OUT_OF_SCOPE_PERMISSION = "out_of_scope_permission"
OUT_OF_SCOPE_USER = "out_of_scope_user"
OUT_OF_SCOPE_CHANNEL = "out_of_scope_channel"
+
+
+class SendConfirmationEmailErrorCode(Enum):
+ INVALID = "invalid"
+ ACCOUNT_CONFIRMED = "account_confirmed"
+ CONFIRMATION_ALREADY_REQUESTED = "confirmation_already_requested"
+ MISSING_CHANNEL_SLUG = "missing_channel_slug"
diff --git a/saleor/account/migrations/0080_user_is_confirmed.py b/saleor/account/migrations/0080_user_is_confirmed.py
new file mode 100644
index 0000000000..4c641ca5a1
--- /dev/null
+++ b/saleor/account/migrations/0080_user_is_confirmed.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.18 on 2023-05-24 06:06
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0079_full_channel_access_group_for_openid"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="user",
+ name="is_confirmed",
+ field=models.BooleanField(default=True),
+ ),
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE account_user
+ ALTER COLUMN is_confirmed
+ SET DEFAULT true;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/account/migrations/0081_update_user_is_confirmed.py b/saleor/account/migrations/0081_update_user_is_confirmed.py
new file mode 100644
index 0000000000..0a371bd964
--- /dev/null
+++ b/saleor/account/migrations/0081_update_user_is_confirmed.py
@@ -0,0 +1,60 @@
+from django.db import migrations, transaction
+from django.db.models import QuerySet
+from ..models import User
+
+
+# Batch size of 5000 is about ~8MB of memory usage
+BATCH_SIZE = 5000
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]
+ pks = list(qs.values_list("pk", flat=True))
+
+ if not pks:
+ break
+
+ yield pks
+
+ start_pk = pks[-1]
+
+
+def set_user_is_confirmed_to_false(qs: QuerySet["User"]):
+ with transaction.atomic():
+ # lock the batch of objects
+ _users = list(qs.select_for_update(of=(["self"])))
+ qs.update(is_confirmed=False)
+
+
+def set_user_is_confirmed_task(apps, schema_editor):
+ User = apps.get_model("account", "User")
+ SiteSettings = apps.get_model("site", "SiteSettings")
+ confirmation_enabled = (
+ SiteSettings.objects.first().enable_account_confirmation_by_email
+ )
+
+ users = User.objects.order_by("pk").filter(is_confirmed=True)
+ if confirmation_enabled:
+ users = users.filter(is_active=False, last_login__isnull=True)
+
+ for ids in queryset_in_batches(users):
+ qs = User.objects.filter(pk__in=ids)
+ set_user_is_confirmed_to_false(qs)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0080_user_is_confirmed"),
+ ("site", "0038_auto_20230510_1107"),
+ ]
+
+ operations = [
+ migrations.RunPython(set_user_is_confirmed_task, migrations.RunPython.noop)
+ ]
diff --git a/saleor/account/migrations/0082_user_last_confirm_email_request.py b/saleor/account/migrations/0082_user_last_confirm_email_request.py
new file mode 100644
index 0000000000..5d25cb914c
--- /dev/null
+++ b/saleor/account/migrations/0082_user_last_confirm_email_request.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0081_update_user_is_confirmed"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="user",
+ name="last_confirm_email_request",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/saleor/account/models.py b/saleor/account/models.py
index a92e80ce4c..d93bd26432 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -20,6 +20,7 @@ from ..core.utils.json_serializer import CustomJsonEncoder
from ..order.models import Order
from ..permission.enums import AccountPermissions, BasePermissionEnum, get_permissions
from ..permission.models import Permission, PermissionsMixin, _user_has_perm
+from ..site.models import SiteSettings
from . import CustomerEvents
from .validators import validate_possible_number
@@ -166,6 +167,8 @@ class User(
)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
+ is_confirmed = models.BooleanField(default=True)
+ last_confirm_email_request = models.DateTimeField(null=True, blank=True)
note = models.TextField(null=True, blank=True)
date_joined = models.DateTimeField(default=timezone.now, editable=False)
updated_at = models.DateTimeField(auto_now=True, db_index=True)
@@ -304,6 +307,13 @@ class User(
]
return super().has_perms(perm_list, obj)
+ def can_login(self, site_settings: SiteSettings):
+ return self.is_active and (
+ site_settings.allow_login_without_confirmation
+ or not site_settings.enable_account_confirmation_by_email
+ or self.is_confirmed
+ )
+
class CustomerNote(models.Model):
user = models.ForeignKey(
diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
index f6ca327756..ef920b5758 100644
--- a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
@@ -564,6 +564,13 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
was_activated = not old_instance.is_active and updated_instance.is_active
was_deactivated = old_instance.is_active and not updated_instance.is_active
metadata_update = old_instance.metadata != updated_instance.metadata
+ being_confirmed = (
+ not old_instance.is_confirmed and updated_instance.is_confirmed
+ )
+
+ if has_new_email or being_confirmed:
+ assign_user_gift_cards(updated_instance)
+ match_orders_with_new_user(updated_instance)
# Generate the events accordingly
if has_new_email:
@@ -576,8 +583,6 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
parameters={"message": new_email},
)
)
- assign_user_gift_cards(updated_instance)
- match_orders_with_new_user(updated_instance)
users_with_name_or_email_updated.append(updated_instance)
if has_new_name:
diff --git a/saleor/graphql/account/mutations/account/__init__.py b/saleor/graphql/account/mutations/account/__init__.py
index 180f924705..b3e4e6f141 100644
--- a/saleor/graphql/account/mutations/account/__init__.py
+++ b/saleor/graphql/account/mutations/account/__init__.py
@@ -9,6 +9,7 @@ from .account_update import AccountUpdate
from .confirm_account import ConfirmAccount
from .confirm_email_change import ConfirmEmailChange
from .request_email_change import RequestEmailChange
+from .send_confirmation_email import SendConfirmationEmail
__all__ = [
"AccountAddressCreate",
@@ -22,4 +23,5 @@ __all__ = [
"ConfirmAccount",
"ConfirmEmailChange",
"RequestEmailChange",
+ "SendConfirmationEmail",
]
diff --git a/saleor/graphql/account/mutations/account/account_register.py b/saleor/graphql/account/mutations/account/account_register.py
index 7bfa16f575..74dc9bbcbc 100644
--- a/saleor/graphql/account/mutations/account/account_register.py
+++ b/saleor/graphql/account/mutations/account/account_register.py
@@ -85,6 +85,13 @@ class AccountRegister(ModelMutation):
type=WebhookEventAsyncType.NOTIFY_USER,
description="A notification for account confirmation.",
),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED,
+ description=(
+ "An user confirmation was requested. "
+ "This event is always sent regardless of settings."
+ ),
+ ),
]
@classmethod
@@ -150,8 +157,8 @@ class AccountRegister(ModelMutation):
redirect_url = cleaned_input.get("redirect_url")
with traced_atomic_transaction():
+ user.is_confirmed = False
if site.settings.enable_account_confirmation_by_email:
- user.is_active = False
user.save()
# Notifications will be deprecated in the future
diff --git a/saleor/graphql/account/mutations/account/confirm_account.py b/saleor/graphql/account/mutations/account/confirm_account.py
index 8e4d6a4ac4..84d4a97aa4 100644
--- a/saleor/graphql/account/mutations/account/confirm_account.py
+++ b/saleor/graphql/account/mutations/account/confirm_account.py
@@ -60,7 +60,8 @@ class ConfirmAccount(BaseMutation):
)
user.is_active = True
- user.save(update_fields=["is_active", "updated_at"])
+ user.is_confirmed = True
+ user.save(update_fields=["is_active", "is_confirmed", "updated_at"])
match_orders_with_new_user(user)
assign_user_gift_cards(user)
diff --git a/saleor/graphql/account/mutations/account/send_confirmation_email.py b/saleor/graphql/account/mutations/account/send_confirmation_email.py
new file mode 100644
index 0000000000..838f9678e6
--- /dev/null
+++ b/saleor/graphql/account/mutations/account/send_confirmation_email.py
@@ -0,0 +1,129 @@
+from typing import cast
+from urllib.parse import urlencode
+
+import graphene
+from django.conf import settings
+from django.contrib.auth.tokens import default_token_generator
+from django.core.exceptions import ValidationError
+from django.utils import timezone
+
+from .....account import models
+from .....account.error_codes import SendConfirmationEmailErrorCode
+from .....account.notifications import send_account_confirmation
+from .....core.utils.url import prepare_url, validate_storefront_url
+from .....permission.auth_filters import AuthorizationFilters
+from .....webhook.event_types import WebhookEventAsyncType
+from ....channel.utils import clean_channel
+from ....core import ResolveInfo
+from ....core.descriptions import ADDED_IN_315, PREVIEW_FEATURE
+from ....core.doc_category import DOC_CATEGORY_USERS
+from ....core.mutations import BaseMutation
+from ....core.types import SendConfirmationEmailError
+from ....core.utils import WebhookEventInfo
+from ....plugins.dataloaders import get_plugin_manager_promise
+from ....site.dataloaders import get_site_promise
+
+
+class SendConfirmationEmail(BaseMutation):
+ class Arguments:
+ redirect_url = graphene.String(
+ required=True,
+ description=(
+ "Base of frontend URL that will be needed to create confirmation "
+ "URL."
+ ),
+ )
+ channel = graphene.String(
+ required=True,
+ description=("Slug of a channel which will be used for notify user."),
+ )
+
+ class Meta:
+ description = (
+ "Sends a notification confirmation." + ADDED_IN_315 + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_USERS
+ error_type_class = SendConfirmationEmailError
+ permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.NOTIFY_USER,
+ description="A notification for account confirmation.",
+ ),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED,
+ description=(
+ "An account confirmation was requested. "
+ "This event is always sent regardless of settings."
+ ),
+ ),
+ ]
+
+ @classmethod
+ def clean_user(cls, site, redirect_url, info: ResolveInfo):
+ user = info.context.user
+ user = cast(models.User, user)
+
+ if user.is_confirmed or not site.settings.enable_account_confirmation_by_email:
+ raise ValidationError(
+ ValidationError(
+ "User is already confirmed",
+ code=SendConfirmationEmailErrorCode.ACCOUNT_CONFIRMED.value,
+ )
+ )
+
+ if confirm_email_time := user.last_confirm_email_request:
+ delta = timezone.now() - confirm_email_time
+ if delta.total_seconds() < settings.CONFIRMATION_EMAIL_LOCK_TIME:
+ raise ValidationError(
+ ValidationError(
+ "Confirmation email already requested",
+ code=SendConfirmationEmailErrorCode.CONFIRMATION_ALREADY_REQUESTED.value,
+ )
+ )
+
+ try:
+ validate_storefront_url(redirect_url)
+ except ValidationError as error:
+ raise ValidationError(
+ {"redirect_url": error},
+ code=SendConfirmationEmailErrorCode.INVALID.value,
+ )
+
+ return user
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ site = get_site_promise(info.context).get()
+ redirect_url = data["redirect_url"]
+ user = cls.clean_user(site, redirect_url, info)
+
+ channel = clean_channel(
+ data.get("channel"), error_class=SendConfirmationEmailErrorCode
+ ).slug
+ manager = get_plugin_manager_promise(info.context).get()
+ token = default_token_generator.make_token(user)
+
+ send_account_confirmation(
+ user,
+ redirect_url,
+ manager,
+ channel_slug=channel,
+ token=token,
+ )
+ user.last_confirm_email_request = timezone.now()
+ user.save(update_fields=["last_confirm_email_request", "updated_at"])
+
+ 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,
+ channel,
+ token,
+ redirect_url,
+ )
+
+ return SendConfirmationEmail()
diff --git a/saleor/graphql/account/mutations/authentication/create_token.py b/saleor/graphql/account/mutations/authentication/create_token.py
index 55dfdb06f7..394e3cafa7 100644
--- a/saleor/graphql/account/mutations/authentication/create_token.py
+++ b/saleor/graphql/account/mutations/authentication/create_token.py
@@ -13,6 +13,7 @@ from ....core.descriptions import ADDED_IN_38
from ....core.doc_category import DOC_CATEGORY_AUTH
from ....core.mutations import BaseMutation
from ....core.types import AccountError
+from ....site.dataloaders import get_site_promise
from ...types import User
from .utils import _get_new_csrf_token
@@ -55,7 +56,8 @@ class CreateToken(BaseMutation):
return None
@classmethod
- def get_user(cls, _info: ResolveInfo, email, password):
+ def get_user(cls, info: ResolveInfo, email, password):
+ site_settings = get_site_promise(info.context).get().settings
user = cls._retrieve_user_from_credentials(email, password)
if not user:
raise ValidationError(
@@ -66,7 +68,11 @@ class CreateToken(BaseMutation):
)
}
)
- if not user.is_active and not user.last_login:
+ if (
+ not user.is_confirmed
+ and not site_settings.allow_login_without_confirmation
+ and site_settings.enable_account_confirmation_by_email
+ ):
raise ValidationError(
{
"email": ValidationError(
@@ -76,7 +82,7 @@ class CreateToken(BaseMutation):
}
)
- if not user.is_active and user.last_login:
+ if not user.is_active:
raise ValidationError(
{
"email": ValidationError(
diff --git a/saleor/graphql/account/mutations/authentication/request_password_reset.py b/saleor/graphql/account/mutations/authentication/request_password_reset.py
index ca33988175..91beaef585 100644
--- a/saleor/graphql/account/mutations/authentication/request_password_reset.py
+++ b/saleor/graphql/account/mutations/authentication/request_password_reset.py
@@ -15,6 +15,7 @@ from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ....core.utils import WebhookEventInfo
from ....plugins.dataloaders import get_plugin_manager_promise
+from ....site.dataloaders import get_site_promise
class RequestPasswordReset(BaseMutation):
@@ -50,7 +51,7 @@ class RequestPasswordReset(BaseMutation):
]
@classmethod
- def clean_user(cls, email, redirect_url):
+ def clean_user(cls, email, redirect_url, info: ResolveInfo):
try:
validate_storefront_url(redirect_url)
except ValidationError as error:
@@ -58,6 +59,7 @@ class RequestPasswordReset(BaseMutation):
{"redirect_url": error}, code=AccountErrorCode.INVALID.value
)
+ site = get_site_promise(info.context).get()
user = retrieve_user_by_email(email)
if not user:
raise ValidationError(
@@ -69,7 +71,7 @@ class RequestPasswordReset(BaseMutation):
}
)
- if not user.is_active:
+ if not user.can_login(site.settings):
raise ValidationError(
{
"email": ValidationError(
@@ -98,7 +100,7 @@ class RequestPasswordReset(BaseMutation):
email = data["email"]
redirect_url = data["redirect_url"]
channel_slug = data.get("channel")
- user = cls.clean_user(email, redirect_url)
+ user = cls.clean_user(email, redirect_url, info)
if not user.is_staff:
channel_slug = clean_channel(
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index c73ea56e23..a86e063142 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -22,7 +22,7 @@ from ...account.types import Address, AddressInput, User
from ...app.dataloaders import get_app_promise
from ...channel.utils import clean_channel, validate_channel
from ...core import ResolveInfo, SaleorContext
-from ...core.descriptions import ADDED_IN_310, ADDED_IN_314
+from ...core.descriptions import ADDED_IN_310, ADDED_IN_314, ADDED_IN_315
from ...core.doc_category import DOC_CATEGORY_USERS
from ...core.enums import LanguageCodeEnum
from ...core.mutations import ModelDeleteMutation, ModelMutation
@@ -209,6 +209,9 @@ class CustomerInput(UserInput, UserAddressInput):
external_reference = graphene.String(
description="External ID of the customer." + ADDED_IN_310, required=False
)
+ is_confirmed = graphene.Boolean(
+ required=False, description="User account is confirmed." + ADDED_IN_315
+ )
class Meta:
doc_category = DOC_CATEGORY_USERS
diff --git a/saleor/graphql/account/mutations/staff/customer_update.py b/saleor/graphql/account/mutations/staff/customer_update.py
index a9ecb50570..f94ab49ef3 100644
--- a/saleor/graphql/account/mutations/staff/customer_update.py
+++ b/saleor/graphql/account/mutations/staff/customer_update.py
@@ -71,14 +71,17 @@ class CustomerUpdate(CustomerCreate, ModelWithExtRefMutation):
has_new_email = old_instance.email != new_email
was_activated = not old_instance.is_active and new_instance.is_active
was_deactivated = old_instance.is_active and not new_instance.is_active
+ being_confirmed = not old_instance.is_confirmed and new_instance.is_confirmed
+
+ if has_new_email or being_confirmed:
+ assign_user_gift_cards(new_instance)
+ match_orders_with_new_user(new_instance)
# Generate the events accordingly
if has_new_email:
account_events.assigned_email_to_a_customer_event(
staff_user=staff_user, app=app, new_email=new_email
)
- assign_user_gift_cards(new_instance)
- match_orders_with_new_user(new_instance)
if has_new_name:
account_events.assigned_name_to_a_customer_event(
staff_user=staff_user, app=app, new_name=new_fullname
diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.py
index 83ff3d14bb..336edcd258 100644
--- a/saleor/graphql/account/schema.py
+++ b/saleor/graphql/account/schema.py
@@ -32,6 +32,7 @@ from .mutations.account import (
ConfirmAccount,
ConfirmEmailChange,
RequestEmailChange,
+ SendConfirmationEmail,
)
from .mutations.authentication import (
CreateToken,
@@ -267,6 +268,7 @@ class AccountMutations(graphene.ObjectType):
external_verify = ExternalVerify.Field()
request_password_reset = RequestPasswordReset.Field()
+ send_confirmation_email = SendConfirmationEmail.Field()
confirm_account = ConfirmAccount.Field()
set_password = SetPassword.Field()
password_change = PasswordChange.Field()
diff --git a/saleor/graphql/account/tests/benchmark/test_account.py b/saleor/graphql/account/tests/benchmark/test_account.py
index 49aeec5fbb..75660323f3 100644
--- a/saleor/graphql/account/tests/benchmark/test_account.py
+++ b/saleor/graphql/account/tests/benchmark/test_account.py
@@ -41,6 +41,7 @@ def test_query_staff_user(
lastName
isStaff
isActive
+ isConfirmed
addresses {
id
isDefaultShippingAddress
diff --git a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py
index 7143bde9aa..fffa1fe9c7 100644
--- a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py
+++ b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py
@@ -281,6 +281,56 @@ def test_customers_bulk_update_generate_events_when_email_change(
assert order.user == customer_user
+def test_customers_bulk_update_match_orders_and_gift_card_when_confirmed(
+ staff_api_client,
+ staff_user,
+ gift_card,
+ order,
+ customer_user,
+ permission_manage_users,
+):
+ # given
+ customer_user.is_confirmed = False
+ customer_user.save()
+
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+
+ gift_card.created_by = None
+ gift_card.created_by_email = customer_user.email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+
+ order.user = None
+ order.user_email = customer_user.email
+ order.save(update_fields=["user_email", "user"])
+
+ customers_input = [
+ {
+ "id": customer_id,
+ "input": {
+ "isConfirmed": True,
+ },
+ }
+ ]
+
+ variables = {"customers": customers_input}
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_users)
+ response = staff_api_client.post_graphql(CUSTOMER_BULK_UPDATE_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["customerBulkUpdate"]
+
+ # then
+ gift_card.refresh_from_db()
+ order.refresh_from_db()
+ customer_user.refresh_from_db()
+ assert not data["results"][0]["errors"]
+ assert data["count"] == 1
+ assert gift_card.created_by == customer_user
+ assert gift_card.created_by_email == customer_user.email
+ assert order.user == customer_user
+
+
def test_customers_bulk_update_using_external_refs(
staff_api_client,
customer_users,
diff --git a/saleor/graphql/account/tests/mutations/account/test_confirm_account.py b/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
index 8b533b84ec..b89a528e13 100644
--- a/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
+++ b/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
@@ -36,7 +36,7 @@ def test_account_confirmation(
customer_user,
channel_USD,
):
- customer_user.is_active = False
+ customer_user.is_confirmed = False
customer_user.save()
variables = {
@@ -51,7 +51,7 @@ def test_account_confirmation(
customer_user.refresh_from_db()
match_orders_with_new_user_mock.assert_called_once_with(customer_user)
assign_gift_cards_mock.assert_called_once_with(customer_user)
- assert customer_user.is_active is True
+ assert customer_user.is_confirmed is True
@freeze_time("2018-05-31 12:00:01")
diff --git a/saleor/graphql/account/tests/mutations/account/test_send_confirmation_email.py b/saleor/graphql/account/tests/mutations/account/test_send_confirmation_email.py
new file mode 100644
index 0000000000..623ab09aa6
--- /dev/null
+++ b/saleor/graphql/account/tests/mutations/account/test_send_confirmation_email.py
@@ -0,0 +1,220 @@
+import datetime
+from unittest.mock import patch
+from urllib.parse import urlencode
+
+from django.contrib.auth.tokens import default_token_generator
+from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
+
+from ......account.error_codes import SendConfirmationEmailErrorCode
+from ......account.notifications import get_default_user_payload
+from ......core.notify_events import NotifyEventType
+from ......core.tests.utils import get_site_context_payload
+from ......core.utils.url import prepare_url
+from .....tests.utils import get_graphql_content
+
+SEND_CONFIRMATION_EMAIL_MUTATION = """
+ mutation SendConfirmationEmail(
+ $redirectUrl: String!, $channel: String!) {
+ sendConfirmationEmail(
+ redirectUrl: $redirectUrl, channel: $channel) {
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_send_confirmation_email(
+ mocked_notify,
+ user_api_client,
+ channel_PLN,
+ site_settings,
+):
+ # given
+ redirect_url = "https://www.example.com"
+ variables = {
+ "redirectUrl": redirect_url,
+ "channel": channel_PLN.slug,
+ }
+ user = user_api_client.user
+ user.is_confirmed = False
+ user.save(update_fields=["is_confirmed"])
+
+ # when
+ response = user_api_client.post_graphql(SEND_CONFIRMATION_EMAIL_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["sendConfirmationEmail"]
+ assert not data["errors"]
+
+ token = default_token_generator.make_token(user)
+ params = urlencode({"email": user.email, "token": token})
+ confirm_url = prepare_url(params, redirect_url)
+ expected_payload = {
+ "user": get_default_user_payload(user),
+ "token": token,
+ "confirm_url": confirm_url,
+ "recipient_email": user.email,
+ "channel_slug": channel_PLN.slug,
+ **get_site_context_payload(site_settings.site),
+ }
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_CONFIRMATION,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
+ )
+ user.refresh_from_db()
+ assert user.last_confirm_email_request == timezone.now()
+
+
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_send_confirmation_email_on_cooldown(
+ mocked_notify, user_api_client, channel_PLN
+):
+ # given
+ redirect_url = "https://www.example.com"
+ variables = {
+ "redirectUrl": redirect_url,
+ "channel": channel_PLN.slug,
+ }
+ user = user_api_client.user
+ user.last_confirm_email_request = timezone.now()
+ user.is_confirmed = False
+ user.save(update_fields=["last_confirm_email_request", "is_confirmed"])
+
+ # when
+ response = user_api_client.post_graphql(SEND_CONFIRMATION_EMAIL_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["sendConfirmationEmail"]["errors"]
+ assert errors == [
+ {
+ "field": None,
+ "message": "Confirmation email already requested",
+ "code": SendConfirmationEmailErrorCode.CONFIRMATION_ALREADY_REQUESTED.name,
+ }
+ ]
+ mocked_notify.assert_not_called()
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_send_confirmation_email_after_cooldown(user_api_client, channel_PLN, settings):
+ # given
+ redirect_url = "https://www.example.com"
+ variables = {
+ "redirectUrl": redirect_url,
+ "channel": channel_PLN.slug,
+ }
+
+ user = user_api_client.user
+ user.last_confirm_email_request = timezone.now() - datetime.timedelta(
+ seconds=settings.CONFIRMATION_EMAIL_LOCK_TIME
+ )
+ user.is_confirmed = False
+ user.save(update_fields=["last_confirm_email_request", "is_confirmed"])
+
+ # when
+ response = user_api_client.post_graphql(SEND_CONFIRMATION_EMAIL_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert len(content["data"]["sendConfirmationEmail"]["errors"]) == 0
+
+
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_send_confirmation_email_user_already_confirmed(
+ mocked_notify, user_api_client, channel_PLN
+):
+ # given
+ redirect_url = "https://www.example.com"
+ variables = {
+ "redirectUrl": redirect_url,
+ "channel": channel_PLN.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(SEND_CONFIRMATION_EMAIL_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["sendConfirmationEmail"]["errors"]
+ assert errors == [
+ {
+ "field": None,
+ "message": "User is already confirmed",
+ "code": SendConfirmationEmailErrorCode.ACCOUNT_CONFIRMED.name,
+ }
+ ]
+ mocked_notify.assert_not_called()
+
+
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+@override_settings(ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=False)
+def test_send_confirmation_email_confirmation_disabled(
+ mocked_notify, user_api_client, channel_PLN
+):
+ # given
+ redirect_url = "https://www.example.com"
+ variables = {
+ "redirectUrl": redirect_url,
+ "channel": channel_PLN.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(SEND_CONFIRMATION_EMAIL_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["sendConfirmationEmail"]["errors"]
+ assert errors == [
+ {
+ "field": None,
+ "message": "User is already confirmed",
+ "code": SendConfirmationEmailErrorCode.ACCOUNT_CONFIRMED.name,
+ }
+ ]
+ mocked_notify.assert_not_called()
+
+
+@override_settings(
+ ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=True,
+ ALLOWED_CLIENT_HOSTS=["localhost"],
+)
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_send_confirmation_email_generates_valid_token(
+ mocked_notify,
+ user_api_client,
+ channel_PLN,
+):
+ # given
+ redirect_url = "http://localhost:3000"
+ variables = {
+ "redirectUrl": redirect_url,
+ "channel": channel_PLN.slug,
+ }
+ user = user_api_client.user
+ user.is_confirmed = False
+ user.save()
+
+ # when
+ response = user_api_client.post_graphql(SEND_CONFIRMATION_EMAIL_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["sendConfirmationEmail"]["errors"]
+
+ token = mocked_notify.call_args.kwargs["payload"]["token"]
+ user.refresh_from_db()
+ assert default_token_generator.check_token(user, token)
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
index 8e2f98dec0..26512a00c9 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
@@ -156,7 +156,7 @@ def test_create_token_invalid_email(api_client, customer_user):
def test_create_token_unconfirmed_email(api_client, customer_user):
# given
variables = {"email": customer_user.email, "password": customer_user._password}
- customer_user.is_active = False
+ customer_user.is_confirmed = False
customer_user.save()
expected_error_code = AccountErrorCode.ACCOUNT_NOT_CONFIRMED.value.upper()
@@ -170,10 +170,54 @@ def test_create_token_unconfirmed_email(api_client, customer_user):
assert response_error["field"] == "email"
+@freeze_time("2020-03-18 12:00:00")
+def test_create_token_unconfirmed_user_unconfirmed_login_enabled(
+ api_client, customer_user, settings, site_settings
+):
+ # given
+ variables = {"email": customer_user.email, "password": customer_user._password}
+ site_settings.allow_login_without_confirmation = True
+ site_settings.save()
+ customer_user.is_confirmed = False
+ customer_user.save()
+
+ # when
+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["tokenCreate"]
+
+ user_email = data["user"]["email"]
+ assert customer_user.email == user_email
+ assert content["data"]["tokenCreate"]["errors"] == []
+
+ token = data["token"]
+ refreshToken = data["refreshToken"]
+
+ payload = jwt_decode(token)
+ assert payload["email"] == customer_user.email
+ assert payload["user_id"] == graphene.Node.to_global_id("User", customer_user.id)
+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_ACCESS
+ assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert payload["type"] == JWT_ACCESS_TYPE
+
+ payload = jwt_decode(refreshToken)
+ assert payload["email"] == customer_user.email
+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_REFRESH
+ assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert payload["type"] == JWT_REFRESH_TYPE
+ assert payload["token"] == customer_user.jwt_token_key
+ assert payload["iss"] == build_absolute_uri(reverse("api"))
+
+
def test_create_token_deactivated_user(api_client, customer_user):
# given
variables = {"email": customer_user.email, "password": customer_user._password}
customer_user.is_active = False
+ customer_user.is_confirmed = True
customer_user.last_login = datetime(2020, 3, 18, tzinfo=timezone.utc)
customer_user.save()
expected_error_code = AccountErrorCode.INACTIVE.value.upper()
diff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py b/saleor/graphql/account/tests/mutations/staff/test_customer_update.py
index 8ea2101a50..8d037c33c0 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_update.py
@@ -574,3 +574,63 @@ def test_customer_update_trigger_gift_card_search_vector_update(
for card in gift_card_list:
card.refresh_from_db()
assert card.search_index_dirty is True
+
+
+UPDATE_CUSTOMER_IS_CONFIRMED_MUTATION = """
+ mutation UpdateCustomer(
+ $id: ID!, $isConfirmed: Boolean) {
+ customerUpdate(id: $id, input: {
+ isConfirmed: $isConfirmed,
+ }) {
+ errors {
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_customer_confirm_assign_gift_cards_and_orders(
+ staff_api_client,
+ staff_user,
+ customer_user,
+ address,
+ gift_card,
+ order,
+ permission_manage_users,
+):
+ # given
+ query = UPDATE_CUSTOMER_IS_CONFIRMED_MUTATION
+
+ customer_user.is_confirmed = False
+ customer_user.save()
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+
+ gift_card.created_by = None
+ gift_card.created_by_email = customer_user.email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+
+ order.user = None
+ order.user_email = customer_user.email
+ order.save(update_fields=["user_email", "user"])
+
+ variables = {
+ "id": user_id,
+ "isConfirmed": True,
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+
+ # then
+ gift_card.refresh_from_db()
+ customer_user.refresh_from_db()
+ assert gift_card.created_by == customer_user
+ assert gift_card.created_by_email == customer_user.email
+
+ order.refresh_from_db()
+ assert order.user == customer_user
diff --git a/saleor/graphql/account/tests/queries/test_user.py b/saleor/graphql/account/tests/queries/test_user.py
index 1b7105d002..f7d906b583 100644
--- a/saleor/graphql/account/tests/queries/test_user.py
+++ b/saleor/graphql/account/tests/queries/test_user.py
@@ -26,6 +26,7 @@ FULL_USER_QUERY = """
lastName
isStaff
isActive
+ isConfirmed
addresses {
id
isDefaultShippingAddress
@@ -160,6 +161,7 @@ def test_query_customer_user(
assert data["lastName"] == user.last_name
assert data["isStaff"] == user.is_staff
assert data["isActive"] == user.is_active
+ assert data["isConfirmed"] == user.is_confirmed
assert data["orders"]["totalCount"] == user.orders.count()
assert data["avatar"]["url"]
assert data["languageCode"] == settings.LANGUAGE_CODE.upper()
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 968a3e75f3..c1f7140607 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -30,6 +30,7 @@ from ..core.descriptions import (
ADDED_IN_38,
ADDED_IN_310,
ADDED_IN_314,
+ ADDED_IN_315,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
@@ -301,6 +302,10 @@ class User(ModelObjectType[models.User]):
is_active = graphene.Boolean(
required=True, description="Determine if the user is active."
)
+ is_confirmed = graphene.Boolean(
+ required=True,
+ description="Determines if user has confirmed email." + ADDED_IN_315,
+ )
addresses = NonNullList(
Address, description="List of all user's addresses.", required=True
)
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 04a55ce72b..54df61f735 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -311,6 +311,11 @@ ProductVariantBulkErrorCode.doc_category = DOC_CATEGORY_PRODUCTS
CollectionErrorCode = graphene.Enum.from_enum(product_error_codes.CollectionErrorCode)
CollectionErrorCode.doc_category = DOC_CATEGORY_PRODUCTS
+SendConfirmationEmailErrorCode = graphene.Enum.from_enum(
+ account_error_codes.SendConfirmationEmailErrorCode
+)
+SendConfirmationEmailErrorCode.doc_category = DOC_CATEGORY_USERS
+
ShopErrorCode = graphene.Enum.from_enum(core_error_codes.ShopErrorCode)
ShippingErrorCode = graphene.Enum.from_enum(shipping_error_codes.ShippingErrorCode)
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 93d019cc94..0cde816d55 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -51,6 +51,7 @@ from .common import (
ProductVariantBulkError,
ProductVariantBulkTranslateError,
ProductWithoutVariantError,
+ SendConfirmationEmailError,
SeoInput,
ShippingError,
ShopError,
@@ -143,6 +144,7 @@ __all__ = [
"ProductVariantBulkError",
"ProductVariantBulkTranslateError",
"ReducedRate",
+ "SendConfirmationEmailError",
"SeoInput",
"ShippingError",
"ShopError",
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 0ac4a91ce2..d501ec1628 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -70,6 +70,7 @@ from ..enums import (
ProductTranslateErrorCode,
ProductVariantBulkErrorCode,
ProductVariantTranslateErrorCode,
+ SendConfirmationEmailErrorCode,
ShippingErrorCode,
ShopErrorCode,
StockBulkUpdateErrorCode,
@@ -183,6 +184,13 @@ class AccountError(Error):
doc_category = DOC_CATEGORY_USERS
+class SendConfirmationEmailError(Error):
+ code = SendConfirmationEmailErrorCode(description="The error code.", required=True)
+
+ class Meta:
+ doc_category = DOC_CATEGORY_USERS
+
+
class AppError(Error):
code = AppErrorCode(description="The error code.", required=True)
permissions = NonNullList(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c8a41e2aa6..2807f33bf2 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -9586,6 +9586,15 @@ type Shop implements ObjectWithMetadata {
"""
enableAccountConfirmationByEmail: Boolean
+ """
+ Determines if user can login without confirmation when `enableAccountConfrimation` is enabled.
+
+ Added in Saleor 3.15.
+
+ Requires one of the following permissions: MANAGE_SETTINGS.
+ """
+ allowLoginWithoutConfirmation: Boolean
+
"""
Resource limitations and current usage if any set for a shop
@@ -9760,6 +9769,13 @@ type User implements Node & ObjectWithMetadata @doc(category: "Users") {
"""Determine if the user is active."""
isActive: Boolean!
+ """
+ Determines if user has confirmed email.
+
+ Added in Saleor 3.15.
+ """
+ isConfirmed: Boolean!
+
"""List of all user's addresses."""
addresses: [Address!]!
@@ -17836,6 +17852,27 @@ type Mutation {
redirectUrl: String!
): RequestPasswordReset @doc(category: "Users") @webhookEventsInfo(asyncEvents: [NOTIFY_USER], syncEvents: [])
+ """
+ Sends a notification confirmation.
+
+ Added in Saleor 3.15.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: AUTHENTICATED_USER.
+
+ Triggers the following webhook events:
+ - NOTIFY_USER (async): A notification for account confirmation.
+ - ACCOUNT_CONFIRMATION_REQUESTED (async): An account confirmation was requested. This event is always sent regardless of settings.
+ """
+ sendConfirmationEmail(
+ """Slug of a channel which will be used for notify user."""
+ channel: String!
+
+ """Base of frontend URL that will be needed to create confirmation URL."""
+ redirectUrl: String!
+ ): SendConfirmationEmail @doc(category: "Users") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, ACCOUNT_CONFIRMATION_REQUESTED], syncEvents: [])
+
"""Confirm user account with token sent by email during registration."""
confirmAccount(
"""E-mail of the user performing account confirmation."""
@@ -17983,11 +18020,12 @@ type Mutation {
Triggers the following webhook events:
- CUSTOMER_CREATED (async): A new customer account was created.
- NOTIFY_USER (async): A notification for account confirmation.
+ - ACCOUNT_CONFIRMATION_REQUESTED (async): An user confirmation was requested. This event is always sent regardless of settings.
"""
accountRegister(
"""Fields required to create a user."""
input: AccountRegisterInput!
- ): AccountRegister @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_CREATED, NOTIFY_USER], syncEvents: [])
+ ): AccountRegister @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_CREATED, NOTIFY_USER, ACCOUNT_CONFIRMATION_REQUESTED], syncEvents: [])
"""
Updates the account of the logged-in user.
@@ -19312,6 +19350,13 @@ input ShopSettingsInput {
"""
enableAccountConfirmationByEmail: Boolean
+ """
+ Enable possibility to login without account confirmation.
+
+ Added in Saleor 3.15.
+ """
+ allowLoginWithoutConfirmation: Boolean
+
"""
Shop public metadata.
@@ -28002,6 +28047,44 @@ type RequestPasswordReset @doc(category: "Users") @webhookEventsInfo(asyncEvents
errors: [AccountError!]!
}
+"""
+Sends a notification confirmation.
+
+Added in Saleor 3.15.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires one of the following permissions: AUTHENTICATED_USER.
+
+Triggers the following webhook events:
+- NOTIFY_USER (async): A notification for account confirmation.
+- ACCOUNT_CONFIRMATION_REQUESTED (async): An account confirmation was requested. This event is always sent regardless of settings.
+"""
+type SendConfirmationEmail @doc(category: "Users") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, ACCOUNT_CONFIRMATION_REQUESTED], syncEvents: []) {
+ errors: [SendConfirmationEmailError!]!
+}
+
+type SendConfirmationEmailError @doc(category: "Users") {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: SendConfirmationEmailErrorCode!
+}
+
+"""An enumeration."""
+enum SendConfirmationEmailErrorCode @doc(category: "Users") {
+ INVALID
+ ACCOUNT_CONFIRMED
+ CONFIRMATION_ALREADY_REQUESTED
+ MISSING_CHANNEL_SLUG
+}
+
"""Confirm user account with token sent by email during registration."""
type ConfirmAccount @doc(category: "Users") {
"""An activated user account."""
@@ -28138,8 +28221,9 @@ Register a new user.
Triggers the following webhook events:
- CUSTOMER_CREATED (async): A new customer account was created.
- NOTIFY_USER (async): A notification for account confirmation.
+- ACCOUNT_CONFIRMATION_REQUESTED (async): An user confirmation was requested. This event is always sent regardless of settings.
"""
-type AccountRegister @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_CREATED, NOTIFY_USER], syncEvents: []) {
+type AccountRegister @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_CREATED, NOTIFY_USER, ACCOUNT_CONFIRMATION_REQUESTED], syncEvents: []) {
"""Informs whether users need to confirm their email address."""
requiresConfirmation: Boolean
accountErrors: [AccountError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
@@ -28365,6 +28449,13 @@ input UserCreateInput @doc(category: "Users") {
"""
externalReference: String
+ """
+ User account is confirmed.
+
+ Added in Saleor 3.15.
+ """
+ isConfirmed: Boolean
+
"""
URL of a view where users should be redirected to set the password. URL in RFC 1808 format.
"""
@@ -28436,6 +28527,13 @@ input CustomerInput @doc(category: "Users") {
Added in Saleor 3.10.
"""
externalReference: String
+
+ """
+ User account is confirmed.
+
+ Added in Saleor 3.15.
+ """
+ isConfirmed: Boolean
}
"""
diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.py
index e149d948b2..77f29ab11d 100644
--- a/saleor/graphql/shop/mutations/shop_settings_update.py
+++ b/saleor/graphql/shop/mutations/shop_settings_update.py
@@ -81,6 +81,11 @@ class ShopSettingsInput(graphene.InputObjectType):
enable_account_confirmation_by_email = graphene.Boolean(
description="Enable automatic account confirmation by email." + ADDED_IN_314
)
+ allow_login_without_confirmation = graphene.Boolean(
+ description=(
+ "Enable possibility to login without account confirmation." + ADDED_IN_315
+ )
+ )
metadata = common_types.NonNullList(
MetadataInput,
description="Shop public metadata." + ADDED_IN_315,
diff --git a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
index fd78b70635..72c4fefdf2 100644
--- a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
+++ b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
@@ -22,6 +22,7 @@ SHOP_SETTINGS_UPDATE_MUTATION = """
reserveStockDurationAnonymousUser
reserveStockDurationAuthenticatedUser
limitQuantityPerCheckout
+ allowLoginWithoutConfirmation
}
errors {
field
@@ -83,6 +84,7 @@ def test_shop_settings_mutation(
"chargeTaxesOnShipping": new_charge_taxes_on_shipping,
"fulfillmentAllowUnpaid": False,
"enableAccountConfirmationByEmail": False,
+ "allowLoginWithoutConfirmation": True,
}
}
@@ -100,11 +102,13 @@ def test_shop_settings_mutation(
assert data["fulfillmentAutoApprove"] is True
assert data["fulfillmentAllowUnpaid"] is False
assert data["enableAccountConfirmationByEmail"] is False
+ assert data["allowLoginWithoutConfirmation"] is True
site_settings.refresh_from_db()
assert not site_settings.include_taxes_in_prices
assert site_settings.charge_taxes_on_shipping == new_charge_taxes_on_shipping
assert site_settings.enable_account_confirmation_by_email is False
+ assert site_settings.allow_login_without_confirmation is True
def test_shop_reservation_settings_mutation(
diff --git a/saleor/graphql/shop/tests/queries/test_shop.py b/saleor/graphql/shop/tests/queries/test_shop.py
index 36abaa6f55..f5d302080e 100644
--- a/saleor/graphql/shop/tests/queries/test_shop.py
+++ b/saleor/graphql/shop/tests/queries/test_shop.py
@@ -850,3 +850,27 @@ def test_query_countries_filter_shiping_zones_attached_none(
# then
assert len(data) == len(countries)
+
+
+def test_query_allow_login_without_confirmation(
+ staff_api_client, permission_manage_settings, site_settings
+):
+ # given
+ query = """
+ query {
+ shop {
+ allowLoginWithoutConfirmation
+ }
+ }
+ """
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_settings]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ assert content["data"]["shop"]["allowLoginWithoutConfirmation"] == (
+ site_settings.allow_login_without_confirmation
+ )
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index d2da7fc842..8a128c725b 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -20,6 +20,7 @@ from ..core.descriptions import (
ADDED_IN_31,
ADDED_IN_35,
ADDED_IN_314,
+ ADDED_IN_315,
DEPRECATED_IN_3X_FIELD,
DEPRECATED_IN_3X_INPUT,
)
@@ -312,6 +313,14 @@ class Shop(graphene.ObjectType):
),
permissions=[SitePermissions.MANAGE_SETTINGS],
)
+ allow_login_without_confirmation = PermissionsField(
+ graphene.Boolean,
+ description=(
+ "Determines if user can login without confirmation when "
+ "`enableAccountConfrimation` is enabled." + ADDED_IN_315
+ ),
+ permissions=[SitePermissions.MANAGE_SETTINGS],
+ )
limits = PermissionsField(
LimitInfo,
required=True,
@@ -557,6 +566,11 @@ class Shop(graphene.ObjectType):
def resolve_enable_account_confirmation_by_email(_, _info, site):
return site.settings.enable_account_confirmation_by_email
+ @staticmethod
+ @load_site_callback
+ def resolve_allow_login_without_confirmation(_, _info, site):
+ return site.settings.allow_login_without_confirmation
+
@staticmethod
def resolve_limits(_, _info):
return LimitInfo(current_usage=Limits(), allowed_usage=Limits())
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index e8ee59ac90..0f0fb136c3 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -33,6 +33,7 @@ from ...graphql.account.mutations.authentication.utils import (
from ...order.utils import match_orders_with_new_user
from ...permission.enums import get_permission_names, get_permissions_from_codenames
from ...permission.models import Permission
+from ...site.models import Site
from ..error_codes import PluginErrorCode
from ..models import PluginConfiguration
from . import PLUGIN_ID
@@ -391,6 +392,7 @@ def get_or_create_user_from_payload(
defaults_create = {
"is_active": True,
+ "is_confirmed": True,
"email": user_email,
"first_name": payload.get("given_name", ""),
"last_name": payload.get("family_name", ""),
@@ -412,7 +414,8 @@ def get_or_create_user_from_payload(
defaults=defaults_create,
)
- if not user.is_active: # it is true only if we fetch disabled user.
+ site_settings = Site.objects.get_current().settings
+ if not user.can_login(site_settings): # it is true only if we fetch disabled user.
raise AuthenticationError("Unable to log in.")
_update_user_details(
@@ -481,8 +484,10 @@ def get_user_from_token(claims: CodeIDToken) -> User:
user_email = claims.get("email")
if not user_email:
raise AuthenticationError("Missing user's email.")
- user = User.objects.filter(email=user_email, is_active=True).first()
- if not user:
+
+ site_settings = Site.objects.get_current().settings
+ user = User.objects.filter(email=user_email).first()
+ if not user or not user.can_login(site_settings):
raise AuthenticationError("User does not exist.")
return user
diff --git a/saleor/settings.py b/saleor/settings.py
index 8a41380525..ec2ce90057 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -821,3 +821,8 @@ WEBHOOK_CELERY_QUEUE_NAME = os.environ.get("WEBHOOK_CELERY_QUEUE_NAME", None)
RESET_PASSWORD_LOCK_TIME = parse(
os.environ.get("RESET_PASSWORD_LOCK_TIME", "15 minutes")
)
+
+# Lock time for request confirmation email mutation per user
+CONFIRMATION_EMAIL_LOCK_TIME = parse(
+ os.environ.get("CONFIRMATION_EMAIL_LOCK_TIME", "15 minutes")
+)
diff --git a/saleor/site/migrations/0040_sitesettings_allow_login_without_confirmation.py b/saleor/site/migrations/0040_sitesettings_allow_login_without_confirmation.py
new file mode 100644
index 0000000000..7876844dc8
--- /dev/null
+++ b/saleor/site/migrations/0040_sitesettings_allow_login_without_confirmation.py
@@ -0,0 +1,23 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("site", "0039_auto_20230615_1754"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="allow_login_without_confirmation",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE site_sitesettings
+ ALTER COLUMN allow_login_without_confirmation
+ SET DEFAULT false;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 4f09d1726f..1e85625407 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -66,6 +66,7 @@ class SiteSettings(ModelWithMetadata):
)
default_mail_sender_address = models.EmailField(blank=True, null=True)
enable_account_confirmation_by_email = models.BooleanField(default=True)
+ allow_login_without_confirmation = models.BooleanField(default=False)
customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)
fulfillment_auto_approve = models.BooleanField(default=True)
fulfillment_allow_unpaid = models.BooleanField(default=True)