Skip to content

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

Fix CVE-2026-44472

Mikail Kocak5110542c1649
diff --git a/saleor/graphql/account/mutations/account/confirm_account.py b/saleor/graphql/account/mutations/account/confirm_account.py
index ab5cd5a391..cbcf14f045 100644
--- a/saleor/graphql/account/mutations/account/confirm_account.py
+++ b/saleor/graphql/account/mutations/account/confirm_account.py
@@ -1,8 +1,13 @@
+import logging
+from typing import Any
+
import graphene
+from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from .....account import models
from .....account.error_codes import AccountErrorCode
+from .....account.throttling import authenticate_with_throttling
from .....core.tokens import (
account_confirm_token_generator,
legacy_account_confirm_token_generator,
@@ -10,8 +15,10 @@ from .....core.tokens import (
)
from .....giftcard.utils import assign_user_gift_cards
from .....order.utils import match_orders_with_new_user
+from .....site import AccountConfirmMode
+from .....site.models import SiteSettings
from .....webhook.event_types import WebhookEventAsyncType
-from ....core import ResolveInfo
+from ....core import ResolveInfo, SaleorContext
from ....core.doc_category import DOC_CATEGORY_USERS
from ....core.mutations import BaseMutation
from ....core.types import AccountError
@@ -22,6 +29,9 @@ from ...types import User
INVALID_TOKEN = "Invalid or expired token."
+logger = logging.getLogger(__name__)
+
+
class ConfirmAccount(BaseMutation):
user = graphene.Field(User, description="An activated user account.")
@@ -34,6 +44,14 @@ class ConfirmAccount(BaseMutation):
description="E-mail of the user performing account confirmation.",
required=True,
)
+ password = graphene.String(
+ description=(
+ "Password of the user confirming their account. Required "
+ "when `REQUIRED_PASSWORD` mode is enabled in shop settings. "
+ "Learn more at "
+ "https://docs.saleor.io/upgrade-guides/core/migrate-account-merging"
+ )
+ )
class Meta:
description = (
@@ -49,6 +67,81 @@ class ConfirmAccount(BaseMutation):
),
]
+ @staticmethod
+ def maybe_merge_account(
+ *,
+ request: SaleorContext,
+ user: models.User,
+ site_settings: SiteSettings,
+ data: dict[str, Any],
+ ) -> None:
+ """Merge the account if the user confirms their knowledge of the password.
+
+ Note: having different response times and different error messages
+ which would reveal the user's existence is not a security issue
+ in this context. We already verified the user has the account
+ confirmation token. We are only verifying whether they know the
+ password of that account and thus we're trying to ensure they
+ aren't being tricked by someone.
+ """
+ if (
+ site_settings.account_confirm_merge_mode
+ == AccountConfirmMode.MERGE_DISABLED
+ ):
+ return
+
+ if (
+ site_settings.account_confirm_merge_mode
+ != AccountConfirmMode.REQUIRE_PASSWORD
+ ):
+ raise ValueError(
+ "Received an unknown account merging mode",
+ site_settings.account_confirm_merge_mode,
+ )
+
+ password: str | None = data.get("password")
+
+ # development safeguard due to Graphene automatically casting non-string
+ # to strings
+ assert password is None or isinstance(password, str)
+
+ if not password:
+ raise ValidationError(
+ {
+ "password": ValidationError(
+ "Password is required", code=AccountErrorCode.REQUIRED.value
+ )
+ }
+ )
+
+ auth_user = authenticate_with_throttling(
+ request=request, email=user.email, password=password
+ )
+
+ if not auth_user or auth_user != user:
+ # This should be impossible, but if it occurs, then don't crash, just
+ # log a fatal error so someone can look into and just return "Invalid password"
+ # to the user
+ # Note: auth_user can be null if the password is wrong, in which case we
+ # shouldn't throw an error in logs
+ if auth_user is not None and auth_user != user:
+ logger.exception(
+ "Unexpected user mismatch during authentication in"
+ " confirmAccount() mutation"
+ )
+
+ raise ValidationError(
+ {
+ "password": ValidationError(
+ "Invalid password", code=AccountErrorCode.INVALID.value
+ )
+ }
+ )
+
+ # User proved they possess their password, thus it's safe to merge
+ match_orders_with_new_user(user)
+ assign_user_gift_cards(user)
+
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
error = False
@@ -77,12 +170,19 @@ class ConfirmAccount(BaseMutation):
}
)
+ cls.maybe_merge_account(
+ request=info.context,
+ user=user,
+ # Note: doesn't use Site.objects.get_current().settings as it will
+ # retrieve stale data (in-memory cache)
+ site_settings=SiteSettings.objects.get(site=Site.objects.get_current()),
+ data=data,
+ )
+
+ user.is_active = True
user.is_confirmed = True
user.save(update_fields=["is_confirmed", "updated_at"])
- match_orders_with_new_user(user)
- assign_user_gift_cards(user)
-
cls.post_save_action(info, user)
return ConfirmAccount(user=user)
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 a6d1e4b9d3..c68322c093 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
@@ -18,6 +18,7 @@ CUSTOMER_BULK_UPDATE_MUTATION = """
$errorPolicy: ErrorPolicyEnum
){
customerBulkUpdate(customers: $customers, errorPolicy: $errorPolicy){
+ errors { code message }
results{
errors {
path
@@ -27,6 +28,7 @@ CUSTOMER_BULK_UPDATE_MUTATION = """
customer{
id
firstName
+ email
defaultShippingAddress {
metadata {
key
@@ -1143,3 +1145,107 @@ def test_bulk_metadata_and_customer_data_update_sends_both_webhooks(
# Verify both webhooks were sent
assert mocked_customer_updated.call_count == 2
assert mocked_customer_metadata_updated.call_count == 2
+
+
+def test_customer_update_existing_user_does_not_merge_with_existing_account(
+ staff_api_client,
+ staff_user,
+ customer_user,
+ gift_card,
+ order,
+ permission_manage_users,
+):
+ """Ensure customerBulkUpdate() doesn't allowing merging with existing users.
+
+ When setting the email address of a customer to an email address that already
+ is associated to an account, it should reject the change and shouldn't merge
+ the account (i.e., orders and giftcards shouldn't associated).
+
+ When there is no account associated, then it should automatically merge.
+ """
+ staff_user.user_permissions.add(permission_manage_users)
+
+ user_for_update = customer_user
+ existing_email = "[email protected]"
+ existing_user = models.User.objects.create(email=existing_email)
+
+ assert user_for_update.email != existing_user.email
+
+ # Create anonymous objects assigned to the targeted email
+ order.user = gift_card.created_by = None
+ order.user_email = gift_card.created_by_email = existing_email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+ order.save(update_fields=["user", "user_email"])
+
+ # When attempting to merge onto an existing account, it should reject
+ # the request, and shouldn't assign the anonymous objects.
+ query = CUSTOMER_BULK_UPDATE_MUTATION
+ variables = {
+ "customers": [
+ {
+ "id": graphene.Node.to_global_id("User", user_for_update.pk),
+ "input": {"email": existing_email},
+ }
+ ],
+ "errorPolicy": ErrorPolicyEnum.REJECT_EVERYTHING.name,
+ }
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ root_errors = content["data"]["customerBulkUpdate"]["errors"]
+ assert root_errors == [], "shouldn't have return errors at the root"
+ results = content["data"]["customerBulkUpdate"]["results"]
+ assert len(results) == 1
+ assert results == [
+ {
+ "customer": None,
+ "errors": [
+ {
+ "code": "UNIQUE",
+ "path": "input.email",
+ "message": "User with this Email already exists.",
+ }
+ ],
+ }
+ ]
+
+ customer_user.refresh_from_db(fields=("email",))
+ assert customer_user.email != existing_email, "shoudln't have updated the customer"
+
+ gift_card.refresh_from_db(fields=("created_by", "created_by_email"))
+ assert gift_card.created_by is None, "shouldn't have merged the gift card"
+ assert gift_card.created_by_email == existing_email, (
+ "shouldn't have changed the email"
+ )
+
+ order.refresh_from_db(fields=("user", "user_email"))
+ assert order.user is None, "shouldn't have merged the gift card"
+ assert order.user_email == existing_email, "shouldn't have changed the email"
+
+ # sanity check: if the conflicting user is gone, the same update should merge
+ existing_user.delete()
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ root_errors = content["data"]["customerBulkUpdate"]["errors"]
+ assert root_errors == [], "shouldn't have return errors at the root"
+ results = content["data"]["customerBulkUpdate"]["results"]
+ assert len(results) == 1
+ assert len(results[0]["errors"]) == 0, "shouldn't have failed the bulk update"
+
+ result_customer = results[0]["customer"]
+ assert result_customer is not None, "should have returned the updated object"
+ assert result_customer["email"] == existing_email, "should have updated the email"
+
+ customer_user.refresh_from_db(fields=("email",))
+ assert customer_user.email == existing_email, "should have updated the customer"
+
+ gift_card.refresh_from_db(fields=("created_by", "created_by_email"))
+ assert gift_card.created_by == customer_user, "should have merged the gift card"
+ assert gift_card.created_by_email == existing_email, (
+ "shouldn't have changed the email"
+ )
+
+ order.refresh_from_db(fields=("user", "user_email"))
+ assert order.user == customer_user, "should have merged the gift card"
+ assert order.user_email == existing_email, "shouldn't have changed the email"
diff --git a/saleor/graphql/account/tests/mutations/account/conftest.py b/saleor/graphql/account/tests/mutations/account/conftest.py
index 980d7f2a47..b2f5f874e0 100644
--- a/saleor/graphql/account/tests/mutations/account/conftest.py
+++ b/saleor/graphql/account/tests/mutations/account/conftest.py
@@ -1,3 +1,7 @@
+from unittest import mock
+
+import pytest
+
REQUEST_EMAIL_CHANGE_QUERY = """
mutation requestEmailChange(
$password: String!, $new_email: String!, $redirect_url: String!, $channel:String
@@ -34,3 +38,11 @@ mutation emailUpdate($token: String!, $channel: String) {
}
}
"""
+
+
+def throttling_disabled():
+ """Disable password throttling."""
+
+ with mock.patch("saleor.account.throttling.cache"):
+ yield
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 9df5ef037b..b48bc39379 100644
--- a/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
+++ b/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
@@ -1,5 +1,9 @@
+import functools
+from typing import Any
+from unittest import mock
from unittest.mock import patch
+import pytest
from freezegun import freeze_time
from ......account.error_codes import AccountErrorCode
@@ -8,14 +12,16 @@ from ......core.tokens import (
legacy_account_confirm_token_generator,
password_reset_token_generator,
)
+from ......site import AccountConfirmMode
from .....tests.utils import get_graphql_content
CONFIRM_ACCOUNT_MUTATION = """
- mutation ConfirmAccount($email: String!, $token: String!) {
- confirmAccount(email: $email, token: $token) {
+ mutation ConfirmAccount($email: String!, $token: String!, $password: String) {
+ confirmAccount(email: $email, token: $token, password: $password) {
errors {
field
code
+ message
}
user {
id
@@ -25,41 +31,83 @@ CONFIRM_ACCOUNT_MUTATION = """
}
"""
+WRONG_PASSWORD_ERROR = {
+ "field": "password",
+ "code": "INVALID",
+ "message": "Invalid password",
+}
+
+
+def account_merging_enabled(site_settings):
+ # TODO: in Saleor 3.24.0, replace this with `assert
+ # site_settings.account_confirm_merge_mode == AccountConfirmMode.REQUIRE_PASSWORD`
+ site_settings.account_confirm_merge_mode = AccountConfirmMode.REQUIRE_PASSWORD
+ site_settings.save(update_fields=("account_confirm_merge_mode",))
+
@freeze_time("2018-05-31 12:00:01")
-@patch(
- "saleor.graphql.account.mutations.account.confirm_account.assign_user_gift_cards"
-)
-@patch(
- "saleor.graphql.account.mutations.account.confirm_account.match_orders_with_new_user"
-)
@patch("saleor.plugins.manager.PluginsManager.account_confirmed")
+ ("merge_mode", "should_merge"),
+ [
+ (AccountConfirmMode.REQUIRE_PASSWORD, True),
+ (AccountConfirmMode.MERGE_DISABLED, False),
+ ],
+)
def test_account_confirmation(
- match_orders_with_new_user_mock,
- assign_gift_cards_mock,
mocked_account_confirmed,
+ merge_mode: str,
+ should_merge: bool,
api_client,
customer_user,
channel_USD,
+ site_settings,
+ order,
+ gift_card,
+ throttling_disabled,
):
+ site_settings.account_confirm_merge_mode = merge_mode
+ site_settings.save(update_fields=("account_confirm_merge_mode",))
+
customer_user.is_confirmed = False
customer_user.save()
+ # Create anonymous objects assigned to the targeted email
+ order.user = gift_card.created_by = None
+ order.user_email = gift_card.created_by_email = customer_user.email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+ order.save(update_fields=["user", "user_email"])
+
variables = {
"email": customer_user.email,
"token": account_confirm_token_generator.make_token(customer_user),
"channel": channel_USD.slug,
+ "password": "password",
}
response = api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
content = get_graphql_content(response)
assert not content["data"]["confirmAccount"]["errors"]
assert content["data"]["confirmAccount"]["user"]["email"] == customer_user.email
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_confirmed is True
+
+ assert customer_user.is_confirmed is True, "should have confirmed the the user"
mocked_account_confirmed.assert_called_once_with(customer_user)
+ gift_card.refresh_from_db(fields=("created_by", "created_by_email"))
+ order.refresh_from_db(fields=("user", "user_email"))
+
+ # In both cases, it shouldn't touch the email address
+ assert gift_card.created_by_email == customer_user.email
+ assert order.user_email == customer_user.email
+
+ if should_merge is True:
+ assert order.user == customer_user, "should have merged the order"
+ assert gift_card.created_by == customer_user, "should have merged the gift card"
+ else:
+ assert order.user is None, "shouldn't have merged the order"
+ assert gift_card.created_by is None, "shouldn't have merged the gift card"
+
@freeze_time("2018-05-31 12:00:01")
@patch(
@@ -74,6 +122,7 @@ def test_account_confirmation_invalid_user(
user_api_client,
customer_user,
channel_USD,
+ account_merging_enabled,
):
variables = {
"email": "[email protected]",
@@ -91,6 +140,231 @@ def test_account_confirmation_invalid_user(
assign_gift_cards_mock.assert_not_called()
+ ("_case", "input_data", "expected_errors"),
+ [
+ (
+ "Invalid password",
+ {"password": "hunter2"},
+ [WRONG_PASSWORD_ERROR],
+ ),
+ (
+ "Missing 'password' field",
+ {},
+ [
+ {
+ "field": "password",
+ "code": "REQUIRED",
+ "message": "Password is required",
+ }
+ ],
+ ),
+ (
+ "Empty password",
+ {"password": ""},
+ [
+ {
+ "field": "password",
+ "code": "REQUIRED",
+ "message": "Password is required",
+ }
+ ],
+ ),
+ (
+ "Null password",
+ {"password": None},
+ [
+ {
+ "field": "password",
+ "code": "REQUIRED",
+ "message": "Password is required",
+ }
+ ],
+ ),
+ (
+ # Note: per GraphQL specs, Graphene is automatically casting non-string
+ # values to a string (https://spec.graphql.org/June2018/#sec-String)
+ # ("GraphQL servers may coerce non‐string raw values to String [...]")
+ "Password is not a string",
+ {"password": True},
+ [WRONG_PASSWORD_ERROR],
+ ),
+ ],
+)
+def test_account_confirmation_requires_valid_password_when_require_password_mode(
+ _case: str,
+ input_data: dict[str, Any],
+ expected_errors: list[dict[str, Any]],
+ api_client,
+ customer_user,
+ channel_USD,
+ site_settings,
+ order,
+ gift_card,
+ throttling_disabled,
+):
+ """A valid password is required when using the REQUIRE_PASSWORD mode."""
+
+ site_settings.account_confirm_merge_mode = AccountConfirmMode.REQUIRE_PASSWORD
+ site_settings.save(update_fields=("account_confirm_merge_mode",))
+
+ customer_user.is_confirmed = False
+ customer_user.save(update_fields=("is_confirmed",))
+
+ # Create anonymous objects assigned to the targeted email
+ order.user = gift_card.created_by = None
+ order.user_email = gift_card.created_by_email = customer_user.email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+ order.save(update_fields=["user", "user_email"])
+
+ variables = {
+ "email": customer_user.email,
+ "token": account_confirm_token_generator.make_token(customer_user),
+ "channel": channel_USD.slug,
+ **input_data,
+ }
+
+ with mock.patch("saleor.account.throttling.cache", side_effect=1):
+ response = api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["confirmAccount"]["errors"] == expected_errors
+ assert content["data"]["confirmAccount"]["user"] is None
+ customer_user.refresh_from_db(fields=("is_confirmed",))
+
+ assert customer_user.is_confirmed is False, "shouldn't have confirmed the the user"
+
+ # Ensure it didn't merge anonymous objects
+ gift_card.refresh_from_db(fields=("created_by", "created_by_email"))
+ order.refresh_from_db(fields=("user", "user_email"))
+ assert gift_card.created_by_email == customer_user.email
+ assert order.user_email == customer_user.email
+ assert order.user is None, "shouldn't have merged the order"
+ assert gift_card.created_by is None, "shouldn't have merged the gift card"
+
+
+ ("_case", "input_data"),
+ [
+ (
+ # When MERGE_DISABLED is set and the user passes an invalid password,
+ # we expect the password to not be verified. This ensures a smooth
+ # transition from MERGE_DISABLED to REQUIRE_PASSWORD
+ "Invalid password -> shouldn't return an error",
+ {"password": "incorrect"},
+ ),
+ (
+ "Missing 'password' field -> no error",
+ {},
+ ),
+ (
+ "Empty password -> no error",
+ {"password": ""},
+ ),
+ (
+ "Null password -> no error",
+ {"password": None},
+ ),
+ (
+ "Password is not a string -> no error",
+ {"password": True},
+ ),
+ ],
+)
+def test_account_confirmation_no_password_required_when_merging_disabled(
+ _case: str,
+ input_data: dict[str, Any],
+ api_client,
+ customer_user,
+ channel_USD,
+ site_settings,
+ order,
+ gift_card,
+ throttling_disabled,
+):
+ """A password isn't required when using the MERGE_DISABLED mode."""
+
+ site_settings.account_confirm_merge_mode = AccountConfirmMode.MERGE_DISABLED
+ site_settings.save(update_fields=("account_confirm_merge_mode",))
+
+ customer_user.is_confirmed = False
+ customer_user.save(update_fields=("is_confirmed",))
+
+ # Create anonymous objects assigned to the targeted email
+ order.user = gift_card.created_by = None
+ order.user_email = gift_card.created_by_email = customer_user.email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+ order.save(update_fields=["user", "user_email"])
+
+ variables = {
+ "email": customer_user.email,
+ "token": account_confirm_token_generator.make_token(customer_user),
+ "channel": channel_USD.slug,
+ **input_data,
+ }
+
+ with mock.patch("saleor.account.throttling.cache", side_effect=1):
+ response = api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["confirmAccount"]["errors"] == []
+ resp_user = content["data"]["confirmAccount"]["user"]
+ assert resp_user is not None
+ assert resp_user["email"] is not None
+ assert resp_user["email"] == customer_user.email
+ customer_user.refresh_from_db(fields=("is_confirmed",))
+
+ assert customer_user.is_confirmed is True, "should have confirmed the the user"
+
+ # Ensure it didn't merge anonymous objects
+ gift_card.refresh_from_db(fields=("created_by", "created_by_email"))
+ order.refresh_from_db(fields=("user", "user_email"))
+ assert gift_card.created_by_email == customer_user.email
+ assert order.user_email == customer_user.email
+ assert order.user is None, "shouldn't have merged the order"
+ assert gift_card.created_by is None, "shouldn't have merged the gift card"
+
+
+def test_account_confirmation_rate_limits_password(
+ cache_clear,
+ api_client,
+ customer_user,
+ channel_USD,
+ account_merging_enabled,
+):
+ """Account confirmation attempts with a valid token should be rate-limited."""
+
+ customer_user.is_confirmed = False
+ customer_user.save(update_fields=("is_confirmed",))
+
+ variables = {
+ "email": customer_user.email,
+ "token": account_confirm_token_generator.make_token(customer_user),
+ "channel": channel_USD.slug,
+ "password": "invalid",
+ }
+
+ send_request = functools.partial(
+ api_client.post_graphql, CONFIRM_ACCOUNT_MUTATION, variables
+ )
+
+ # 1st request should work (wrong password error)
+ content = get_graphql_content(send_request())
+ assert content["data"]["confirmAccount"]["errors"] == [WRONG_PASSWORD_ERROR]
+ assert content["data"]["confirmAccount"]["user"] is None
+
+ # 2nd request shouldn't work due to sending a new attempt too quickly
+ content = get_graphql_content(send_request())
+ assert content["data"]["confirmAccount"]["user"] is None
+ errors = content["data"]["confirmAccount"]["errors"]
+ assert errors == [
+ {
+ "field": None,
+ "code": "LOGIN_ATTEMPT_DELAYED",
+ "message": mock.ANY,
+ }
+ ]
+ assert "too many logging attempts" in errors[0]["message"]
+
+
@patch(
"saleor.graphql.account.mutations.account.confirm_account.assign_user_gift_cards"
)
@@ -103,6 +377,7 @@ def test_account_confirmation_invalid_token(
user_api_client,
customer_user,
channel_USD,
+ account_merging_enabled,
):
variables = {
"email": customer_user.email,
@@ -133,6 +408,8 @@ def test_account_confirmation_rejects_token_for_wrong_scope(
assign_gift_cards_mock,
user_api_client,
customer_user,
+ account_merging_enabled,
+ throttling_disabled,
):
"""When providing a token that's meant for another mutation, it should reject.
@@ -148,6 +425,7 @@ def test_account_confirmation_rejects_token_for_wrong_scope(
variables = {
"email": customer_user.email,
"token": invalid_token,
+ "password": "password",
}
# Should reject the token
@@ -196,6 +474,8 @@ def test_account_confirmation_accepts_legacy_account_confirm_token(
assign_gift_cards_mock,
user_api_client,
customer_user,
+ account_merging_enabled,
+ throttling_disabled,
):
"""Ensure old tokens before adding scopes still work properly."""
@@ -206,6 +486,7 @@ def test_account_confirmation_accepts_legacy_account_confirm_token(
variables = {
"email": customer_user.email,
"token": token,
+ "password": "password",
}
# when
@@ -238,6 +519,8 @@ def test_account_confirmation_rejects_disabled_accounts(
assign_gift_cards_mock,
api_client,
customer_user,
+ account_merging_enabled,
+ throttling_disabled,
):
"""Ensure a user with `is_active=False` cannot confirm their account.
@@ -253,6 +536,7 @@ def test_account_confirmation_rejects_disabled_accounts(
variables = {
"email": customer_user.email,
"token": token,
+ "password": "password",
}
# when
@@ -302,8 +586,10 @@ def test_account_confirmation_rejects_already_confirmed(
mocked_account_confirmed,
match_orders_with_new_user_mock,
assign_gift_cards_mock,
+ account_merging_enabled,
api_client,
customer_user,
+ throttling_disabled,
):
"""Ensure a user with `is_confirmed=True` cannot confirm their account.
@@ -317,6 +603,7 @@ def test_account_confirmation_rejects_already_confirmed(
variables = {
"email": customer_user.email,
"token": token,
+ "password": "password",
}
# when
@@ -349,7 +636,7 @@ def test_account_confirmation_rejects_already_confirmed(
"should have accepted the token"
)
customer_user.refresh_from_db(fields=("is_confirmed",))
- assert customer_user.is_confirmed is True, "shouldh have activated the account"
+ assert customer_user.is_confirmed is True, "should have activated the account"
match_orders_with_new_user_mock.assert_called_once_with(customer_user)
assign_gift_cards_mock.assert_called_once_with(customer_user)
mocked_account_confirmed.assert_called_once_with(customer_user)
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 d692666e85..4fe7d25773 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_update.py
@@ -4,6 +4,7 @@ import graphene
import pytest
from ......account import events as account_events
+from ......account import models
from ......account.error_codes import AccountErrorCode
from ......giftcard.models import GiftCard
from ......giftcard.search import update_gift_cards_search_vector
@@ -673,6 +674,90 @@ def test_customer_update_generates_event_when_changing_email_by_app(
assert email_changed_event.parameters == {"message": "[email protected]"}
+def test_customer_update_existing_user_does_not_merge_with_existing_account(
+ staff_api_client,
+ staff_user,
+ customer_user,
+ gift_card,
+ order,
+ permission_manage_users,
+):
+ """Ensure customerUpdate() doesn't allowing merging with existing users.
+
+ When setting the email address of a customer to an email address that already
+ is associated to an account, it should reject the change and shouldn't merge
+ the account (i.e., orders and giftcards shouldn't associated).
+
+ When there is no account associated, then it should automatically merge.
+ """
+ staff_user.user_permissions.add(permission_manage_users)
+
+ user_for_update = customer_user
+ existing_email = "[email protected]"
+ existing_user = models.User.objects.create(email=existing_email)
+
+ assert user_for_update.email != existing_user.email
+
+ # Create anonymous objects assigned to the targeted email
+ order.user = gift_card.created_by = None
+ order.user_email = gift_card.created_by_email = existing_email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+ order.save(update_fields=["user", "user_email"])
+
+ # When attempting to merge onto an existing account, it should reject
+ # the request, and shouldn't assign the anonymous objects.
+ query = UPDATE_CUSTOMER_EMAIL_MUTATION
+ variables = {
+ "id": graphene.Node.to_global_id("User", user_for_update.pk),
+ "email": existing_email,
+ }
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["customerUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors == [
+ {
+ "field": "email",
+ "message": "User with this Email already exists.",
+ }
+ ]
+
+ customer_user.refresh_from_db(fields=("email",))
+ assert customer_user.email != existing_email, "shoudln't have updated the customer"
+
+ gift_card.refresh_from_db(fields=("created_by", "created_by_email"))
+ assert gift_card.created_by is None, "shouldn't have merged the gift card"
+ assert gift_card.created_by_email == existing_email, (
+ "shouldn't have changed the email"
+ )
+
+ order.refresh_from_db(fields=("user", "user_email"))
+ assert order.user is None, "shouldn't have merged the gift card"
+ assert order.user_email == existing_email, "shouldn't have changed the email"
+
+ # sanity check: if the conflicting user is gone, the same update should merge
+ existing_user.delete()
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ errors = content["data"]["customerUpdate"]["errors"]
+ assert len(errors) == 0
+
+ customer_user.refresh_from_db(fields=("email",))
+ assert customer_user.email == existing_email, "should have updated the customer"
+
+ gift_card.refresh_from_db(fields=("created_by", "created_by_email"))
+ assert gift_card.created_by == customer_user, "should have merged the gift card"
+ assert gift_card.created_by_email == existing_email, (
+ "shouldn't have changed the email"
+ )
+
+ order.refresh_from_db(fields=("user", "user_email"))
+ assert order.user == customer_user, "should have merged the gift card"
+ assert order.user_email == existing_email, "shouldn't have changed the email"
+
+
def test_customer_update_assign_gift_cards_and_orders(
staff_api_client,
staff_user,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 13fab7ac7f..8de97fe8cd 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -15115,6 +15115,11 @@ type Shop implements ObjectWithMetadata {
Added in Saleor 3.22.
"""
useLegacyUpdateWebhookEmission: Boolean @deprecated
+
+ """
+ Controls the method used for merging existing orders and giftcards when password-based authentication is used. Learn more at https://docs.saleor.io/upgrade-guides/core/migrate-account-merging
+ """
+ accountConfirmMergeMode: AccountConfirmModeEnum!
}
"""External authentication plugin."""
@@ -15255,6 +15260,25 @@ enum PasswordLoginModeEnum @doc(category: "Authentication") {
DISABLED
}
+"""
+AccountConfirmMode set the account merging mode for anonymous objects.
+
+ This dictates the behavior of the `confirmAccount()` mutation for
+ password-based authentication when attempting to merge orders & giftcard
+ that aren't associated to a user account.
+
+ Modes:
+
+ - MERGE_DISABLED disables merging only when the authentication method
+ is password (i.e., when not using OIDC)
+ - REQUIRE_PASSWORD enables account merging who accounts that use password
+ authentication but it requires the user to enter their password
+"""
+enum AccountConfirmModeEnum @doc(category: "Authentication") {
+ MERGE_DISABLED
+ REQUIRE_PASSWORD
+}
+
"""Gift card related settings from site settings."""
type GiftCardSettings @doc(category: "Gift cards") {
"""The gift card expiry type settings."""
@@ -21791,6 +21815,11 @@ type Mutation {
"""E-mail of the user performing account confirmation."""
email: String!
+ """
+ Password of the user confirming their account. Required when `REQUIRED_PASSWORD` mode is enabled in shop settings. Learn more at https://docs.saleor.io/upgrade-guides/core/migrate-account-merging
+ """
+ password: String
+
"""A one-time token required to confirm the account."""
token: String!
): ConfirmAccount @doc(category: "Users") @webhookEventsInfo(asyncEvents: [ACCOUNT_CONFIRMED], syncEvents: [])
@@ -23230,6 +23259,11 @@ input ShopSettingsInput {
Added in Saleor 3.22.
"""
useLegacyUpdateWebhookEmission: Boolean @deprecated
+
+ """
+ Controls the method used for merging existing orders and giftcards when password-based authentication is used. Learn more at https://docs.saleor.io/upgrade-guides/core/migrate-account-merging
+ """
+ accountConfirmMergeMode: AccountConfirmModeEnum
}
"""
diff --git a/saleor/graphql/shop/enums.py b/saleor/graphql/shop/enums.py
index 3f981d9e4c..23c33924a4 100644
--- a/saleor/graphql/shop/enums.py
+++ b/saleor/graphql/shop/enums.py
@@ -3,6 +3,7 @@ from typing import Final
import graphene
from ...site import (
+ AccountConfirmMode,
AnnouncementImportance,
GiftCardSettingsExpiryType,
PasswordLoginMode,
@@ -32,3 +33,8 @@ AnnouncementImportanceEnum: Final[graphene.Enum] = to_enum(
description=AnnouncementImportance.__doc__,
)
AnnouncementImportanceEnum.doc_category = DOC_CATEGORY_SHOP
+
+AccountConfirmModeEnum: Final[graphene.Enum] = to_enum(
+ AccountConfirmMode, description=AccountConfirmMode.__doc__
+)
+AccountConfirmModeEnum.doc_category = DOC_CATEGORY_AUTH
diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.py
index 3078df0458..ce41a39abd 100644
--- a/saleor/graphql/shop/mutations/shop_settings_update.py
+++ b/saleor/graphql/shop/mutations/shop_settings_update.py
@@ -19,7 +19,7 @@ from ...core.utils import WebhookEventInfo
from ...meta.inputs import MetadataInput, MetadataInputDescription
from ...plugins.dataloaders import get_plugin_manager_promise
from ...site.dataloaders import get_site_promise
-from ..enums import PasswordLoginModeEnum
+from ..enums import AccountConfirmModeEnum, PasswordLoginModeEnum
from ..types import Shop
@@ -143,6 +143,15 @@ class ShopSettingsInput(graphene.InputObjectType):
),
)
+ account_confirm_merge_mode = AccountConfirmModeEnum(
+ description=(
+ "Controls the method used for merging existing orders and giftcards "
+ "when password-based authentication is used. "
+ "Learn more at "
+ "https://docs.saleor.io/upgrade-guides/core/migrate-account-merging"
+ ),
+ )
+
class ShopSettingsUpdate(BaseMutation):
shop = graphene.Field(Shop, description="Updated shop.")
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 86992e817e..1b0cd9a1ad 100644
--- a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
+++ b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
@@ -1,3 +1,4 @@
+import functools
from unittest.mock import ANY, patch
import pytest
@@ -5,8 +6,8 @@ import pytest
from .....core.error_codes import ShopErrorCode
from .....core.jwt import JWT_OWNER_FIELD
from .....site.models import Site
-from ....tests.utils import get_graphql_content
-from ...enums import PasswordLoginModeEnum
+from ....tests.utils import get_graphql_content, get_graphql_content_from_response
+from ...enums import AccountConfirmModeEnum, PasswordLoginModeEnum
SHOP_SETTINGS_UPDATE_MUTATION = """
mutation updateSettings($input: ShopSettingsInput!) {
@@ -636,6 +637,177 @@ def test_shop_settings_update_password_login_mode_preserves_when_not_provided(
assert site_settings.password_login_mode == login_mode
+MUTATION_UPDATE_ACCOUNT_MERGE_MODE = """
+ mutation updateSettings($input: ShopSettingsInput!) {
+ shopSettingsUpdate(input: $input) {
+ shop {
+ accountConfirmMergeMode
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_shop_settings_update_account_merge_requires_permission(
+ staff_api_client,
+ site_settings,
+ permission_manage_settings,
+):
+ """Account merge mode should only be changeable with MANAGE_SETTINGS permission."""
+
+ initial_setting = AccountConfirmModeEnum.MERGE_DISABLED
+ new_setting = AccountConfirmModeEnum.REQUIRE_PASSWORD
+ site_settings.account_confirm_merge_mode = initial_setting.value
+ site_settings.save(update_fields=("account_confirm_merge_mode",))
+
+ send_gql = functools.partial(
+ staff_api_client.post_graphql,
+ MUTATION_UPDATE_ACCOUNT_MERGE_MODE,
+ variables={"input": {"accountConfirmMergeMode": new_setting.name}},
+ )
+
+ content = get_graphql_content_from_response(send_gql())
+
+ errors = content["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["message"]
+ == "To access this path, you need one of the following permissions: MANAGE_SETTINGS"
+ )
+ # Should not have altered the settings
+ site_settings.refresh_from_db(fields=("account_confirm_merge_mode",))
+ assert site_settings.account_confirm_merge_mode == initial_setting.value, (
+ "shouldn't have changed"
+ )
+
+ # Sanity check: when adding the permisison, it should then work
+ staff_api_client.user.user_permissions.add(permission_manage_settings)
+ content = get_graphql_content_from_response(send_gql())
+ assert "errors" not in content
+ assert content["data"] == {
+ "shopSettingsUpdate": {
+ "shop": {"accountConfirmMergeMode": "REQUIRE_PASSWORD"},
+ "errors": [],
+ }
+ }, "should have succeeded the request"
+
+ # Should have change the settings
+ site_settings.refresh_from_db(fields=("account_confirm_merge_mode",))
+ assert site_settings.account_confirm_merge_mode == new_setting.value, (
+ "should have changed"
+ )
+
+
+ ("initial_setting", "new_setting"),
+ [
+ (
+ AccountConfirmModeEnum.MERGE_DISABLED,
+ AccountConfirmModeEnum.REQUIRE_PASSWORD,
+ ),
+ (
+ AccountConfirmModeEnum.REQUIRE_PASSWORD,
+ AccountConfirmModeEnum.MERGE_DISABLED,
+ ),
+ ],
+)
+def test_shop_settings_update_account_merge_mode(
+ staff_api_client,
+ site_settings,
+ permission_manage_settings,
+ initial_setting,
+ new_setting,
+):
+ """Setting should be changed when the user sets a new preference."""
+
+ # Set the initial state
+ site_settings.account_confirm_merge_mode = initial_setting.value
+ site_settings.save(update_fields=("account_confirm_merge_mode",))
+ expected_site_setting = new_setting.value
+ assert site_settings.account_confirm_merge_mode != expected_site_setting
+
+ variables = {"input": {"accountConfirmMergeMode": new_setting.name}}
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ MUTATION_UPDATE_ACCOUNT_MERGE_MODE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ )
+ data = content["data"]["shopSettingsUpdate"]
+ assert data["errors"] == [], "shouldn't have errored"
+
+ # Should have updated the settings
+ assert data["shop"]["accountConfirmMergeMode"] == new_setting.name
+ site_settings.refresh_from_db(fields=("account_confirm_merge_mode",))
+ assert site_settings.account_confirm_merge_mode == expected_site_setting
+
+
+ "initial_setting",
+ [AccountConfirmModeEnum.MERGE_DISABLED, AccountConfirmModeEnum.REQUIRE_PASSWORD],
+)
+def test_shop_settings_update_account_merge_mode_omitted(
+ staff_api_client,
+ site_settings,
+ permission_manage_settings,
+ initial_setting,
+):
+ """When omitting the account merge mode, it shoudn't change it."""
+
+ site_settings.account_confirm_merge_mode = initial_setting.value
+ site_settings.save(update_fields=("account_confirm_merge_mode",))
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ MUTATION_UPDATE_ACCOUNT_MERGE_MODE,
+ variables={"input": {}},
+ permissions=[permission_manage_settings],
+ )
+ )
+ data = content["data"]["shopSettingsUpdate"]
+ assert data["errors"] == [], "shouldn't have errored"
+
+ # Should not have altered the settings
+ assert data["shop"]["accountConfirmMergeMode"] == initial_setting.name
+ site_settings.refresh_from_db(fields=("account_confirm_merge_mode",))
+ assert site_settings.account_confirm_merge_mode == initial_setting.value
+
+
+def test_shop_settings_update_account_merge_only_valid_values(
+ staff_api_client,
+ site_settings,
+ permission_manage_settings,
+):
+ """Account merge mode should only allow valid enum values."""
+
+ initial_setting = site_settings.account_confirm_merge_mode
+ staff_api_client.user.user_permissions.add(permission_manage_settings)
+
+ content = get_graphql_content_from_response(
+ staff_api_client.post_graphql(
+ MUTATION_UPDATE_ACCOUNT_MERGE_MODE,
+ variables={"input": {"accountConfirmMergeMode": "INVALID"}},
+ )
+ )
+
+ errors = content["errors"]
+ assert len(errors) == 1
+ assert (
+ 'Expected type "AccountConfirmModeEnum", found "INVALID"'
+ in errors[0]["message"]
+ )
+
+ # Should not have altered the settings
+ site_settings.refresh_from_db(fields=("account_confirm_merge_mode",))
+ assert site_settings.account_confirm_merge_mode == initial_setting
+
+
MUTATION_UPDATE_SHOP_NAME = """
mutation updateSettings($input: ShopSettingsInput!) {
shopSettingsUpdate(input: $input) {
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 09b6f65c94..17294fd2f1 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -55,6 +55,7 @@ from ..translations.resolvers import resolve_translation
from ..translations.types import ShopTranslation
from ..utils import format_permissions_for_display
from .enums import (
+ AccountConfirmModeEnum,
AnnouncementImportanceEnum,
GiftCardSettingsExpiryTypeEnum,
PasswordLoginModeEnum,
@@ -492,6 +493,16 @@ class Shop(graphene.ObjectType):
deprecation_reason=DEFAULT_DEPRECATION_REASON,
)
+ account_confirm_merge_mode = AccountConfirmModeEnum(
+ description=(
+ "Controls the method used for merging existing orders and giftcards "
+ "when password-based authentication is used. "
+ "Learn more at "
+ "https://docs.saleor.io/upgrade-guides/core/migrate-account-merging"
+ ),
+ required=True,
+ )
+
class Meta:
description = (
"Represents a shop resource containing general shop data and configuration."
@@ -780,3 +791,8 @@ class Shop(graphene.ObjectType):
@load_site_callback
def resolve_use_legacy_update_webhook_emission(_, _info, site):
return site.settings.use_legacy_update_webhook_emission
+
+ @staticmethod
+ @load_site_callback
+ def resolve_account_confirm_merge_mode(_, _info, site):
+ return site.settings.account_confirm_merge_mode
diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.py
index 99508e7d7a..6d9f93756d 100644
--- a/saleor/plugins/openid_connect/tests/test_utils.py
+++ b/saleor/plugins/openid_connect/tests/test_utils.py
@@ -2,6 +2,7 @@ import datetime
import json
import time
import warnings
+from functools import partial
from unittest import mock
from unittest.mock import MagicMock, Mock, call, patch
@@ -475,6 +476,74 @@ def test_get_or_create_user_from_payload_creates_user_with_sub(
assert user_from_payload.is_confirmed
[email protected]("saleor.plugins.openid_connect.utils.cache.set")
[email protected]("saleor.plugins.openid_connect.utils.cache.get")
+def test_get_or_create_user_from_payload_does_not_match_orders_for_existing_user(
+ mocked_cache_get,
+ _mocked_cache_set,
+ customer_user,
+ customer_user2,
+ order,
+ gift_card,
+):
+ """When a user already exists, it should NOT merge anonymous objects."""
+
+ mocked_cache_get.side_effect = lambda cache_key: None
+
+ # This user has the email address that 'login_as_user' user will use to login
+ other_user = customer_user2
+ other_email = other_user.email
+
+ # The user that we are logging as
+ login_as_user = customer_user
+ original_email = login_as_user.email
+ login_as_user.private_metadata = {"oidc:https://saleor.io/oauth": "oauth|1234"}
+ login_as_user.save(update_fields=("private_metadata",))
+ assert other_email != original_email
+
+ perform_get_or_create = partial(
+ get_or_create_user_from_payload,
+ payload={"sub": "oauth|1234", "email": other_email},
+ oauth_url="https://saleor.io/oauth",
+ )
+
+ # Create anonymous objects assigned to the targeted email
+ order.user = gift_card.created_by = None
+ order.user_email = gift_card.created_by_email = other_email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+ order.save(update_fields=["user", "user_email"])
+
+ # Perform the call - it shouldn't attempt to associate the anonymous objects
+ user_from_payload, created, _updated = perform_get_or_create()
+ assert created is False, "should have found the user already exists"
+
+ # Ensure we indeed did not merge the account with 'other_user'
+ login_as_user.refresh_from_db(fields=("email",))
+ assert login_as_user.email == original_email, "shouldn't have changed the email"
+
+ order.refresh_from_db(fields=("user",))
+ assert order.user is None, "shouldn't have associated the anonymous order"
+ gift_card.refresh_from_db(fields=("created_by",))
+ assert gift_card.created_by is None, (
+ "shouldn't have associated the anonymous giftcard"
+ )
+
+ # Sanity check: if the user doesn't exist in DB, then it should merge
+ # the anonymous objects
+ other_user.delete()
+ user_from_payload, created, _updated = perform_get_or_create()
+
+ # Ensure we now updated the email address as it's no longer taken
+ login_as_user.refresh_from_db(fields=("email",))
+ assert login_as_user.email == other_email, "should have changed the email"
+
+ assert created is False, "shouldn't have created a new user"
+ order.refresh_from_db(fields=("user",))
+ assert order.user == user_from_payload, "should have merged the order"
+ gift_card.refresh_from_db(fields=("created_by",))
+ assert gift_card.created_by is None, "shouldn't have merged the giftcard"
+
+
@mock.patch("saleor.plugins.openid_connect.utils.cache.set")
@mock.patch("saleor.plugins.openid_connect.utils.cache.get")
def test_get_or_create_user_from_payload_match_orders_for_new_user(
@@ -1131,25 +1200,44 @@ def test_update_user_details_no_user_with_new_email_in_db(
@patch("saleor.plugins.openid_connect.utils.match_orders_with_new_user")
@patch("saleor.plugins.openid_connect.utils.logger")
def test_update_user_details_user_with_new_email_in_db(
- mock_logger, mock_match_orders_with_new_user, customer_user, customer_user2
+ mock_logger,
+ mock_match_orders_with_new_user,
+ customer_user,
+ customer_user2,
+ order,
+ gift_card,
):
+ """When a user already exists, it shouldn't merge anonymous objects."""
+
+ existing_user = customer_user2
+ existing_email = existing_user.email
+
+ update_details = partial(
+ _update_user_details,
+ user=customer_user,
+ oidc_key="test oidc_key",
+ user_email=existing_email,
+ user_first_name=customer_user.first_name,
+ user_last_name=customer_user.last_name,
+ sub="test oidc_sub",
+ last_login=customer_user.last_login,
+ )
+
+ # Create anonymous objects assigned to the targeted email
+ order.user = gift_card.created_by = None
+ order.user_email = gift_card.created_by_email = existing_email
+ gift_card.save(update_fields=["created_by", "created_by_email"])
+ order.save(update_fields=["user", "user_email"])
+
# given
assert customer_user.email != customer_user2.email
# when
- _update_user_details(
- customer_user,
- "test oidc_key",
- customer_user2.email,
- customer_user.first_name,
- customer_user.last_name,
- "test oidc_sub",
- customer_user.last_login,
- )
+ update_details()
# then
customer_user.refresh_from_db()
- assert customer_user.email != customer_user2.email
+ assert customer_user.email != existing_email
assert mock_logger.mock_calls == [
call.warning(
"Unable to update user email as the new one already exists in DB",
@@ -1158,6 +1246,14 @@ def test_update_user_details_user_with_new_email_in_db(
]
mock_match_orders_with_new_user.assert_not_called()
+ # Sanity check: if the user doesn't exist in DB, then it should merge
+ # the anonymous objects
+ existing_user.delete()
+ update_details()
+ customer_user.refresh_from_db(fields=("email",))
+ assert customer_user.email == existing_email, "should have changed the email"
+ mock_match_orders_with_new_user.assert_called_once_with(customer_user)
+
@patch(
"saleor.plugins.openid_connect.utils.update_user_search_vector",
diff --git a/saleor/settings.py b/saleor/settings.py
index 80e3e9bbd7..aea24a3c8b 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -1046,6 +1046,14 @@ CHECKOUT_SEARCH_UPDATE_PARALLEL_TASKS = int(
os.environ.get("CHECKOUT_SEARCH_UPDATE_PARALLEL_TASKS", 5)
)
+# Sets the default behavior for new Saleor installations.
+# When set to 'False', it disables account merging by default in DB
+# migrations, and when to 'True', it enables account merging but requires
+# password confirmation.
+# This setting has no effect against existing Saleor installations and
+# shouldn't be changed.
+ACCOUNT_CONFIRM_ASSOCIATE_ANONYMOUS_OBJECTS = False
+
# Patch SubscriberExecutionContext class from `graphql-core-legacy` package
# to fix bug causing not returning errors for subscription queries.
diff --git a/saleor/site/__init__.py b/saleor/site/__init__.py
index f3c4eda9d7..b572cbc69b 100644
--- a/saleor/site/__init__.py
+++ b/saleor/site/__init__.py
@@ -29,6 +29,30 @@ class GiftCardSettingsExpiryType:
]
+class AccountConfirmMode:
+ """AccountConfirmMode set the account merging mode for anonymous objects.
+
+ This dictates the behavior of the `confirmAccount()` mutation for
+ password-based authentication when attempting to merge orders & giftcard
+ that aren't associated to a user account.
+
+ Modes:
+
+ - MERGE_DISABLED disables merging only when the authentication method
+ is password (i.e., when not using OIDC)
+ - REQUIRE_PASSWORD enables account merging who accounts that use password
+ authentication but it requires the user to enter their password
+ """
+
+ MERGE_DISABLED = "merge_disabled"
+ REQUIRE_PASSWORD = "require_password"
+
+ CHOICES = [
+ (MERGE_DISABLED, "Account merging disabled"),
+ (REQUIRE_PASSWORD, "Require password for merging"),
+ ]
+
+
class AnnouncementImportance:
"""Defines a shop-level announcement's level/severity."""
diff --git a/saleor/site/migrations/0041_sitesettings_account_confirm_merge_mode.py b/saleor/site/migrations/0041_sitesettings_account_confirm_merge_mode.py
new file mode 100644
index 0000000000..08724caf0d
--- /dev/null
+++ b/saleor/site/migrations/0041_sitesettings_account_confirm_merge_mode.py
@@ -0,0 +1,29 @@
+# Generated by Django 5.2.13 on 2026-05-07 09:28
+
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("site", "0050_sitesettings_return_reason_reference_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="account_confirm_merge_mode",
+ field=models.CharField(
+ choices=[
+ ("merge_disabled", "Account merging disabled"),
+ ("require_password", "Require password for merging"),
+ ],
+ default=(
+ "require_password"
+ if settings.ACCOUNT_CONFIRM_ASSOCIATE_ANONYMOUS_OBJECTS
+ else "merge_disabled"
+ ),
+ max_length=30,
+ ),
+ ),
+ ]
diff --git a/saleor/site/migrations/0045_merge_20260717_1359.py b/saleor/site/migrations/0045_merge_20260717_1359.py
new file mode 100644
index 0000000000..dcf9dbac39
--- /dev/null
+++ b/saleor/site/migrations/0045_merge_20260717_1359.py
@@ -0,0 +1,12 @@
+# Generated by Django 5.2.16 on 2026-07-17 13:59
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("site", "0041_sitesettings_account_confirm_merge_mode"),
+ ("site", "0044_sitesettings_preserve_all_address_fields"),
+ ]
+
+ operations = []
diff --git a/saleor/site/migrations/0051_merge_20260717_1400.py b/saleor/site/migrations/0051_merge_20260717_1400.py
new file mode 100644
index 0000000000..e4c1a0e392
--- /dev/null
+++ b/saleor/site/migrations/0051_merge_20260717_1400.py
@@ -0,0 +1,12 @@
+# Generated by Django 5.2.16 on 2026-07-17 14:00
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("site", "0045_merge_20260717_1359"),
+ ("site", "0050_sitesettings_return_reason_reference_type"),
+ ]
+
+ operations = []
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 6c59362d57..31d0866f50 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -14,7 +14,7 @@ from ..core.models import ModelWithMetadata
from ..core.units import WeightUnits
from ..core.utils.translations import Translation
from ..permission.enums import SitePermissions
-from . import GiftCardSettingsExpiryType, PasswordLoginMode
+from . import AccountConfirmMode, GiftCardSettingsExpiryType, PasswordLoginMode
from .error_codes import SiteErrorCode
from .patch_sites import patch_contrib_sites
@@ -151,6 +151,16 @@ class SiteSettings(ModelWithMetadata):
db_default=True,
)
+ account_confirm_merge_mode = models.CharField(
+ max_length=30,
+ choices=AccountConfirmMode.CHOICES,
+ default=(
+ AccountConfirmMode.REQUIRE_PASSWORD
+ if settings.ACCOUNT_CONFIRM_ASSOCIATE_ANONYMOUS_OBJECTS
+ else AccountConfirmMode.MERGE_DISABLED
+ ),
+ )
+
class Meta:
permissions = (
(SitePermissions.MANAGE_SETTINGS.codename, "Manage settings."),
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 4e1ee2aec8..f4f4ca6c32 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock
import graphene
import pytest
from django.conf import settings
+from django.core.cache import cache
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import connection
from django.test.utils import CaptureQueriesContext as BaseCaptureQueriesContext
@@ -1697,3 +1698,11 @@ def tax_configuration_avatax_plugin(channel_USD):
tc.tax_app_id = "plugin:avatax"
tc.save()
return tc
+
+
+def cache_clear():
+ """Clear the cache before & after a test case."""
+ cache.clear()
+ yield
+ cache.clear()