Skip to content

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

Support setting password on account without one with `changePassword` (#11999)

Rafał Pitoń16d2c86e0036
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b3e2c6fee5..af01ff96c6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Deprecate `Shop.orderSettings` query. Use `Channel.orderSettings` query instead.
- Deprecate `Shop.orderSettingsUpdate` mutation. Use `Channel.channelUpdate` instead.
- Add meta fields to `ProductMedia` model - #11894 by @zedzior
+- Make `oldPassword` argument on `passwordChange` mutation optional; support accounts without usable passwords - @11999 by @rafalp
### Other changes
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 8c8d29952f..4b76d13b50 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -2,6 +2,7 @@ from typing import cast
import graphene
from django.contrib.auth import password_validation
+from django.contrib.auth.hashers import make_password
from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import ObjectDoesNotExist, ValidationError
@@ -272,7 +273,7 @@ class PasswordChange(BaseMutation):
class Arguments:
old_password = graphene.String(
- required=True, description="Current user password."
+ required=False, description="Current user password."
)
new_password = graphene.String(required=True, description="New user password.")
@@ -282,22 +283,34 @@ class PasswordChange(BaseMutation):
error_type_field = "account_errors"
permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
+ @staticmethod
+ def raise_invalid_credentials():
+ raise ValidationError(
+ {
+ "old_password": ValidationError(
+ "Old password isn't valid.",
+ code=AccountErrorCode.INVALID_CREDENTIALS.value,
+ )
+ }
+ )
+
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
user = info.context.user
user = cast(models.User, user)
- old_password = data["old_password"]
+ old_password = data.get("old_password")
new_password = data["new_password"]
- if not user.check_password(old_password):
- raise ValidationError(
- {
- "old_password": ValidationError(
- "Old password isn't valid.",
- code=AccountErrorCode.INVALID_CREDENTIALS.value,
- )
- }
- )
+ if old_password is None:
+ # Spend time hashing useless password
+ # This prevents the outside actors from telling if user has
+ # unusable password set or not by measuring API's response time
+ make_password("waste-time")
+
+ if user.has_usable_password():
+ cls.raise_invalid_credentials()
+ elif not user.check_password(old_password):
+ cls.raise_invalid_credentials()
try:
password_validation.validate_password(new_password, user)
except ValidationError as error:
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index fc76f2f349..880ab3e48c 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -4377,7 +4377,7 @@ def test_set_password_invalid_password(user_api_client, customer_user, settings)
CHANGE_PASSWORD_MUTATION = """
- mutation PasswordChange($oldPassword: String!, $newPassword: String!) {
+ mutation PasswordChange($oldPassword: String, $newPassword: String!) {
passwordChange(oldPassword: $oldPassword, newPassword: $newPassword) {
errors {
field
@@ -4448,6 +4448,69 @@ def test_password_change_invalid_new_password(user_api_client, settings):
assert errors[1]["message"] == "This password is entirely numeric."
+def test_password_change_user_unusable_password_fails_if_old_password_is_set(
+ user_api_client,
+):
+ customer_user = user_api_client.user
+ customer_user.set_unusable_password()
+ customer_user.save()
+
+ 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 data["errors"]
+ assert data["errors"][0]["field"] == "oldPassword"
+
+ customer_user.refresh_from_db()
+ assert not customer_user.has_usable_password()
+
+
+def test_password_change_user_unusable_password_if_old_password_is_omitted(
+ user_api_client,
+):
+ customer_user = user_api_client.user
+ customer_user.set_unusable_password()
+ customer_user.save()
+
+ new_password = "spanish-inquisition"
+
+ variables = {"oldPassword": None, "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_CHANGED
+ assert password_change_event.user == customer_user
+
+
+def test_password_change_user_usable_password_fails_if_old_password_is_omitted(
+ user_api_client,
+):
+ customer_user = user_api_client.user
+
+ new_password = "spanish-inquisition"
+
+ variables = {"newPassword": new_password}
+ response = user_api_client.post_graphql(CHANGE_PASSWORD_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["passwordChange"]
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "oldPassword"
+
+ customer_user.refresh_from_db()
+ assert customer_user.has_usable_password()
+ assert not customer_user.check_password(new_password)
+
+
ADDRESS_CREATE_MUTATION = """
mutation CreateUserAddress($user: ID!, $address: AddressInput!) {
addressCreate(userId: $user, input: $address) {
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index d27e33ea45..a17e1fd928 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -15698,7 +15698,7 @@ type Mutation {
newPassword: String!
"""Current user password."""
- oldPassword: String!
+ oldPassword: String
): PasswordChange
"""