Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Make email authentication case insensitive (#11284)
Piotr Zabieglik075153568ead
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 59b36898cc..84974a37eb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add new properties in the `Product` type - #10537 by @kadewu- Add new fields: `Product.attribute`, `Product.variant`- Add `sortBy` argument to `Product.media`+- Allow assigning attribute value using its ID. Add to `AttributeValueInput` dedicated field for each input type. #11206 by @zedzior### Other changes@@ -36,9 +37,8 @@ All notable, unreleased changes to this project will be documented in this file.- Bump cryptography to 38.0.3: use OpenSSL 3.0.7 - #11126 by @NyanKiyoshi- Add exif image validation - #11224 by @IKarbowiak- Include fully qualified API URL `Saleor-Api-Url` in communication with Apps. #11223 by @przlada-- Add `attribute` field to `AttributeValueTranslatableContent` type. #11028 by @zedzior-- Allow assigning attribute value using its ID. Add to `AttributeValueInput` dedicated field for each input type. #11206 by @zedzior- Add metadata on order line payload notifications. #10954 by @CarlesLopezMagem+- Make email authentication case-insensitive. #11284 by @zedzior- Fix the observability reporter to obfuscate URLs. #11282 by @przlada# 3.8.0diff --git a/saleor/account/tests/test_utils.py b/saleor/account/tests/test_utils.pyindex f346bb4411..f3f9f5af68 100644--- a/saleor/account/tests/test_utils.py+++ b/saleor/account/tests/test_utils.py@@ -1,3 +1,4 @@+from typing import Listfrom unittest.mock import patchimport pytest@@ -11,6 +12,7 @@ from ..utils import (remove_staff_member,remove_the_oldest_user_address,remove_the_oldest_user_address_if_address_limit_is_reached,+ retrieve_user_by_email,store_user_address,)@@ -189,3 +191,43 @@ def test_remove_the_oldest_user_address_if_address_limit_is_reached_limit_reache# thenremove_the_oldest_user_address_mock.assert_called_with(customer_user)+++def users_with_similar_emails():+ users = User.objects.bulk_create(+ [+ User(email="[email protected]"),+ User(email="[email protected]"),+ User(email="[email protected]"),+ User(email="[email protected]"),+ User(email="[email protected]"),+ User(email="[email protected]"),+ ]+ )+ return users+++ "email,expected_user",+ [+ ("[email protected]", 0),+ ("[email protected]", 1),+ ("[email protected]", 0),+ ("[email protected]", 2),+ ("[email protected]", 2),+ ("[email protected]", 3),+ ("[email protected]", 3),+ ("[email protected]", 4),+ ("[email protected]", None),+ ("[email protected]", None),+ ("[email protected]", None),+ ],+)+def test_email_case_sensitivity(email, expected_user, users_with_similar_emails):+ # given+ users: List[User] = users_with_similar_emails+ # when+ user = retrieve_user_by_email(email=email)+ # then+ assert user == users[expected_user] if expected_user is not None else user is Nonediff --git a/saleor/account/utils.py b/saleor/account/utils.pyindex 5f8c58d240..bf3e6fdf0a 100644--- a/saleor/account/utils.py+++ b/saleor/account/utils.py@@ -112,3 +112,21 @@ def remove_staff_member(staff):staff.save()else:staff.delete()+++def retrieve_user_by_email(email):+ """Retrieve user by email.++ Email lookup is case-insensitive, unless the query returns more than one user. In+ such a case, function return case-sensitive result.+ """+ users = User.objects.filter(email__iexact=email)++ if len(users) > 1:+ users_exact = [user for user in users if user.email == email]+ users_iexact = [user for user in users if user.email == email.lower()]+ users = users_exact or users_iexact # type: ignore++ if users:+ return users[0]+ return Nonediff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.pyindex a0e7364cc3..22d515e232 100644--- a/saleor/graphql/account/mutations/account.py+++ b/saleor/graphql/account/mutations/account.py@@ -121,6 +121,8 @@ class AccountRegister(ModelMutation):data.get("channel"), error_class=AccountErrorCode).slug+ data["email"] = data["email"].lower()+password = data["password"]try:password_validation.validate_password(password, instance)@@ -429,7 +431,7 @@ class RequestEmailChange(BaseMutation):def perform_mutation(cls, _root, info, **data):user = info.context.userpassword = data["password"]- new_email = data["new_email"]+ new_email = data["new_email"].lower()redirect_url = data["redirect_url"]if not user.check_password(password):@@ -519,7 +521,7 @@ class ConfirmEmailChange(BaseMutation):token = data["token"]payload = cls.get_token_payload(token)- new_email = payload["new_email"]+ new_email = payload["new_email"].lower()old_email = payload["old_email"]if models.User.objects.filter(email=new_email).exists():diff --git a/saleor/graphql/account/mutations/authentication.py b/saleor/graphql/account/mutations/authentication.pyindex b6c7bb8df0..8ae9ce48f3 100644--- a/saleor/graphql/account/mutations/authentication.py+++ b/saleor/graphql/account/mutations/authentication.py@@ -14,6 +14,7 @@ from graphene.types.generic import GenericScalarfrom ....account import modelsfrom ....account.error_codes import AccountErrorCode+from ....account.utils import retrieve_user_by_emailfrom ....core.jwt import (JWT_REFRESH_TOKEN_COOKIE_NAME,JWT_REFRESH_TYPE,@@ -106,7 +107,8 @@ class CreateToken(BaseMutation):@classmethoddef _retrieve_user_from_credentials(cls, email, password) -> Optional[models.User]:- user = models.User.objects.filter(email=email).first()+ user = retrieve_user_by_email(email)+if user and user.check_password(password):return userreturn Nonediff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 421dad1bc2..14aa398e85 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -11,6 +11,7 @@ from ....account.notifications import (send_set_password_notification,)from ....account.search import prepare_user_search_document_value+from ....account.utils import retrieve_user_by_emailfrom ....checkout import AddressTypefrom ....core.exceptions import PermissionDeniedfrom ....core.permissions import AccountPermissions, AuthorizationFilters@@ -158,9 +159,8 @@ class RequestPasswordReset(BaseMutation):{"redirect_url": error}, code=AccountErrorCode.INVALID)- try:- user = models.User.objects.get(email=email)- except ObjectDoesNotExist:+ user = retrieve_user_by_email(email)+ if not user:raise ValidationError({"email": ValidationError(@@ -482,6 +482,10 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):{"redirect_url": error}, code=AccountErrorCode.INVALID)+ email = cleaned_input.get("email")+ if email:+ cleaned_input["email"] = email.lower()+return cleaned_input@classmethoddiff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.pyindex e0a397739c..e18b85e231 100644--- a/saleor/graphql/account/mutations/staff.py+++ b/saleor/graphql/account/mutations/staff.py@@ -241,6 +241,10 @@ class StaffCreate(ModelMutation):cls.clean_groups(requestor, cleaned_input, errors)cls.clean_is_active(cleaned_input, instance, info.context.user, errors)+ email = cleaned_input.get("email")+ if email:+ cleaned_input["email"] = email.lower()+if errors:raise ValidationError(errors)diff --git a/saleor/graphql/account/tests/mutations/test_token_create.py b/saleor/graphql/account/tests/mutations/test_token_create.pyindex 784a560aa7..606f597815 100644--- a/saleor/graphql/account/tests/mutations/test_token_create.py+++ b/saleor/graphql/account/tests/mutations/test_token_create.py@@ -221,3 +221,22 @@ def test_create_token_active_user_logged_before(api_client, customer_user, settiassert payload["type"] == JWT_REFRESH_TYPEassert payload["token"] == customer_user.jwt_token_keyassert payload["iss"] == build_absolute_uri(reverse("api"))+++@freeze_time("2020-03-18 12:00:00")+def test_create_token_email_case_insensitive(api_client, customer_user, settings):+ # given+ variables = {+ "email": customer_user.email.upper(),+ "password": customer_user._password,+ }++ # when+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["tokenCreate"]+ assert customer_user.email == data["user"]["email"]+ assert not data["errors"]+ assert data["token"]diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.pyindex 6a0bdcbc3f..70377055b4 100644--- a/saleor/graphql/account/tests/test_account.py+++ b/saleor/graphql/account/tests/test_account.py@@ -9,6 +9,7 @@ from urllib.parse import urlencodeimport grapheneimport pytest+from django.conf import settingsfrom django.contrib.auth.models import Groupfrom django.contrib.auth.tokens import default_token_generatorfrom django.core.exceptions import ValidationError@@ -1384,6 +1385,7 @@ ACCOUNT_REGISTER_MUTATION = """}user {id}}}@@ -1488,6 +1490,22 @@ def test_customer_register_no_redirect_url(mocked_notify, api_client):mocked_notify.assert_not_called()+@override_settings(ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL=False)+def test_customer_register_upper_case_email(api_client):+ # given+ email = "[email protected]"+ variables = {"email": 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"]["email"].lower()++CUSTOMER_CREATE_MUTATION = """mutation CreateCustomer($email: String, $firstName: String, $lastName: String, $channel: String@@ -1707,6 +1725,25 @@ def test_customer_create_with_not_allowed_url(assert not staff_user+def test_customer_create_with_upper_case_email(+ staff_api_client, permission_manage_users+):+ # given+ email = "[email protected]"+ variables = {"email": email}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_CREATE_MUTATION, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["customerCreate"]+ assert not data["errors"]+ assert data["user"]["email"] == email.lower()++def test_customer_update(staff_api_client, staff_user, customer_user, address, permission_manage_users):@@ -3104,6 +3141,25 @@ def test_staff_create_with_not_allowed_url(assert not staff_user+def test_staff_create_with_upper_case_email(+ staff_api_client, media_root, permission_manage_staff+):+ # given+ email = "[email protected]"+ variables = {"email": email}++ # when+ response = staff_api_client.post_graphql(+ STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["staffCreate"]+ assert not data["errors"]+ assert data["user"]["email"] == email.lower()++STAFF_UPDATE_MUTATIONS = """mutation UpdateStaff($id: ID!, $input: StaffUpdateInput!) {@@ -4891,6 +4947,45 @@ def test_account_reset_password()+@freeze_time("2018-05-31 12:00:01")+@patch("saleor.plugins.manager.PluginsManager.notify")+def test_account_reset_password_with_upper_case_email(+ mocked_notify,+ user_api_client,+ customer_user,+ channel_PLN,+ channel_USD,+ site_settings,+):+ redirect_url = "https://www.example.com"+ variables = {+ "email": customer_user.email.upper(),+ "redirectUrl": redirect_url,+ "channel": channel_PLN.slug,+ }+ response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)+ 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,+ )++@freeze_time("2018-05-31 12:00:01")@patch("saleor.graphql.account.mutations.base.assign_user_gift_cards")@patch("saleor.graphql.account.mutations.base.match_orders_with_new_user")@@ -6359,6 +6454,58 @@ mutation requestEmailChange("""+@freeze_time("2018-05-31 12:00:01")+@patch("saleor.plugins.manager.PluginsManager.notify")+def test_account_request_email_change_with_upper_case_email(+ mocked_notify,+ user_api_client,+ customer_user,+ site_settings,+ channel_PLN,+):+ # given+ new_email = "[email protected]"+ redirect_url = "https://www.example.com"+ variables = {+ "new_email": new_email,+ "redirect_url": redirect_url,+ "password": "password",+ }+ token_payload = {+ "old_email": customer_user.email,+ "new_email": new_email.lower(),+ "user_pk": customer_user.pk,+ }+ token = create_token(token_payload, settings.JWT_TTL_REQUEST_EMAIL_CHANGE)++ # when+ response = user_api_client.post_graphql(REQUEST_EMAIL_CHANGE_QUERY, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["requestEmailChange"]+ assert not data["errors"]++ params = urlencode({"token": token})+ redirect_url = prepare_url(params, redirect_url)+ expected_payload = {+ "user": get_default_user_payload(customer_user),+ "recipient_email": new_email.lower(),+ "token": token,+ "redirect_url": redirect_url,+ "old_email": customer_user.email,+ "new_email": new_email.lower(),+ "channel_slug": channel_PLN.slug,+ **get_site_context_payload(site_settings.site),+ }++ mocked_notify.assert_called_once_with(+ NotifyEventType.ACCOUNT_CHANGE_EMAIL_REQUEST,+ payload=expected_payload,+ channel_slug=channel_PLN.slug,+ )++def test_request_email_change(user_api_client, customer_user, channel_PLN):variables = {"password": "password",diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.pyindex defd04c899..f0c620c880 100644--- a/saleor/graphql/account/utils.py+++ b/saleor/graphql/account/utils.py@@ -11,6 +11,7 @@ from graphene.utils.str_converters import to_camel_casefrom ...account import events as account_eventsfrom ...account.error_codes import AccountErrorCode+from ...account.models import Userfrom ...core.exceptions import PermissionDeniedfrom ...core.permissions import (AccountPermissions,@@ -22,7 +23,6 @@ from ..app.dataloaders import load_appif TYPE_CHECKING:from django.db.models import QuerySet- from ...account.models import Userfrom ...app.models import App