Skip to content

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

Add change password mutation

fowczarek9e18d62940e1
diff --git a/saleor/account/__init__.py b/saleor/account/__init__.py
index 22db4280f6..00a497d076 100755
--- a/saleor/account/__init__.py
+++ b/saleor/account/__init__.py
@@ -8,6 +8,7 @@ class CustomerEvents:
ACCOUNT_CREATED = "account_created"
PASSWORD_RESET_LINK_SENT = "password_reset_link_sent"
PASSWORD_RESET = "password_reset"
+ PASSWORD_CHANGE = "password_change"
# Order related events
PLACED_ORDER = "placed_order" # created an order
diff --git a/saleor/account/events.py b/saleor/account/events.py
index 53b55e9a6b..d8e3e670c2 100644
--- a/saleor/account/events.py
+++ b/saleor/account/events.py
@@ -25,6 +25,10 @@ def customer_password_reset_event(*, user: UserType) -> Optional[CustomerEvent]:
return CustomerEvent.objects.create(user=user, type=CustomerEvents.PASSWORD_RESET)
+def customer_password_change_event(*, user: UserType) -> Optional[CustomerEvent]:
+ return CustomerEvent.objects.create(user=user, type=CustomerEvents.PASSWORD_CHANGE)
+
+
def customer_placed_order_event(
*, user: UserType, order: Order
) -> Optional[CustomerEvent]:
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 528c78ec54..5da262f870 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -114,6 +114,41 @@ class RequestPasswordReset(BaseMutation):
return RequestPasswordReset()
+class PasswordChange(BaseMutation):
+ user = graphene.Field(User, description="An user instance with new password.")
+
+ class Arguments:
+ old_password = graphene.String(
+ required=True, description="Current user password."
+ )
+ new_password = graphene.String(required=True, description="New user password.")
+
+ class Meta:
+ description = "Change the password of the logged in user."
+
+ @classmethod
+ def check_permissions(cls, user):
+ return user.is_authenticated
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ user = info.context.user
+ old_password = data["old_password"]
+ new_password = data["new_password"]
+
+ if not user.check_password(old_password):
+ raise ValidationError({"old_password": "Old password isn't valid."})
+ try:
+ password_validation.validate_password(new_password, user)
+ except ValidationError as error:
+ raise ValidationError({"new_password": error.messages})
+
+ user.set_password(new_password)
+ user.save(update_fields=["password"])
+ account_events.customer_password_change_event(user=user)
+ return PasswordChange(user=user)
+
+
class BaseAddressUpdate(ModelMutation):
"""Base mutation for address update used by staff and account."""
diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.py
index 7f95f33f8a..3a6e326b9d 100644
--- a/saleor/graphql/account/schema.py
+++ b/saleor/graphql/account/schema.py
@@ -18,6 +18,7 @@ from .mutations.account import (
AccountUpdate,
)
from .mutations.base import (
+ PasswordChange,
RequestPasswordReset,
SetPassword,
UserClearStoredMeta,
@@ -118,6 +119,7 @@ class AccountMutations(graphene.ObjectType):
# Base mutations
request_password_reset = RequestPasswordReset.Field()
set_password = SetPassword.Field()
+ password_change = PasswordChange.Field()
user_update_metadata = UserUpdateMeta.Field()
user_clear_stored_metadata = UserClearStoredMeta.Field()
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index 7d2678ac71..31df43d691 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -1471,6 +1471,78 @@ def test_password_reset_email_non_existing_user(
send_password_reset_mock.assert_not_called()
+CHANGE_PASSWORD_MUTATION = """
+ mutation PasswordChange($oldPassword: String!, $newPassword: String!) {
+ passwordChange(oldPassword: $oldPassword, newPassword: $newPassword) {
+ errors {
+ field
+ message
+ }
+ user {
+ email
+ }
+ }
+ }
+"""
+
+
+def test_password_change(user_api_client):
+ customer_user = user_api_client.user
+ new_password = "spanish-inquisition"
+
+ variables = {"oldPassword": "password", "newPassword": new_password}
+ response = user_api_client.post_graphql(CHANGE_PASSWORD_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["passwordChange"]
+ assert not data["errors"]
+ assert data["user"]["email"] == customer_user.email
+
+ customer_user.refresh_from_db()
+ assert customer_user.check_password(new_password)
+
+ password_change_event = account_events.CustomerEvent.objects.get()
+ assert password_change_event.type == account_events.CustomerEvents.PASSWORD_CHANGE
+ assert password_change_event.user == customer_user
+
+
+def test_password_change_incorrect_old_password(user_api_client):
+ customer_user = user_api_client.user
+ variables = {"oldPassword": "incorrect", "newPassword": ""}
+ response = user_api_client.post_graphql(CHANGE_PASSWORD_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["passwordChange"]
+ customer_user.refresh_from_db()
+ assert customer_user.check_password("password")
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "oldPassword"
+
+
+def test_password_change_invalid_new_password(user_api_client, settings):
+ settings.AUTH_PASSWORD_VALIDATORS = [
+ {
+ "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
+ "OPTIONS": {"min_length": 5},
+ },
+ {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
+ ]
+
+ customer_user = user_api_client.user
+ variables = {"oldPassword": "password", "newPassword": "1234"}
+ response = user_api_client.post_graphql(CHANGE_PASSWORD_MUTATION, variables)
+ content = get_graphql_content(response)
+ errors = content["data"]["passwordChange"]["errors"]
+ customer_user.refresh_from_db()
+ assert customer_user.check_password("password")
+ assert len(errors) == 2
+ assert errors[1]["field"] == "newPassword"
+ assert (
+ errors[0]["message"]
+ == "This password is too short. It must contain at least 5 characters."
+ )
+ assert errors[1]["field"] == "newPassword"
+ assert errors[1]["message"] == "This password is entirely numeric."
+
+
def test_create_address_mutation(
staff_api_client, customer_user, permission_manage_users
):