Skip to content

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

Update user confirmation (#15513)

Iga Karbowiak9f2a574c8b4c
diff --git a/saleor/account/migrations/0081_update_user_is_confirmed.py b/saleor/account/migrations/0081_update_user_is_confirmed.py
index 884d9cce1b..282fd11903 100644
--- a/saleor/account/migrations/0081_update_user_is_confirmed.py
+++ b/saleor/account/migrations/0081_update_user_is_confirmed.py
@@ -35,15 +35,10 @@ def set_user_is_confirmed_to_false(qs: QuerySet["User"]):
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)
+ users = User.objects.order_by("pk").filter(
+ is_confirmed=True, 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)
diff --git a/saleor/account/migrations/0083_confirm_active_user.py b/saleor/account/migrations/0083_confirm_active_user.py
new file mode 100644
index 0000000000..f61746458e
--- /dev/null
+++ b/saleor/account/migrations/0083_confirm_active_user.py
@@ -0,0 +1,49 @@
+# Generated by Django 3.2.24 on 2024-02-29 13:21
+
+from django.db import migrations
+from django.db.models import QuerySet
+
+# 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_true(qs: QuerySet):
+ qs.update(is_confirmed=True)
+
+
+def confirm_active_users(apps, schema_editor):
+ User = apps.get_model("account", "User")
+
+ users = User.objects.order_by("pk").filter(
+ is_confirmed=False, is_active=True, last_login__isnull=False
+ )
+ for ids in queryset_in_batches(users):
+ qs = User.objects.filter(pk__in=ids)
+ set_user_is_confirmed_to_true(qs)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0082_auto_20231204_1419"),
+ ]
+
+ operations = [migrations.RunPython(confirm_active_users, migrations.RunPython.noop)]
diff --git a/saleor/account/migrations/0084_merge_20240229_1435.py b/saleor/account/migrations/0084_merge_20240229_1435.py
new file mode 100644
index 0000000000..75a124d177
--- /dev/null
+++ b/saleor/account/migrations/0084_merge_20240229_1435.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.24 on 2024-02-29 14:35
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0083_confirm_active_user"),
+ ("account", "0083_merge_20231205_1315"),
+ ]
+
+ operations = []
diff --git a/saleor/graphql/account/mutations/authentication/request_password_reset.py b/saleor/graphql/account/mutations/authentication/request_password_reset.py
index 25fdcb236c..90de5443aa 100644
--- a/saleor/graphql/account/mutations/authentication/request_password_reset.py
+++ b/saleor/graphql/account/mutations/authentication/request_password_reset.py
@@ -18,7 +18,6 @@ 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):
@@ -72,7 +71,6 @@ 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(
@@ -84,7 +82,7 @@ class RequestPasswordReset(BaseMutation):
}
)
- if not user.can_login(site.settings):
+ if not user.is_active:
raise ValidationError(
{
"email": ValidationError(
diff --git a/saleor/graphql/account/mutations/authentication/set_password.py b/saleor/graphql/account/mutations/authentication/set_password.py
index a6ff43ad04..c319421f0e 100644
--- a/saleor/graphql/account/mutations/authentication/set_password.py
+++ b/saleor/graphql/account/mutations/authentication/set_password.py
@@ -6,6 +6,7 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationError
from .....account import events as account_events
from .....account import models
from .....account.error_codes import AccountErrorCode
+from .....order.utils import match_orders_with_new_user
from ....core import ResolveInfo
from ....core.context import disallow_replica_in_context
from ....core.doc_category import DOC_CATEGORY_USERS
@@ -79,6 +80,14 @@ class SetPassword(CreateToken):
password_validation.validate_password(password, user)
except ValidationError as error:
raise ValidationError({"password": error})
+ fields_to_save = ["password", "updated_at"]
user.set_password(password)
- user.save(update_fields=["password", "updated_at"])
+ # To reset the password user need to process the token sent separately by email,
+ # so we can be sure that the user has access to email account and can be
+ # confirmed.
+ if not user.is_confirmed:
+ user.is_confirmed = True
+ match_orders_with_new_user(user)
+ fields_to_save.append("is_confirmed")
+ user.save(update_fields=fields_to_save)
account_events.customer_password_reset_event(user=user)
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_request_password_reset.py b/saleor/graphql/account/tests/mutations/authentication/test_request_password_reset.py
index 43fc65db76..5d03a57097 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_request_password_reset.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_request_password_reset.py
@@ -350,3 +350,59 @@ def test_account_reset_password_event_triggered(
# then
mocked_trigger_webhooks_async.assert_called()
+
+
+@freeze_time("2018-05-31 12:00:01")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+@patch("saleor.plugins.manager.PluginsManager.account_set_password_requested")
+def test_account_reset_password_for_not_confirmed_user(
+ mocked_account_set_password_requested,
+ mocked_notify,
+ user_api_client,
+ customer_user,
+ channel_PLN,
+ channel_USD,
+ site_settings,
+):
+ # given
+ customer_user.is_confirmed = False
+ customer_user.save(update_fields=["is_confirmed"])
+
+ redirect_url = "https://www.example.com"
+ variables = {
+ "email": customer_user.email,
+ "redirectUrl": redirect_url,
+ "channel": channel_PLN.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["requestPasswordReset"]
+ assert not data["errors"]
+ token = default_token_generator.make_token(customer_user)
+ params = urlencode({"email": customer_user.email, "token": token})
+ reset_url = prepare_url(params, redirect_url)
+ expected_payload = {
+ "user": get_default_user_payload(customer_user),
+ "reset_url": reset_url,
+ "token": token,
+ "recipient_email": customer_user.email,
+ "channel_slug": channel_PLN.slug,
+ **get_site_context_payload(site_settings.site),
+ }
+
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ACCOUNT_PASSWORD_RESET,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
+ )
+ user = user_api_client.user
+ user.refresh_from_db()
+ assert user.last_password_reset_request == timezone.now()
+
+ mocked_account_set_password_requested.assert_called_once_with(
+ user, channel_PLN.slug, token, reset_url
+ )
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_set_password.py b/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
index ac305f4724..ef1e189143 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
@@ -1,3 +1,5 @@
+from unittest.mock import patch
+
from django.contrib.auth.tokens import default_token_generator
from freezegun import freeze_time
@@ -49,6 +51,41 @@ def test_set_password(user_api_client, customer_user):
assert password_resent_event.user == customer_user
+@freeze_time("2018-05-31 12:00:01")
+@patch(
+ "saleor.graphql.account.mutations.authentication.set_password.match_orders_with_new_user"
+)
+def test_set_password_confirm_user_and_match_orders(
+ match_orders_with_new_user_mock, user_api_client, customer_user
+):
+ # given
+ customer_user.is_confirmed = False
+ customer_user.save(update_fields=["is_confirmed"])
+
+ token = default_token_generator.make_token(customer_user)
+ password = "spanish-inquisition"
+
+ variables = {"email": customer_user.email, "password": password, "token": token}
+
+ # when
+ response = user_api_client.post_graphql(SET_PASSWORD_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["setPassword"]
+ assert data["user"]["id"]
+ assert data["token"]
+
+ customer_user.refresh_from_db()
+ assert customer_user.check_password(password)
+
+ password_resent_event = account_events.CustomerEvent.objects.get()
+ assert password_resent_event.type == account_events.CustomerEvents.PASSWORD_RESET
+ assert password_resent_event.user == customer_user
+ assert customer_user.is_confirmed
+ match_orders_with_new_user_mock.assert_called_once_with(customer_user)
+
+
def test_set_password_invalid_token(user_api_client, customer_user):
variables = {"email": customer_user.email, "password": "pass", "token": "token"}
response = user_api_client.post_graphql(SET_PASSWORD_MUTATION, variables)
diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.py
index 1e33c24f2e..8632f75bb1 100644
--- a/saleor/plugins/openid_connect/tests/test_utils.py
+++ b/saleor/plugins/openid_connect/tests/test_utils.py
@@ -328,6 +328,8 @@ def test_get_or_create_user_from_payload_creates_user_with_sub(
assert user_from_payload.email == customer_email
assert user_from_payload.private_metadata[f"oidc:{oauth_url}"] == sub_id
assert not user_from_payload.has_usable_password()
+ assert user_from_payload.is_active
+ assert user_from_payload.is_confirmed
@mock.patch("saleor.plugins.openid_connect.utils.cache.set")
@@ -526,6 +528,36 @@ def test_get_or_create_user_from_payload_update_last_login(
assert last_login == "2019-03-18 12:00:00"
[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_set_is_confirmed(
+ mocked_cache_get, mocked_cache_set, customer_user
+):
+ # given
+ customer_user.is_confirmed = False
+ customer_user.save(update_fields=["is_confirmed"])
+ assert customer_user.last_login is None
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|1234"
+
+ mocked_cache_get.side_effect = lambda cache_key: None
+
+ # when
+ get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_user.email},
+ oauth_url=oauth_url,
+ )
+ cache_key = f"oidc:{oauth_url}" + ":" + str(sub_id)
+
+ # then
+ customer_user.refresh_from_db()
+ mocked_cache_get.assert_called_once_with(cache_key)
+ mocked_cache_set.assert_called_once_with(
+ cache_key, customer_user.id, OIDC_CACHE_TIMEOUT
+ )
+ assert customer_user.is_confirmed
+
+
@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_last_login_stays_same(
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index c8b94a6be4..f86a4d6b0c 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -421,8 +421,9 @@ def get_or_create_user_from_payload(
defaults=defaults_create,
)
- site_settings = Site.objects.get_current().settings
- if not user.can_login(site_settings): # it is true only if we fetch disabled user.
+ # User logged in by OpenID are treated as confirmed by default so we only need to
+ # check if user is active
+ if not user.is_active:
raise AuthenticationError("Unable to log in.")
_update_user_details(
@@ -499,6 +500,10 @@ def _update_user_details(
)
fields_to_save.add("search_document")
+ if not user.is_confirmed:
+ user.is_confirmed = True
+ fields_to_save.add("is_confirmed")
+
if fields_to_save:
user.save(update_fields=fields_to_save)