Skip to content

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

Introduce good practices in account related mutations (#16937)

Krzysztof Waliczek6f1c35292094
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 439cd8202e..f2966dd263 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,4 +1,3 @@
-
# Changelog
All notable, unreleased changes to this project will be documented in this file. For the released changes, please visit the [Releases](https://github.com/saleor/saleor/releases) page.
@@ -11,6 +10,13 @@ All notable, unreleased changes to this project will be documented in this file.
- Drop the `manager.perform_mutation` method. - #16515 by @maarcingebala
- Dropped the invoicing plugin. For an example of a replacement, see https://docs.saleor.io/developer/app-store/apps/invoices - #16631 by @patrys
+- Change error codes related to user enumeration bad habbit. Included mutations will now not reveal information in error codes if email was already registered:
+ - `AccountRegister`,
+ `AccountRegister` mutation will additionaly not return `ID` of the user.
+ - `ConfirmAccount`,
+ - `RequestPasswordReset`,
+ `RequestPasswordReset` will now require `channel` as input for staff users,
+ - `SetPassword` - #16243 by @kadewu
### GraphQL API
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 9d80daeac6..5bea13f5d2 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -192,6 +192,7 @@ class User(
uuid = models.UUIDField(default=uuid4, unique=True)
USERNAME_FIELD = "email"
+ RETURN_ID_IN_API_RESPONSE = True
objects = UserManager()
diff --git a/saleor/account/tasks.py b/saleor/account/tasks.py
new file mode 100644
index 0000000000..1331f6602d
--- /dev/null
+++ b/saleor/account/tasks.py
@@ -0,0 +1,113 @@
+from typing import cast
+from urllib.parse import urlencode
+
+from django.contrib.auth.tokens import default_token_generator
+from django.utils import timezone
+
+from ..celeryconf import app
+from ..core.db.connection import allow_writer
+from ..core.utils.events import call_event
+from ..core.utils.url import prepare_url
+from ..graphql.plugins.dataloaders import get_plugin_manager_promise
+from ..graphql.site.dataloaders import get_site_promise
+from . import events, notifications, search
+from .models import User
+from .notifications import send_password_reset_notification
+from .utils import RequestorAwareContext
+
+
+def _prepare_redirect_url(user: User, redirect_url: str, token: str) -> str:
+ params = urlencode({"email": user.email, "token": token})
+ return prepare_url(params, redirect_url)
+
+
+@allow_writer()
+def trigger_send_password_reset_notification(
+ redirect_url, user_pk, context_data, channel_slug
+):
+ if not user_pk:
+ return
+
+ user = User.objects.filter(pk=user_pk).first()
+ user = cast(User, user)
+
+ context_data["allow_replica"] = True
+ manager = get_plugin_manager_promise(
+ RequestorAwareContext.from_context_data(context_data)
+ ).get()
+
+ send_password_reset_notification(
+ redirect_url=redirect_url,
+ user=user,
+ manager=manager,
+ channel_slug=channel_slug,
+ staff=user.is_staff,
+ )
+
+ token = default_token_generator.make_token(user)
+ redirect_params = _prepare_redirect_url(user, redirect_url, token)
+
+ if user.is_staff:
+ call_event(
+ manager.staff_set_password_requested,
+ user,
+ channel_slug,
+ token,
+ redirect_params,
+ )
+ else:
+ call_event(
+ manager.account_set_password_requested,
+ user,
+ channel_slug,
+ token,
+ redirect_params,
+ )
+
+ user.last_password_reset_request = timezone.now()
+ user.save(update_fields=("last_password_reset_request",))
+
+
+@allow_writer()
+def finish_creating_user(user_pk, redirect_url, channel_slug, context_data):
+ if not user_pk:
+ return
+
+ user = User.objects.get(pk=user_pk)
+ user.search_document = search.prepare_user_search_document_value(
+ user, attach_addresses_data=False
+ )
+ user.save(update_fields=["search_document"])
+
+ context_data["allow_replica"] = True
+ context = RequestorAwareContext.from_context_data(context_data)
+
+ manager = get_plugin_manager_promise(context).get()
+ site = get_site_promise(context).get()
+
+ if site.settings.enable_account_confirmation_by_email:
+ # Notifications will be deprecated in the future
+ token = default_token_generator.make_token(user)
+ notifications.send_account_confirmation(
+ user=user,
+ redirect_url=redirect_url,
+ channel_slug=channel_slug,
+ manager=manager,
+ token=token,
+ )
+
+ if redirect_url:
+ redirect_url = _prepare_redirect_url(user, redirect_url, token)
+
+ call_event(
+ manager.account_confirmation_requested,
+ user,
+ channel_slug,
+ token,
+ redirect_url,
+ )
+
+ call_event(manager.customer_created, user)
+ events.customer_account_created_event(user=user)
diff --git a/saleor/account/throttling.py b/saleor/account/throttling.py
index 9a39290139..7a392f1c99 100644
--- a/saleor/account/throttling.py
+++ b/saleor/account/throttling.py
@@ -44,9 +44,19 @@ def authenticate_with_throttling(request, email, password) -> Optional[models.Us
# retrieve user from credentials
ip_user_attempts_count = 0
- if user := retrieve_user_by_email(email):
+ user_exists = True
+
+ user = retrieve_user_by_email(email)
+ if not user:
+ user_exists = False
+ user = models.User()
+
+ correct_password = user.check_password(password)
+
+ if user_exists:
ip_user_key = get_cache_key_failed_ip_with_user(ip, user.pk)
- if user.check_password(password):
+
+ if correct_password:
# clear cache entries when login successful
clear_cache([ip_key, ip_user_key, block_key])
return user
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index 1a268be936..e0d1451ca7 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -1,8 +1,10 @@
-from typing import TYPE_CHECKING
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Optional
from django.conf import settings
from django.db.models import Exists, OuterRef
+from ..app.models import App
from ..checkout import AddressType
from ..core.utils.events import call_event
from ..permission.models import Permission
@@ -14,6 +16,43 @@ if TYPE_CHECKING:
from .models import Address
+@dataclass
+class RequestorAwareContext:
+ allow_replica: bool
+ user: Optional[User] = None
+ app: Optional[App] = None
+
+ @property
+ def META(self):
+ return {}
+
+ @staticmethod
+ def _get_or_none(model, pk_value):
+ return (
+ model.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(pk=pk_value)
+ .first()
+ if pk_value
+ else None
+ )
+
+ @classmethod
+ def from_context_data(cls, context_data):
+ return cls(
+ allow_replica=context_data["allow_replica"],
+ user=cls._get_or_none(User, context_data["user_pk"]),
+ app=cls._get_or_none(App, context_data["app_pk"]),
+ )
+
+ @staticmethod
+ def create_context_data(context):
+ return {
+ "allow_replica": context.allow_replica,
+ "user_pk": context.user.pk if context.user else None,
+ "app_pk": context.app.pk if context.app else None,
+ }
+
+
def store_user_address(
user: User,
address: "Address",
diff --git a/saleor/graphql/account/mutations/account/account_register.py b/saleor/graphql/account/mutations/account/account_register.py
index 2d61b82f39..7ce639fa92 100644
--- a/saleor/graphql/account/mutations/account/account_register.py
+++ b/saleor/graphql/account/mutations/account/account_register.py
@@ -1,16 +1,13 @@
-from urllib.parse import urlencode
-
import graphene
from django.conf import settings
from django.contrib.auth import password_validation
-from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import ValidationError
-from .....account import events as account_events
-from .....account import models, notifications, search
+from .....account import models
from .....account.error_codes import AccountErrorCode
-from .....core.tracing import traced_atomic_transaction
-from .....core.utils.url import prepare_url, validate_storefront_url
+from .....account.tasks import finish_creating_user
+from .....account.utils import RequestorAwareContext
+from .....core.utils.url import validate_storefront_url
from .....webhook.event_types import WebhookEventAsyncType
from ....channel.utils import clean_channel
from ....core import ResolveInfo
@@ -20,7 +17,6 @@ from ....core.mutations import ModelMutation
from ....core.types import AccountError, NonNullList
from ....core.utils import WebhookEventInfo
from ....meta.inputs import MetadataInput
-from ....plugins.dataloaders import get_plugin_manager_promise
from ....site.dataloaders import get_site_promise
from ...types import User
from .base import AccountBaseInput
@@ -71,11 +67,10 @@ class AccountRegister(ModelMutation):
class Meta:
description = "Register a new user."
doc_category = DOC_CATEGORY_USERS
- exclude = ["password"]
- model = models.User
- object_type = User
error_type_class = AccountError
error_type_field = "account_errors"
+ model = models.User
+ object_type = User
support_meta_field = True
webhook_events_info = [
WebhookEventInfo(
@@ -102,6 +97,9 @@ class AccountRegister(ModelMutation):
response.requires_confirmation = (
site.settings.enable_account_confirmation_by_email
)
+ # we don't want to return id's as it will allow to deduce if user exists
+ if response.user:
+ response.user.RETURN_ID_IN_API_RESPONSE = False
return response
@classmethod
@@ -145,46 +143,89 @@ class AccountRegister(ModelMutation):
return super().clean_input(info, instance, data, **kwargs)
@classmethod
- def save(cls, info: ResolveInfo, user, cleaned_input):
- password = cleaned_input["password"]
- user.set_password(password)
- user.search_document = search.prepare_user_search_document_value(
- user, attach_addresses_data=False
+ def clean_instance(cls, info: ResolveInfo, instance, /):
+ user_exists = False
+
+ try:
+ instance.full_clean(exclude=["password"])
+ except ValidationError as error:
+ user_exists, error.error_dict = cls._clean_errors(error)
+
+ if error.error_dict:
+ raise error
+
+ return user_exists
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ instance = models.User()
+ data = data.get("input")
+ cleaned_input = cls.clean_input(info, instance, data)
+ metadata_list = cleaned_input.pop("metadata", None)
+ private_metadata_list = cleaned_input.pop("private_metadata", None)
+
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.validate_and_update_metadata(instance, metadata_list, private_metadata_list)
+ user_exists = cls.clean_instance(info, instance)
+ context_data = RequestorAwareContext.create_context_data(info.context)
+ cls.save_and_create_task(user_exists, instance, cleaned_input, context_data)
+ return cls.success_response(instance)
+
+ @classmethod
+ def save_and_create_task(cls, user_exists, instance, cleaned_input, context_data):
+ instance.set_password(cleaned_input["password"])
+ instance.is_confirmed = False
+
+ if not user_exists:
+ instance.save()
+
+ # moving logic to async task to prevent timing attacks
+ finish_creating_user.delay(
+ instance.pk if not user_exists else None,
+ cleaned_input.get("redirect_url"),
+ cleaned_input.get("channel"),
+ context_data,
)
- manager = get_plugin_manager_promise(info.context).get()
- site = get_site_promise(info.context).get()
- token = None
- redirect_url = cleaned_input.get("redirect_url")
-
- with traced_atomic_transaction():
- user.is_confirmed = False
- user.save()
- if site.settings.enable_account_confirmation_by_email:
- # Notifications will be deprecated in the future
- token = default_token_generator.make_token(user)
- notifications.send_account_confirmation(
- user,
- redirect_url,
- manager,
- channel_slug=cleaned_input["channel"],
- token=token,
- )
- if redirect_url:
- params = urlencode(
- {
- "email": user.email,
- "token": token or default_token_generator.make_token(user),
- }
- )
- redirect_url = prepare_url(params, redirect_url)
-
- cls.call_event(
- manager.account_confirmation_requested,
- user,
- cleaned_input["channel"],
- token,
- redirect_url,
- )
-
- cls.call_event(manager.customer_created, user)
- account_events.customer_account_created_event(user=user)
+
+ @classmethod
+ def _clean_email_errors(cls, errors):
+ """Clean email errors.
+
+ Iterates over errors for field `email` with purpose to
+ not leak `unique` error in case when user already exists in database which would
+ allow user enumeration.
+ Returns boolean value if user exists and filtered errors
+ that can be displayed to the end user.
+ """
+ existing_user = False
+ filtered_errors = []
+
+ for error in errors:
+ if error.code == "unique":
+ existing_user = True
+ continue
+ filtered_errors.append(error)
+
+ return existing_user, filtered_errors
+
+ @classmethod
+ def _clean_errors(cls, error):
+ """Clean errors.
+
+ Iterate over errors for field `email` with purpose to
+ not leak error indicating user existence in the system.
+ Returns boolean value if user exists and filtered errors
+ that can be displayed to the end user.
+ """
+ existing_user = False
+ error_dict = {}
+
+ for field, errors in error.error_dict.items():
+ if field == "email":
+ existing_user, errors = cls._clean_email_errors(errors)
+ if not errors:
+ continue
+
+ error_dict[field] = errors
+
+ return existing_user, error_dict
diff --git a/saleor/graphql/account/mutations/account/confirm_account.py b/saleor/graphql/account/mutations/account/confirm_account.py
index 3cbaad7ddf..37c88487ad 100644
--- a/saleor/graphql/account/mutations/account/confirm_account.py
+++ b/saleor/graphql/account/mutations/account/confirm_account.py
@@ -47,19 +47,17 @@ class ConfirmAccount(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ error = False
try:
user = models.User.objects.get(email=data["email"])
- except ObjectDoesNotExist as e:
- raise ValidationError(
- {
- "email": ValidationError(
- "User with this email doesn't exist",
- code=AccountErrorCode.NOT_FOUND.value,
- )
- }
- ) from e
+ except ObjectDoesNotExist:
+ # If user doesn't exists in the database we create fake user for calculation
+ # purpose, as we don't want to indicate non existence of user in the system.
+ error = True
+ user = models.User()
- if not default_token_generator.check_token(user, data["token"]):
+ valid_token = default_token_generator.check_token(user, data["token"])
+ if not valid_token or error:
raise ValidationError(
{
"token": ValidationError(
diff --git a/saleor/graphql/account/mutations/authentication/request_password_reset.py b/saleor/graphql/account/mutations/authentication/request_password_reset.py
index e039117cff..08e16ad87d 100644
--- a/saleor/graphql/account/mutations/authentication/request_password_reset.py
+++ b/saleor/graphql/account/mutations/authentication/request_password_reset.py
@@ -1,15 +1,12 @@
-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.error_codes import AccountErrorCode
-from .....account.notifications import send_password_reset_notification
-from .....account.utils import retrieve_user_by_email
-from .....core.utils.url import prepare_url, validate_storefront_url
+from .....account.tasks import trigger_send_password_reset_notification
+from .....account.utils import RequestorAwareContext, retrieve_user_by_email
+from .....core.utils.url import validate_storefront_url
from .....webhook.event_types import WebhookEventAsyncType
from ....channel.utils import clean_channel, validate_channel
from ....core import ResolveInfo
@@ -17,7 +14,6 @@ from ....core.doc_category import DOC_CATEGORY_USERS
from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ....core.utils import WebhookEventInfo
-from ....plugins.dataloaders import get_plugin_manager_promise
class RequestPasswordReset(BaseMutation):
@@ -34,10 +30,7 @@ class RequestPasswordReset(BaseMutation):
),
)
channel = graphene.String(
- description=(
- "Slug of a channel which will be used for notify user. Optional when "
- "only one channel exists."
- )
+ description="Slug of a channel which will be used for notify user."
)
class Meta:
@@ -63,7 +56,7 @@ class RequestPasswordReset(BaseMutation):
]
@classmethod
- def clean_user(cls, email, redirect_url, info: ResolveInfo):
+ def clean_user(cls, email, redirect_url):
try:
validate_storefront_url(redirect_url)
except ValidationError as e:
@@ -72,37 +65,12 @@ class RequestPasswordReset(BaseMutation):
) from e
user = retrieve_user_by_email(email)
- if not user:
- raise ValidationError(
- {
- "email": ValidationError(
- "User with this email doesn't exist",
- code=AccountErrorCode.NOT_FOUND.value,
- )
- }
- )
-
- if not user.is_active:
- raise ValidationError(
- {
- "email": ValidationError(
- "User with this email is inactive",
- code=AccountErrorCode.INACTIVE.value,
- )
- }
- )
-
- if password_reset_time := user.last_password_reset_request:
- delta = timezone.now() - password_reset_time
+ if user and user.last_password_reset_request:
+ delta = timezone.now() - user.last_password_reset_request
if delta.total_seconds() < settings.RESET_PASSWORD_LOCK_TIME:
- raise ValidationError(
- {
- "email": ValidationError(
- "Password reset already requested",
- code=AccountErrorCode.PASSWORD_RESET_ALREADY_REQUESTED.value,
- )
- }
- )
+ user = None
+ elif user and not user.is_active:
+ user = None
return user
@@ -110,46 +78,19 @@ class RequestPasswordReset(BaseMutation):
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
email = data["email"]
redirect_url = data["redirect_url"]
- user = cls.clean_user(email, redirect_url, info)
+ user = cls.clean_user(email, redirect_url)
channel_slug = data.get("channel")
- token = default_token_generator.make_token(user)
- params = urlencode({"email": user.email, "token": token})
- if not user.is_staff:
- channel_slug = clean_channel(
- channel_slug, error_class=AccountErrorCode, allow_replica=False
- ).slug
- elif channel_slug is not None:
- channel_slug = validate_channel(
- channel_slug, error_class=AccountErrorCode
- ).slug
+ channel_slug = clean_channel(
+ channel_slug, error_class=AccountErrorCode, allow_replica=False
+ ).slug
+ channel_slug = validate_channel(channel_slug, error_class=AccountErrorCode).slug
- manager = get_plugin_manager_promise(info.context).get()
- send_password_reset_notification(
- redirect_url,
- user,
- manager,
+ trigger_send_password_reset_notification.delay(
+ redirect_url=redirect_url,
+ user_pk=user.pk if user else None,
+ context_data=RequestorAwareContext.create_context_data(info.context),
channel_slug=channel_slug,
- staff=user.is_staff,
)
- if user.is_staff:
- cls.call_event(
- manager.staff_set_password_requested,
- user,
- channel_slug,
- token,
- prepare_url(params, redirect_url),
- )
- else:
- cls.call_event(
- manager.account_set_password_requested,
- user,
- channel_slug,
- token,
- prepare_url(params, redirect_url),
- )
-
- user.last_password_reset_request = timezone.now()
- user.save(update_fields=["last_password_reset_request"])
return RequestPasswordReset()
diff --git a/saleor/graphql/account/mutations/authentication/set_password.py b/saleor/graphql/account/mutations/authentication/set_password.py
index a6a0132dba..99f3894946 100644
--- a/saleor/graphql/account/mutations/authentication/set_password.py
+++ b/saleor/graphql/account/mutations/authentication/set_password.py
@@ -50,17 +50,17 @@ class SetPassword(CreateToken):
@classmethod
def _set_password_for_user(cls, email, password, token):
+ error = False
try:
user = models.User.objects.get(email=email)
- except ObjectDoesNotExist as e:
- raise ValidationError(
- {
- "email": ValidationError(
- "User doesn't exist", code=AccountErrorCode.NOT_FOUND.value
- )
- }
- ) from e
- if not default_token_generator.check_token(user, token):
+ except ObjectDoesNotExist:
+ # If user doesn't exists in the database we create fake user for calculation
+ # purpose, as we don't want to indicate non existence of user in the system.
+ error = True
+ user = models.User()
+
+ valid_token = default_token_generator.check_token(user, token)
+ if not valid_token or error:
raise ValidationError(
{
"token": ValidationError(
diff --git a/saleor/graphql/account/tests/mutations/account/test_account_register.py b/saleor/graphql/account/tests/mutations/account/test_account_register.py
index 7c15887970..570e63a690 100644
--- a/saleor/graphql/account/tests/mutations/account/test_account_register.py
+++ b/saleor/graphql/account/tests/mutations/account/test_account_register.py
@@ -5,10 +5,10 @@ from django.contrib.auth.tokens import default_token_generator
from django.test import override_settings
from ......account import events as account_events
-from ......account.error_codes import AccountErrorCode
from ......account.models import User
from ......account.notifications import get_default_user_payload
from ......account.search import generate_user_fields_search_document_value
+from ......account.tasks import finish_creating_user
from ......core.notify import NotifyEventType
from ......core.tests.utils import get_site_context_payload
from ......core.utils.url import prepare_url
@@ -29,6 +29,8 @@ ACCOUNT_REGISTER_MUTATION = """
user {
id
email
+ firstName
+ lastName
}
}
}
@@ -40,7 +42,12 @@ ACCOUNT_REGISTER_MUTATION = """
)
@patch("saleor.account.notifications.default_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
+@patch(
+ "saleor.graphql.account.mutations.account.account_register.finish_creating_user",
+ wraps=finish_creating_user,
+)
def test_customer_register(
+ mocked_finish_creating_user,
mocked_notify,
mocked_generator,
api_client,
@@ -86,6 +93,10 @@ def test_customer_register(
"channel_slug": channel_PLN.slug,
**get_site_context_payload(site_settings.site),
}
+ assert data["user"]["firstName"] == variables["input"]["firstName"]
+ assert data["user"]["lastName"] == variables["input"]["lastName"]
+ assert data["user"]["email"] == variables["input"]["email"]
+ assert data["user"]["id"] == ""
assert new_user.metadata == {"meta": "data"}
assert new_user.language_code == "pl"
assert new_user.first_name == variables["input"]["firstName"]
@@ -102,17 +113,109 @@ def test_customer_register(
assert len(called_kwargs) == 2
assert called_kwargs["payload_func"]() == expected_payload
assert called_kwargs["channel_slug"] == channel_PLN.slug
+ assert mocked_finish_creating_user.delay.called
+ assert mocked_finish_creating_user.delay.call_args.args[0] == new_user.pk
+
+
+@override_settings(
+ ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=True, ALLOWED_CLIENT_HOSTS=["localhost"]
+)
+@patch("saleor.account.notifications.default_token_generator.make_token")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+@patch(
+ "saleor.graphql.account.mutations.account.account_register.finish_creating_user",
+ wraps=finish_creating_user,
+)
+def test_customer_register_twice(
+ mocked_finish_creating_user,
+ mocked_notify,
+ mocked_generator,
+ api_client,
+ channel_PLN,
+ order,
+ site_settings,
+):
+ # given
+ mocked_generator.return_value = "token"
+ email = "[email protected]"
+
+ redirect_url = "http://localhost:3000"
+ variables = {
+ "input": {
+ "email": email,
+ "password": "Password",
+ "redirectUrl": redirect_url,
+ "firstName": "saleor",
+ "lastName": "rocks",
+ "languageCode": "PL",
+ "metadata": [{"key": "meta", "value": "data"}],
+ "channel": channel_PLN.slug,
+ }
+ }
+ query = ACCOUNT_REGISTER_MUTATION
+ mutation_name = "accountRegister"
+ # when
response = api_client.post_graphql(query, variables)
+
+ # then
+ new_user = User.objects.get(email=email)
content = get_graphql_content(response)
data = content["data"][mutation_name]
- assert data["errors"]
- assert data["errors"][0]["field"] == "email"
- assert data["errors"][0]["code"] == AccountErrorCode.UNIQUE.name
+ params = urlencode({"email": email, "token": "token"})
+ confirm_url = prepare_url(params, redirect_url)
+
+ expected_payload = {
+ "user": get_default_user_payload(new_user),
+ "token": "token",
+ "confirm_url": confirm_url,
+ "recipient_email": new_user.email,
+ "channel_slug": channel_PLN.slug,
+ **get_site_context_payload(site_settings.site),
+ }
+ assert data["user"]["firstName"] == variables["input"]["firstName"]
+ assert data["user"]["lastName"] == variables["input"]["lastName"]
+ assert data["user"]["email"] == variables["input"]["email"]
+ assert data["user"]["id"] == ""
+ assert new_user.metadata == {"meta": "data"}
+ assert new_user.language_code == "pl"
+ assert new_user.first_name == variables["input"]["firstName"]
+ assert new_user.last_name == variables["input"]["lastName"]
+ assert new_user.search_document == generate_user_fields_search_document_value(
+ new_user
+ )
+ assert not data["errors"]
+ assert mocked_notify.call_count == 1
+ call_args = mocked_notify.call_args_list[0]
+ called_args = call_args.args
+ called_kwargs = call_args.kwargs
+ assert called_args[0] == NotifyEventType.ACCOUNT_CONFIRMATION
+ assert len(called_kwargs) == 2
+ assert called_kwargs["payload_func"]() == expected_payload
+ assert called_kwargs["channel_slug"] == channel_PLN.slug
+ assert mocked_finish_creating_user.delay.called
+ assert mocked_finish_creating_user.delay.call_args.args[0] == new_user.pk
+
+ # when
+ # remove personal data from input
+ del variables["input"]["firstName"]
+ del variables["input"]["lastName"]
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"][mutation_name]
+
+ # then
+ assert not data["errors"]
customer_creation_event = account_events.CustomerEvent.objects.get()
+ assert data["user"]["firstName"] == ""
+ assert data["user"]["lastName"] == ""
+ assert data["user"]["email"] == variables["input"]["email"]
+ assert data["user"]["id"] == ""
assert customer_creation_event.type == account_events.CustomerEvents.ACCOUNT_CREATED
assert customer_creation_event.user == new_user
+ assert mocked_finish_creating_user.delay.call_count == 2
+ assert mocked_finish_creating_user.delay.call_args.args[0] is None
@override_settings(
@@ -251,3 +354,56 @@ def test_customer_register_no_channel_email_confirmation_unset(
assert not data["errors"]
assert data["user"]["email"].lower()
mocked_notify.assert_not_called()
+
+
+def test_account_register_properly_filter_errors(
+ api_client, channel_PLN, site_settings
+):
+ # given
+ site_settings.enable_account_confirmation_by_email = False
+ site_settings.save(update_fields=["enable_account_confirmation_by_email"])
+
+ email = "customer"
+ variables = {
+ "input": {
+ "email": email,
+ "password": "Password",
+ "firstName": "saleor",
+ "lastName": "rocks",
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(ACCOUNT_REGISTER_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["accountRegister"]["errors"]
+ assert errors
+ assert errors[0]["code"] == "INVALID"
+ assert errors[0]["field"] == "email"
+
+
+def test_account_register_returns_empty_id(
+ api_client, channel_PLN, site_settings, customer_user
+):
+ # given
+ site_settings.enable_account_confirmation_by_email = False
+ site_settings.save(update_fields=["enable_account_confirmation_by_email"])
+
+ variables = {
+ "input": {
+ "email": customer_user.email,
+ "password": "Password",
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(ACCOUNT_REGISTER_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountRegister"]
+ assert not data["errors"]
+ assert data["user"]["id"] == ""
+ assert data["user"]["email"] == customer_user.email
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 3d6e2e14d3..84a957d941 100644
--- a/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
+++ b/saleor/graphql/account/tests/mutations/account/test_confirm_account.py
@@ -78,10 +78,10 @@ def test_account_confirmation_invalid_user(
}
response = user_api_client.post_graphql(CONFIRM_ACCOUNT_MUTATION, variables)
content = get_graphql_content(response)
- assert content["data"]["confirmAccount"]["errors"][0]["field"] == "email"
+ assert content["data"]["confirmAccount"]["errors"][0]["field"] == "token"
assert (
content["data"]["confirmAccount"]["errors"][0]["code"]
- == AccountErrorCode.NOT_FOUND.name
+ == AccountErrorCode.INVALID.name
)
match_orders_with_new_user_mock.assert_not_called()
assign_gift_cards_mock.assert_not_called()
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 87e8822697..1ee84fcc14 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
@@ -6,7 +6,6 @@ from django.contrib.auth.tokens import default_token_generator
from django.utils import timezone
from freezegun import freeze_time
-from ......account.error_codes import AccountErrorCode
from ......account.notifications import get_default_user_payload
from ......core.notify import NotifyEventType
from ......core.tests.utils import get_site_context_payload
@@ -34,7 +33,7 @@ REQUEST_PASSWORD_RESET_MUTATION = """
def test_account_reset_password(
mocked_account_set_password_requested,
mocked_notify,
- user_api_client,
+ api_client,
customer_user,
channel_PLN,
channel_USD,
@@ -49,10 +48,10 @@ def test_account_reset_password(
}
# when
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ content = get_graphql_content(response)
# then
- content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
token = default_token_generator.make_token(customer_user)
@@ -76,59 +75,62 @@ def test_account_reset_password(
assert called_kwargs["payload_func"]() == expected_payload
assert called_kwargs["channel_slug"] == channel_PLN.slug
- user = user_api_client.user
- user.refresh_from_db()
- assert user.last_password_reset_request == timezone.now()
+ customer_user.refresh_from_db()
+ assert customer_user.last_password_reset_request == timezone.now()
mocked_account_set_password_requested.assert_called_once_with(
- user, channel_PLN.slug, token, reset_url
+ customer_user, channel_PLN.slug, token, reset_url
)
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_on_cooldown(
- mocked_notify, user_api_client, customer_user, channel_PLN
+ mocked_notify, api_client, customer_user, channel_PLN
):
+ # given
redirect_url = "https://www.example.com"
variables = {
"email": customer_user.email,
"redirectUrl": redirect_url,
"channel": channel_PLN.slug,
}
- user = user_api_client.user
+ user = customer_user
user.last_password_reset_request = timezone.now()
user.save(update_fields=["last_password_reset_request"])
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+
+ # when
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
content = get_graphql_content(response)
+
+ # then
errors = content["data"]["requestPasswordReset"]["errors"]
- assert errors == [
- {
- "field": "email",
- "message": "Password reset already requested",
- "code": AccountErrorCode.PASSWORD_RESET_ALREADY_REQUESTED.name,
- }
- ]
+ assert not errors
mocked_notify.assert_not_called()
@freeze_time("2018-05-31 12:00:01")
def test_account_reset_password_after_cooldown(
- user_api_client, customer_user, channel_PLN, settings
+ api_client, customer_user, channel_PLN, settings
):
+ # given
redirect_url = "https://www.example.com"
variables = {
"email": customer_user.email,
"redirectUrl": redirect_url,
"channel": channel_PLN.slug,
}
- user = user_api_client.user
+ user = customer_user
user.last_password_reset_request = timezone.now() - datetime.timedelta(
seconds=settings.RESET_PASSWORD_LOCK_TIME
)
user.save(update_fields=["last_password_reset_request"])
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+
+ # when
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
content = get_graphql_content(response)
+
+ # then
assert content["data"]["requestPasswordReset"]["errors"] == []
@@ -136,7 +138,7 @@ def test_account_reset_password_after_cooldown(
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_with_upper_case_email(
mocked_notify,
- user_api_client,
+ api_client,
customer_user,
channel_PLN,
channel_USD,
@@ -151,10 +153,10 @@ def test_account_reset_password_with_upper_case_email(
}
# when
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ content = get_graphql_content(response)
# then
- content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
token = default_token_generator.make_token(customer_user)
@@ -182,28 +184,37 @@ def test_account_reset_password_with_upper_case_email(
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_request_password_reset_email_for_staff(
- mocked_notify, staff_api_client, channel_USD, site_settings
+ mocked_notify,
+ api_client,
+ channel_USD,
+ site_settings,
+ staff_user,
):
# given
redirect_url = "https://www.example.com"
- variables = {"email": staff_api_client.user.email, "redirectUrl": redirect_url}
+ variables = {
+ "email": staff_user.email,
+ "redirectUrl": redirect_url,
+ "channel": channel_USD.slug,
+ }
+ user = staff_user
# when
- response = staff_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ content = get_graphql_content(response)
# then
- content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
- token = default_token_generator.make_token(staff_api_client.user)
- params = urlencode({"email": staff_api_client.user.email, "token": token})
+ token = default_token_generator.make_token(user)
+ params = urlencode({"email": user.email, "token": token})
reset_url = prepare_url(params, redirect_url)
expected_payload = {
- "user": get_default_user_payload(staff_api_client.user),
+ "user": get_default_user_payload(user),
"reset_url": reset_url,
"token": token,
- "recipient_email": staff_api_client.user.email,
- "channel_slug": None,
+ "recipient_email": user.email,
+ "channel_slug": channel_USD.slug,
**get_site_context_payload(site_settings.site),
}
@@ -214,29 +225,33 @@ def test_request_password_reset_email_for_staff(
assert called_args[0] == NotifyEventType.ACCOUNT_STAFF_RESET_PASSWORD
assert len(called_kwargs) == 2
assert called_kwargs["payload_func"]() == expected_payload
- assert called_kwargs["channel_slug"] is None
+ assert called_kwargs["channel_slug"] == channel_USD.slug
@patch("saleor.plugins.manager.PluginsManager.notify")
-def test_account_reset_password_invalid_email(
- mocked_notify, user_api_client, channel_USD
-):
+def test_account_reset_password_invalid_email(mocked_notify, api_client, channel_USD):
+ # given
variables = {
"email": "[email protected]",
"redirectUrl": "https://www.example.com",
"channel": channel_USD.slug,
}
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+
+ # when
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
content = get_graphql_content(response)
+
+ # then
data = content["data"]["requestPasswordReset"]
- assert len(data["errors"]) == 1
+ assert not data["errors"]
mocked_notify.assert_not_called()
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_user_is_inactive(
- mocked_notify, user_api_client, customer_user, channel_USD
+ mocked_notify, api_client, customer_user, channel_USD
):
+ # given
user = customer_user
user.is_active = False
user.save()
@@ -246,27 +261,33 @@ def test_account_reset_password_user_is_inactive(
"redirectUrl": "https://www.example.com",
"channel": channel_USD.slug,
}
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
- results = response.json()
- assert "errors" in results
- assert (
- results["errors"][0]["message"]
- == "Invalid token. User does not exist or is inactive."
- )
- assert not mocked_notify.called
+
+ # when
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["requestPasswordReset"]
+ assert not data["errors"]
+ mocked_notify.assert_not_called()
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_storefront_hosts_not_allowed(
- mocked_notify, user_api_client, customer_user, channel_USD
+ mocked_notify, api_client, customer_user, channel_USD
):
+ # given
variables = {
"email": customer_user.email,
"redirectUrl": "https://www.fake.com",
"channel": channel_USD.slug,
}
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+
+ # when
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
content = get_graphql_content(response)
+
+ # then
data = content["data"]["requestPasswordReset"]
assert len(data["errors"]) == 1
assert data["errors"][0]["field"] == "redirectUrl"
@@ -277,7 +298,7 @@ def test_account_reset_password_storefront_hosts_not_allowed(
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_all_storefront_hosts_allowed(
mocked_notify,
- user_api_client,
+ api_client,
customer_user,
settings,
channel_PLN,
@@ -294,10 +315,10 @@ def test_account_reset_password_all_storefront_hosts_allowed(
}
# when
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ content = get_graphql_content(response)
# then
- content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
@@ -325,7 +346,7 @@ def test_account_reset_password_all_storefront_hosts_allowed(
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_subdomain(
- mocked_notify, user_api_client, customer_user, settings, channel_PLN, site_settings
+ mocked_notify, api_client, customer_user, settings, channel_PLN, site_settings
):
# given
settings.ALLOWED_CLIENT_HOSTS = [".example.com"]
@@ -337,10 +358,10 @@ def test_account_reset_password_subdomain(
}
# when
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ content = get_graphql_content(response)
# then
- content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert not data["errors"]
@@ -370,7 +391,7 @@ def test_account_reset_password_subdomain(
def test_account_reset_password_event_triggered(
mocked_trigger_webhooks_async,
settings,
- user_api_client,
+ api_client,
customer_user,
channel_PLN,
subscription_account_set_password_requested_webhook,
@@ -386,7 +407,7 @@ def test_account_reset_password_event_triggered(
}
# when
- user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
# then
mocked_trigger_webhooks_async.assert_called()
@@ -398,7 +419,7 @@ def test_account_reset_password_event_triggered(
def test_account_reset_password_for_not_confirmed_user(
mocked_account_set_password_requested,
mocked_notify,
- user_api_client,
+ api_client,
customer_user,
channel_PLN,
channel_USD,
@@ -416,7 +437,7 @@ def test_account_reset_password_for_not_confirmed_user(
}
# when
- response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+ response = api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
# then
content = get_graphql_content(response)
@@ -443,7 +464,7 @@ def test_account_reset_password_for_not_confirmed_user(
assert called_kwargs["payload_func"]() == expected_payload
assert called_kwargs["channel_slug"] == channel_PLN.slug
- user = user_api_client.user
+ user = customer_user
user.refresh_from_db()
assert user.last_password_reset_request == timezone.now()
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 ef1e189143..ba4a9d5fb8 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
@@ -104,12 +104,12 @@ def test_set_password_invalid_email(user_api_client):
content = get_graphql_content(response)
errors = content["data"]["setPassword"]["errors"]
assert len(errors) == 1
- assert errors[0]["field"] == "email"
+ assert errors[0]["field"] == "token"
account_errors = content["data"]["setPassword"]["errors"]
assert len(account_errors) == 1
- assert account_errors[0]["field"] == "email"
- assert account_errors[0]["code"] == AccountErrorCode.NOT_FOUND.name
+ assert account_errors[0]["field"] == "token"
+ assert account_errors[0]["code"] == AccountErrorCode.INVALID.name
@freeze_time("2018-05-31 12:00:01")
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 8698c358d7..77492fcb6c 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -54,6 +54,7 @@ from ..core.types import (
ModelObjectType,
NonNullList,
Permission,
+ SecureGlobalID,
ThumbnailField,
)
from ..core.utils import from_global_id_or_error, str_to_enum, to_global_id_or_none
@@ -312,7 +313,7 @@ class UserPermission(Permission):
@federated_entity("id")
@federated_entity("email")
class User(ModelObjectType[models.User]):
- id = graphene.GlobalID(required=True, description="The ID of the user.")
+ id = SecureGlobalID(required=True, description="The ID of the user.")
email = graphene.String(required=True, description="The email address of the user.")
first_name = graphene.String(
required=True, description="The given name of the address."
@@ -681,7 +682,7 @@ class User(ModelObjectType[models.User]):
from .resolvers import resolve_users
ids = set()
- emails = set()
+ emails: set[Optional[str]] = set()
for root in roots:
if root.id is not None:
ids.add(root.id)
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index ff7a954010..bcc08b0b85 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -52,6 +52,7 @@ from .common import (
ProductVariantBulkError,
ProductVariantBulkTranslateError,
ProductWithoutVariantError,
+ SecureGlobalID,
SendConfirmationEmailError,
SeoInput,
ShippingError,
@@ -147,6 +148,7 @@ __all__ = [
"ProductVariantBulkError",
"ProductVariantBulkTranslateError",
"ReducedRate",
+ "SecureGlobalID",
"SendConfirmationEmailError",
"SeoInput",
"ShippingError",
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 59132dd81f..0720b7e6e3 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -117,6 +117,19 @@ class NonNullList(graphene.List):
super().__init__(of_type, *args, **kwargs)
+class SecureGlobalID(graphene.GlobalID):
+ @staticmethod
+ def id_resolver(parent_resolver, node, root, info, parent_type_name=None, **args):
+ if (
+ hasattr(root, "RETURN_ID_IN_API_RESPONSE")
+ and not root.RETURN_ID_IN_API_RESPONSE
+ ):
+ return ""
+ return graphene.GlobalID.id_resolver(
+ parent_resolver, node, root, info, parent_type_name, **args
+ )
+
+
class CountryDisplay(graphene.ObjectType):
code = graphene.String(description="Country code.", required=True)
country = graphene.String(description="Country name.", required=True)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index ed0152ea08..51076c9c91 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -18152,9 +18152,7 @@ type Mutation {
- STAFF_SET_PASSWORD_REQUESTED (async): Setting a new password for the staff account is requested.
"""
requestPasswordReset(
- """
- Slug of a channel which will be used for notify user. Optional when only one channel exists.
- """
+ """Slug of a channel which will be used for notify user."""
channel: String
"""Email of the user that will be used for password recovery."""
diff --git a/saleor/tests/e2e/account/test_login_throttling.py b/saleor/tests/e2e/account/test_login_throttling.py
index e1b6a7d313..06bd820c67 100644
--- a/saleor/tests/e2e/account/test_login_throttling.py
+++ b/saleor/tests/e2e/account/test_login_throttling.py
@@ -1,12 +1,12 @@
import datetime
from unittest.mock import patch
-import graphene
import pytest
from django.utils import timezone
from freezegun import freeze_time
from ....account.error_codes import AccountErrorCode
+from ....account.models import User
from ....account.throttling import (
get_cache_key_blocked_ip,
get_cache_key_failed_ip,
@@ -75,9 +75,9 @@ def test_customer_should_not_be_able_to_perform_credential_guessing_attacks_core
user_password,
channel_slug,
)
- user_id = user_account["user"]["id"]
- assert user_id is not None
- _, user_db_id = graphene.Node.from_global_id(user_id)
+ user_object = User.objects.last()
+ assert user_object
+ user_db_id = user_object.pk
assert user_account["user"]["isActive"] is True
# Step 2 - First attempt of logging with an invalid password
diff --git a/saleor/tests/e2e/account/test_should_create_account_without_email_confirmation.py b/saleor/tests/e2e/account/test_should_create_account_without_email_confirmation.py
index f24a87bb95..9728733e6e 100644
--- a/saleor/tests/e2e/account/test_should_create_account_without_email_confirmation.py
+++ b/saleor/tests/e2e/account/test_should_create_account_without_email_confirmation.py
@@ -1,5 +1,7 @@
import pytest
+from ....account.models import User
+from ....graphql.core.utils import to_global_id_or_none
from ..shop.utils import prepare_shop
from ..utils import assign_permissions
from .utils import account_register, token_create
@@ -51,7 +53,9 @@ def test_should_create_account_without_email_confirmation_core_1502(
channel_slug,
redirect_url,
)
- user_id = user_account["user"]["id"]
+ user = User.objects.last()
+ assert user
+ user_id = to_global_id_or_none(user)
assert user_account["user"]["isActive"] is True
# Step 2 - Authenticate as new created user
diff --git a/saleor/tests/e2e/account/test_should_login_before_email_confirmation.py b/saleor/tests/e2e/account/test_should_login_before_email_confirmation.py
index 1f859e9bb7..d104020b52 100644
--- a/saleor/tests/e2e/account/test_should_login_before_email_confirmation.py
+++ b/saleor/tests/e2e/account/test_should_login_before_email_confirmation.py
@@ -1,5 +1,7 @@
import pytest
+from ....account.models import User
+from ....graphql.core.utils import to_global_id_or_none
from ..shop.utils import prepare_shop
from ..utils import assign_permissions
from .utils import account_register, token_create
@@ -53,7 +55,9 @@ def test_should_login_before_email_confirmation_core_1510(
redirect_url,
)
- user_id = user_account["user"]["id"]
+ user = User.objects.last()
+ assert user
+ user_id = to_global_id_or_none(user)
assert user_account["user"]["isActive"] is True
assert user_account["requiresConfirmation"] is True
diff --git a/saleor/tests/e2e/account/test_should_not_be_able_to_create_account_with_existing_email.py b/saleor/tests/e2e/account/test_should_not_be_able_to_create_account_with_existing_email.py
index bb8245ae85..3402f02e28 100644
--- a/saleor/tests/e2e/account/test_should_not_be_able_to_create_account_with_existing_email.py
+++ b/saleor/tests/e2e/account/test_should_not_be_able_to_create_account_with_existing_email.py
@@ -1,5 +1,6 @@
import pytest
+from ....account.models import User
from ..shop.utils import prepare_shop
from ..utils import assign_permissions
from .utils import account_register, raw_account_register
@@ -48,8 +49,6 @@ def test_should_not_be_able_to_create_account_with_existing_email_core_1503(
user_password,
channel_slug,
)
- user_id = user_account["user"]["id"]
- assert user_id is not None
assert user_account["user"]["isActive"] is True
# Step 2 - Create a new account with the same email address
@@ -60,7 +59,6 @@ def test_should_not_be_able_to_create_account_with_existing_email_core_1503(
new_password,
channel_slug,
)
- error = new_user_account["data"]["accountRegister"]["errors"][0]
- assert error["field"] == "email"
- assert error["message"] == "User with this Email already exists."
- assert error["code"] == "UNIQUE"
+ # we do not return errors in case email exists
+ assert not new_user_account["data"]["accountRegister"]["errors"]
+ assert User.objects.filter(email__iexact=user_email).count() == 1
diff --git a/saleor/tests/e2e/checkout/test_guest_checkout_should_be_assigned_to_user_after_creating_the_account.py b/saleor/tests/e2e/checkout/test_guest_checkout_should_be_assigned_to_user_after_creating_the_account.py
index 1aaab5b3c1..eecc6cece3 100644
--- a/saleor/tests/e2e/checkout/test_guest_checkout_should_be_assigned_to_user_after_creating_the_account.py
+++ b/saleor/tests/e2e/checkout/test_guest_checkout_should_be_assigned_to_user_after_creating_the_account.py
@@ -1,5 +1,7 @@
import pytest
+from ....account.models import User
+from ....graphql.core.utils import to_global_id_or_none
from ..account.utils import account_register
from ..product.utils.preparing_product import prepare_product
from ..shop.utils.preparing_shop import prepare_shop
@@ -136,7 +138,9 @@ def test_guest_checkout_should_be_assigned_to_user_after_creating_the_account_CO
channel_slug,
redirect_url,
)
- user_id = user_account["user"]["id"]
+ user = User.objects.last()
+ assert user
+ user_id = to_global_id_or_none(user)
assert user_account["user"]["isActive"] is True
# Step 6 - Confirm new account