Skip to content

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

Introduce password login mode (#18917)

Iga Karbowiak094d2e9507fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 856c617868..27e7bf1753 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,8 +32,12 @@ All notable, unreleased changes to this project will be documented in this file.
- Added new scalar `NonNegativeInt` which allows integer values greater than or equal to zero.
- Scalars `Minute`, `Hour` and `Day` now inherit from `NonNegativeInt`, which mean GraphQL disallows negative values for time units.
- Removed `partial` field from the `Payment` GraphQL type.
+- Added `PasswordLoginMode` setting to control password-based authentication. When set to `DISABLED`, all password authentication mutations (`tokenCreate`, `setPassword`, `passwordChange`, `requestPasswordReset`, `tokenRefresh`) return errors. When set to `CUSTOMERS_ONLY`, staff users who log in with a password are treated as customers without staff
+permissions.
+- `staffDelete` mutation now always deletes the staff user. Previously, staff members with existing orders were only deactivated (`is_staff` set to `False`); now they are fully removed regardless of order history.
### Webhooks
+
- For order webhook events, sync webhooks (such as `ORDER_CALCULATE_TAXES` and `ORDER_FILTER_SHIPPING_METHODS`) are no longer pre-fired before sending async webhook events. Sync webhooks are now only triggered when their data is actually requested, improving performance and decoupling async event delivery from sync webhook execution.
- Building payloads for webhook order events (including draft orders and fulfillments) is now delegated to a separate background task. This speeds up the execution of most order mutations by deferring the expensive payload serialization out of the request path.
@@ -62,6 +66,7 @@ Validation is now performed on the frontend (Dashboard). This change increases v
- The app can now be installed without providing a `tokenTargetUrl` in the manifest file.
- Removed the setting `JWT_EXPIRE` which allowed to configure Saleor to ignore the JWT token expiration. - #18856 by @NyanKiyoshi
- Removed support for custom `User` DB models in `./manage.py createsuperuser` command. - #18890 by @NyanKiyoshi
+- OIDC: When an existing user is claimed by an OIDC provider for the first time, their password is now invalidated to prevent login with stale credentials. This covers the case where a previously deleted staff account is recreated via OIDC.
#### Search improvements
diff --git a/saleor/account/error_codes.py b/saleor/account/error_codes.py
index a66694988c..6a41180618 100644
--- a/saleor/account/error_codes.py
+++ b/saleor/account/error_codes.py
@@ -37,6 +37,7 @@ class AccountErrorCode(Enum):
MISSING_CHANNEL_SLUG = "missing_channel_slug"
ACCOUNT_NOT_CONFIRMED = "account_not_confirmed"
LOGIN_ATTEMPT_DELAYED = "login_attempt_delayed"
+ DISABLED_AUTHENTICATION_METHOD = "disabled_authentication_method"
UNKNOWN_IP_ADDRESS = "unknown_ip_address"
diff --git a/saleor/account/tests/test_utils.py b/saleor/account/tests/test_utils.py
index e1fe5dd84e..2451a02126 100644
--- a/saleor/account/tests/test_utils.py
+++ b/saleor/account/tests/test_utils.py
@@ -9,7 +9,6 @@ from ..models import Address, User
from ..utils import (
get_user_groups_permissions,
is_user_address_limit_reached,
- remove_staff_member,
remove_the_oldest_user_address,
remove_the_oldest_user_address_if_address_limit_is_reached,
retrieve_user_by_email,
@@ -19,29 +18,6 @@ from ..utils import (
from .fixtures.user import dangerously_create_test_user
-def test_remove_staff_member_with_orders(staff_user, permission_manage_products, order):
- # given
- order.user = staff_user
- order.save()
- staff_user.user_permissions.add(permission_manage_products)
-
- # when
- remove_staff_member(staff_user)
-
- # then
- staff_user = User.objects.get(pk=staff_user.pk)
- assert not staff_user.is_staff
- assert not staff_user.user_permissions.exists()
-
-
-def test_remove_staff_member(staff_user):
- # when
- remove_staff_member(staff_user)
-
- # then
- assert not User.objects.filter(pk=staff_user.pk).exists()
-
-
@override_settings(MAX_USER_ADDRESSES=2)
def test_is_user_address_limit_reached_true(customer_user, address):
"""Ensure that true is returned when a user has max amount of addresses assigned."""
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index 1e332231cb..2f4a8abef4 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -129,19 +129,6 @@ def change_user_default_address(
set_user_default_shipping_address(user, address)
-def remove_staff_member(staff):
- """Remove staff member account only if it has no orders placed.
-
- Otherwise, switches is_staff status to False.
- """
- if staff.orders.exists():
- staff.is_staff = False
- staff.user_permissions.clear()
- staff.save()
- else:
- staff.delete()
-
-
def retrieve_user_by_email(email):
"""Retrieve user by email.
diff --git a/saleor/core/auth_backend.py b/saleor/core/auth_backend.py
index 497eef7274..cbb8e70d62 100644
--- a/saleor/core/auth_backend.py
+++ b/saleor/core/auth_backend.py
@@ -4,11 +4,14 @@ from django.conf import settings
from ..account.models import User
from ..graphql.account.dataloaders import UserByEmailLoader
from ..graphql.plugins.dataloaders import AnonymousPluginManagerLoader
+from ..graphql.site.dataloaders import get_site_promise
from ..permission.enums import (
get_permissions_from_codenames,
get_permissions_from_names,
)
+from ..permission.models import Permission
from ..plugins.manager import get_plugins_manager
+from ..site import PasswordLoginMode
from .auth import get_token_from_request
from .jwt import (
JWT_ACCESS_TYPE,
@@ -149,6 +152,12 @@ def load_user_from_request(request):
"Invalid token. Create new one by using tokenCreate mutation."
)
+ site_settings = get_site_promise(request).get().settings
+ password_login_mode = site_settings.password_login_mode
+
+ if password_login_mode != PasswordLoginMode.ENABLED:
+ return _resolve_user_for_password_login_restriction(user, password_login_mode)
+
if permissions is not None:
token_permissions = get_permissions_from_names(permissions)
token_codenames = [perm.codename for perm in token_permissions]
@@ -157,4 +166,18 @@ def load_user_from_request(request):
if payload.get("is_staff"):
user.is_staff = True
+
return user
+
+
+def _resolve_user_for_password_login_restriction(user: User, password_login_mode: str):
+ """Resolve authenticated user for restricted password login modes.
+
+ Returns the user with staff access stripped in CUSTOMERS_ONLY mode.
+ Raises an error when password login is DISABLED.
+ """
+ if password_login_mode == PasswordLoginMode.CUSTOMERS_ONLY:
+ user.is_staff = False
+ user.effective_permissions = Permission.objects.none()
+ return user
+ raise jwt.InvalidTokenError("The authentication method is disabled.")
diff --git a/saleor/core/error_codes.py b/saleor/core/error_codes.py
index f397956fe4..c6ebdde713 100644
--- a/saleor/core/error_codes.py
+++ b/saleor/core/error_codes.py
@@ -9,6 +9,7 @@ class ShopErrorCode(Enum):
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
+ PASSWORD_AUTH_RESTRICTION = "password_auth_restriction"
class MetadataErrorCode(Enum):
diff --git a/saleor/core/tests/test_auth_backend_default_header.py b/saleor/core/tests/test_auth_backend_default_header.py
index 35d23f5c9b..32ea68ddff 100644
--- a/saleor/core/tests/test_auth_backend_default_header.py
+++ b/saleor/core/tests/test_auth_backend_default_header.py
@@ -5,6 +5,7 @@ from jwt import ExpiredSignatureError, InvalidSignatureError, InvalidTokenError
from ...permission.enums import get_permissions_from_names
from ...permission.models import Permission
+from ...site import PasswordLoginMode
from ..auth_backend import JSONWebTokenBackend
from ..jwt import (
JWT_ACCESS_TYPE,
@@ -217,3 +218,57 @@ def test_user_payload_doesnt_have_user_token(prefix, rf, staff_user, settings):
backend = JSONWebTokenBackend()
with pytest.raises(InvalidTokenError):
backend.authenticate(request)
+
+
[email protected]("prefix", ["JWT", "Bearer"])
+def test_staff_user_customers_only_mode(
+ prefix, rf, staff_user, permission_manage_products, site_settings
+):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.CUSTOMERS_ONLY
+ site_settings.save(update_fields=["password_login_mode"])
+ staff_user.user_permissions.add(permission_manage_products)
+ access_token = create_access_token(staff_user)
+
+ # when
+ request = rf.request(HTTP_AUTHORIZATION=f"{prefix} {access_token}")
+ backend = JSONWebTokenBackend()
+ user = backend.authenticate(request)
+
+ # then
+ assert user == staff_user
+ assert user.is_staff is False
+ assert list(user.effective_permissions) == []
+
+
[email protected]("prefix", ["JWT", "Bearer"])
+def test_customer_user_customers_only_mode(prefix, rf, customer_user, site_settings):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.CUSTOMERS_ONLY
+ site_settings.save(update_fields=["password_login_mode"])
+ access_token = create_access_token(customer_user)
+
+ # when
+ request = rf.request(HTTP_AUTHORIZATION=f"{prefix} {access_token}")
+ backend = JSONWebTokenBackend()
+ user = backend.authenticate(request)
+
+ # then
+ assert user == customer_user
+ assert user.is_staff is False
+
+
[email protected]("prefix", ["JWT", "Bearer"])
+def test_staff_user_disabled_mode(prefix, rf, staff_user, site_settings):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.DISABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ access_token = create_access_token(staff_user)
+
+ # when
+ request = rf.request(HTTP_AUTHORIZATION=f"{prefix} {access_token}")
+ backend = JSONWebTokenBackend()
+
+ # then
+ with pytest.raises(InvalidTokenError):
+ backend.authenticate(request)
diff --git a/saleor/core/tests/test_jwt.py b/saleor/core/tests/test_jwt.py
index d17e5638f9..0b2062e2fe 100644
--- a/saleor/core/tests/test_jwt.py
+++ b/saleor/core/tests/test_jwt.py
@@ -4,10 +4,13 @@ from cryptography.hazmat.primitives import serialization
from django.urls import reverse
from ..jwt import (
+ JWT_ACCESS_TYPE,
create_access_token_for_app,
create_access_token_for_app_extension,
+ get_user_from_access_payload,
jwt_decode,
jwt_encode,
+ jwt_user_payload,
)
from ..utils import build_absolute_uri
@@ -186,3 +189,36 @@ def test_jwt_encode_creates_token_signed_with_rs256(settings):
# then
headers = jwt.get_unverified_header(token)
assert headers.get("alg") == "RS256"
+
+
+def test_get_user_from_access_payload_with_is_staff_true(
+ staff_user, settings, permission_manage_products
+):
+ # given
+ staff_user.user_permissions.add(permission_manage_products)
+ payload = jwt_user_payload(staff_user, JWT_ACCESS_TYPE, settings.JWT_TTL_ACCESS)
+ assert payload["is_staff"] is True
+
+ # when
+ user = get_user_from_access_payload(payload)
+
+ # then
+ assert user == staff_user
+ assert user.is_staff is True
+ assert permission_manage_products in user.effective_permissions
+
+
+def test_get_user_from_access_payload_for_customer(customer_user, settings):
+ # given
+ payload = jwt_user_payload(
+ customer_user,
+ JWT_ACCESS_TYPE,
+ settings.JWT_TTL_ACCESS,
+ )
+
+ # when
+ user = get_user_from_access_payload(payload)
+
+ # then
+ assert user == customer_user
+ assert user.is_staff is False
diff --git a/saleor/graphql/account/mutations/authentication/create_token.py b/saleor/graphql/account/mutations/authentication/create_token.py
index 5853ffc36d..4e3ca081a6 100644
--- a/saleor/graphql/account/mutations/authentication/create_token.py
+++ b/saleor/graphql/account/mutations/authentication/create_token.py
@@ -1,3 +1,5 @@
+from typing import Any
+
import graphene
from django.core.exceptions import ValidationError
@@ -10,7 +12,11 @@ from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ....site.dataloaders import get_site_promise
from ...types import User
-from .utils import _get_new_csrf_token, update_user_last_login_if_required
+from .utils import (
+ _get_new_csrf_token,
+ check_password_login_not_disabled,
+ update_user_last_login_if_required,
+)
class CreateToken(BaseMutation):
@@ -85,18 +91,22 @@ class CreateToken(BaseMutation):
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, audience=None, email, password
):
- additional_paylod = {}
+ additional_payload: dict[str, Any] = {}
+
+ site_settings = get_site_promise(info.context).get().settings
+ check_password_login_not_disabled(site_settings)
csrf_token = _get_new_csrf_token()
- refresh_additional_payload = {
+ refresh_additional_payload: dict[str, Any] = {
"csrfToken": csrf_token,
}
if audience:
- additional_paylod["aud"] = f"custom:{audience}"
+ additional_payload["aud"] = f"custom:{audience}"
refresh_additional_payload["aud"] = f"custom:{audience}"
user = cls.get_user(info, email, password)
- access_token = create_access_token(user, additional_payload=additional_paylod)
+
+ access_token = create_access_token(user, additional_payload=additional_payload)
refresh_token = create_refresh_token(
user, additional_payload=refresh_additional_payload
)
diff --git a/saleor/graphql/account/mutations/authentication/password_change.py b/saleor/graphql/account/mutations/authentication/password_change.py
index 3778ef9ef1..1c162897f5 100644
--- a/saleor/graphql/account/mutations/authentication/password_change.py
+++ b/saleor/graphql/account/mutations/authentication/password_change.py
@@ -13,7 +13,9 @@ from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_USERS
from ....core.mutations import BaseMutation
from ....core.types import AccountError
+from ....site.dataloaders import get_site_promise
from ...types import User
+from .utils import check_password_login_not_disabled
class PasswordChange(BaseMutation):
@@ -45,6 +47,9 @@ class PasswordChange(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ site_settings = get_site_promise(info.context).get().settings
+ check_password_login_not_disabled(site_settings)
+
user = info.context.user
user = cast(models.User, user)
old_password = data.get("old_password")
diff --git a/saleor/graphql/account/mutations/authentication/refresh_token.py b/saleor/graphql/account/mutations/authentication/refresh_token.py
index 18ecc29225..6a3b01aef6 100644
--- a/saleor/graphql/account/mutations/authentication/refresh_token.py
+++ b/saleor/graphql/account/mutations/authentication/refresh_token.py
@@ -11,9 +11,11 @@ from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_AUTH
from ....core.mutations import BaseMutation
from ....core.types import AccountError
+from ....site.dataloaders import get_site_promise
from ...types import User
from .utils import (
_does_token_match,
+ check_password_login_not_disabled,
get_payload,
get_user,
update_user_last_login_if_required,
@@ -122,6 +124,9 @@ class RefreshToken(BaseMutation):
def perform_mutation(
cls, _root, info: ResolveInfo, /, *, csrf_token=None, refresh_token=None
):
+ site_settings = get_site_promise(info.context).get().settings
+ check_password_login_not_disabled(site_settings)
+
need_csrf = refresh_token is None
refresh_token = cls.get_refresh_token(info, refresh_token)
payload = cls.clean_refresh_token(refresh_token)
diff --git a/saleor/graphql/account/mutations/authentication/request_password_reset.py b/saleor/graphql/account/mutations/authentication/request_password_reset.py
index 2eba55ebe4..f29f866fed 100644
--- a/saleor/graphql/account/mutations/authentication/request_password_reset.py
+++ b/saleor/graphql/account/mutations/authentication/request_password_reset.py
@@ -14,6 +14,8 @@ from ....core.doc_category import DOC_CATEGORY_USERS
from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ....core.utils import WebhookEventInfo
+from ....site.dataloaders import get_site_promise
+from .utils import check_password_login_not_disabled
class RequestPasswordReset(BaseMutation):
@@ -80,6 +82,9 @@ class RequestPasswordReset(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ site_settings = get_site_promise(info.context).get().settings
+ check_password_login_not_disabled(site_settings)
+
email = data["email"]
redirect_url = data["redirect_url"]
user = cls.clean_user(email, redirect_url)
diff --git a/saleor/graphql/account/mutations/authentication/set_password.py b/saleor/graphql/account/mutations/authentication/set_password.py
index 53c3326937..4467fa9eb0 100644
--- a/saleor/graphql/account/mutations/authentication/set_password.py
+++ b/saleor/graphql/account/mutations/authentication/set_password.py
@@ -13,8 +13,10 @@ from ....core.context import disallow_replica_in_context
from ....core.doc_category import DOC_CATEGORY_USERS
from ....core.mutations import validation_error_to_error_type
from ....core.types import AccountError
+from ....site.dataloaders import get_site_promise
from ..base import INVALID_TOKEN
from . import CreateToken
+from .utils import check_password_login_not_disabled
class SetPassword(CreateToken):
@@ -41,7 +43,9 @@ class SetPassword(CreateToken):
):
disallow_replica_in_context(info.context)
+ site_settings = get_site_promise(info.context).get().settings
try:
+ check_password_login_not_disabled(site_settings)
cls._set_password_for_user(email, password, token)
except ValidationError as e:
errors = validation_error_to_error_type(e, AccountError)
diff --git a/saleor/graphql/account/mutations/authentication/utils.py b/saleor/graphql/account/mutations/authentication/utils.py
index d67d4f81e3..f999c82c1f 100644
--- a/saleor/graphql/account/mutations/authentication/utils.py
+++ b/saleor/graphql/account/mutations/authentication/utils.py
@@ -15,6 +15,8 @@ from .....account.error_codes import AccountErrorCode
from .....account.models import User
from .....core.jwt import PERMISSIONS_FIELD, get_user_from_payload, jwt_decode
from .....permission.enums import get_permissions_from_names
+from .....site import PasswordLoginMode
+from .....site.models import SiteSettings
def get_user(payload):
@@ -61,6 +63,15 @@ def _does_token_match(token: str, csrf_token: str) -> bool:
)
+def check_password_login_not_disabled(site_settings: SiteSettings):
+ """Raise ValidationError if password-based authentication is disabled."""
+ if site_settings.password_login_mode == PasswordLoginMode.DISABLED:
+ raise ValidationError(
+ "Password-based login is disabled.",
+ code=AccountErrorCode.DISABLED_AUTHENTICATION_METHOD.value,
+ )
+
+
def update_user_last_login_if_required(user: User):
time_now = timezone.now()
threshold_delta = datetime.timedelta(
diff --git a/saleor/graphql/account/mutations/staff/staff_delete.py b/saleor/graphql/account/mutations/staff/staff_delete.py
index 5dc751d121..f61f8ba6a8 100644
--- a/saleor/graphql/account/mutations/staff/staff_delete.py
+++ b/saleor/graphql/account/mutations/staff/staff_delete.py
@@ -1,7 +1,6 @@
import graphene
from .....account import models
-from .....account.utils import remove_staff_member
from .....permission.enums import AccountPermissions
from .....webhook.event_types import WebhookEventAsyncType
from ....account.types import User
@@ -43,7 +42,7 @@ class StaffDelete(StaffDeleteMixin, UserDelete):
cls.clean_instance(info, instance)
db_id = instance.id
- remove_staff_member(instance)
+ instance.delete()
# After the instance is deleted, set its ID to the original database's
# ID so that the success response contains ID of the deleted object.
instance.id = db_id
diff --git a/saleor/graphql/account/tests/benchmark/test_account.py b/saleor/graphql/account/tests/benchmark/test_account.py
index 9db2b8539b..6c26ad6d56 100644
--- a/saleor/graphql/account/tests/benchmark/test_account.py
+++ b/saleor/graphql/account/tests/benchmark/test_account.py
@@ -5,6 +5,7 @@ import pytest
from django.core.files import File
from .....account.models import Group, User
+from .....site.models import Site
from ....tests.utils import get_graphql_content
@@ -402,7 +403,7 @@ def test_users_for_federation_query_count(
}
staff_api_client.ensure_access_token()
- with django_assert_num_queries(4):
+ with django_assert_num_queries(6):
response = staff_api_client.post_graphql(
query,
variables,
@@ -412,6 +413,10 @@ def test_users_for_federation_query_count(
content = get_graphql_content(response)
assert len(content["data"]["_entities"]) == 2
+ # Clear cache for proper query count comparison.
+ # Site and site settings are cached in `auth_backend` when querying the current site.
+ Site.objects.clear_cache()
+
variables = {
"representations": [
{
@@ -433,7 +438,7 @@ def test_users_for_federation_query_count(
],
}
- with django_assert_num_queries(4):
+ with django_assert_num_queries(6):
response = staff_api_client.post_graphql(
query,
variables,
@@ -481,7 +486,7 @@ def test_addresses_for_federation_query_count(
}
staff_api_client.ensure_access_token()
- with django_assert_num_queries(3):
+ with django_assert_num_queries(5):
response = staff_api_client.post_graphql(
query,
variables,
@@ -491,6 +496,10 @@ def test_addresses_for_federation_query_count(
content = get_graphql_content(response)
assert len(content["data"]["_entities"]) == 1
+ # Clear cache for proper query count comparison.
+ # Site and site settings are cached in `auth_backend` when querying the current site.
+ Site.objects.clear_cache()
+
variables = {
"representations": [
{
@@ -504,7 +513,7 @@ def test_addresses_for_federation_query_count(
],
}
- with django_assert_num_queries(3):
+ with django_assert_num_queries(5):
response = staff_api_client.post_graphql(
query,
variables,
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_password_change.py b/saleor/graphql/account/tests/mutations/authentication/test_password_change.py
index 7303ccab94..e0702cef11 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_password_change.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_password_change.py
@@ -1,5 +1,6 @@
from ......account import events as account_events
-from .....tests.utils import get_graphql_content
+from ......site import PasswordLoginMode
+from .....tests.utils import get_graphql_content, get_graphql_content_from_response
CHANGE_PASSWORD_MUTATION = """
mutation PasswordChange($oldPassword: String, $newPassword: String!) {
@@ -7,6 +8,7 @@ CHANGE_PASSWORD_MUTATION = """
errors {
field
message
+ code
}
user {
email
@@ -134,3 +136,21 @@ def test_password_change_user_usable_password_fails_if_old_password_is_omitted(
customer_user.refresh_from_db()
assert customer_user.has_usable_password()
assert not customer_user.check_password(new_password)
+
+
+def test_password_change_disabled_password_login(user_api_client, site_settings):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.DISABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ variables = {"oldPassword": "password", "newPassword": "new-password"}
+
+ # when
+ response = user_api_client.post_graphql(CHANGE_PASSWORD_MUTATION, variables)
+
+ # then
+ content = get_graphql_content_from_response(response)
+ assert "errors" in content, content
+ assert content["errors"][0]["message"] == "The authentication method is disabled."
+
+ user_api_client.user.refresh_from_db()
+ assert user_api_client.user.check_password("password")
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 32214395da..d6c82cd78a 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,11 +6,13 @@ from urllib.parse import urlencode
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
from ......core.tokens import token_generator
from ......core.utils.url import prepare_url
+from ......site import PasswordLoginMode
from .....tests.utils import get_graphql_content
REQUEST_PASSWORD_RESET_MUTATION = """
@@ -595,3 +597,26 @@ def test_account_reset_password_no_channel_provided_one_channel(
)
mocked_logger_warning.assert_not_called()
+
+
+def test_request_password_reset_disabled_password_login(
+ api_client, customer_user, site_settings, channel_PLN
+):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.DISABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ variables = {
+ "email": customer_user.email,
+ "redirectUrl": "https://www.example.com",
+ "channel": channel_PLN.slug,
+ }
+
+ # 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
+ error = data["errors"][0]
+ assert error["code"] == AccountErrorCode.DISABLED_AUTHENTICATION_METHOD.name
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 777c78dab6..e89b0bf454 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_set_password.py
@@ -6,6 +6,7 @@ from ......account import events as account_events
from ......account.error_codes import AccountErrorCode
from ......account.tests.fixtures.user import dangerously_create_test_user
from ......core.tokens import token_generator
+from ......site import PasswordLoginMode
from .....core.utils import str_to_enum
from .....tests.utils import get_graphql_content
from ....mutations.base import INVALID_TOKEN
@@ -183,3 +184,32 @@ def test_set_password_invalid_password(
account_errors = content["data"]["setPassword"]["errors"]
assert account_errors[0]["code"] == str_to_enum("password_too_short")
assert account_errors[1]["code"] == str_to_enum("password_entirely_numeric")
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_set_password_disabled_password_login(user_api_client, site_settings):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.DISABLED
+ site_settings.save(update_fields=["password_login_mode"])
+
+ customer_user = dangerously_create_test_user(
+ email="[email protected]", password="old-password"
+ )
+ token = token_generator.make_token(customer_user)
+ variables = {
+ "email": customer_user.email,
+ "password": "new-password",
+ "token": token,
+ }
+
+ # when
+ response = user_api_client.post_graphql(SET_PASSWORD_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["setPassword"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == AccountErrorCode.DISABLED_AUTHENTICATION_METHOD.name
+
+ customer_user.refresh_from_db()
+ assert customer_user.check_password("old-password")
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
index 0642d9b5f4..1df2c71620 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
@@ -19,6 +19,7 @@ from ......core.jwt import (
jwt_decode,
)
from ......core.utils import build_absolute_uri
+from ......site import PasswordLoginMode
from .....tests.utils import get_graphql_content
from ....mutations.authentication.utils import _get_new_csrf_token
@@ -527,3 +528,93 @@ def test_create_token_throttling_unidentified_ip_address(
error = errors[0]
assert error["code"] == AccountErrorCode.UNKNOWN_IP_ADDRESS.name
assert error["field"] is None
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.account.throttling.cache")
+def test_create_token_disabled_password_login(
+ _mocked_cache, api_client, customer_user, site_settings
+):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.DISABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ variables = {"email": customer_user.email, "password": customer_user._password}
+
+ # when
+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["tokenCreate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == AccountErrorCode.DISABLED_AUTHENTICATION_METHOD.name
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.account.throttling.cache")
+def test_create_token_disabled_password_login_for_staff(
+ _mocked_cache, api_client, staff_user, site_settings
+):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.DISABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ variables = {"email": staff_user.email, "password": "password"}
+
+ # when
+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["tokenCreate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == AccountErrorCode.DISABLED_AUTHENTICATION_METHOD.name
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.account.throttling.cache")
+def test_create_token_customers_only_mode_for_customer(
+ _mocked_cache, api_client, customer_user, site_settings
+):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.CUSTOMERS_ONLY
+ site_settings.save(update_fields=["password_login_mode"])
+ variables = {"email": customer_user.email, "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 data["errors"] == []
+ assert data["token"]
+
+ payload = jwt_decode(data["token"])
+ assert payload["is_staff"] is False
+ assert payload["email"] == customer_user.email
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.account.throttling.cache")
+def test_create_token_enabled_mode_for_staff(
+ _mocked_cache, api_client, staff_user, site_settings
+):
+ # given
+ site_settings.password_login_mode = PasswordLoginMode.ENABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ variables = {"email": staff_user.email, "password": "password"}
+
+ # when
+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["tokenCreate"]
+ assert data["errors"] == []
+ assert data["token"]
+
+ payload = jwt_decode(data["token"])
+ assert payload["is_staff"] is True
+ assert payload["email"] == staff_user.email
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py b/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
index b4788af7de..60b0047547 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
@@ -14,6 +14,7 @@ from ......core.jwt import (
jwt_decode,
)
from ......core.utils import build_absolute_uri
+from ......site import PasswordLoginMode
from .....tests.utils import get_graphql_content
from ....mutations.authentication.utils import _get_new_csrf_token
@@ -372,3 +373,49 @@ def test_refresh_token_do_update_last_login_when_out_of_threshold(
assert customer_user.last_login != previous_last_login
assert customer_user.updated_at == time_ouf_of_threshold
assert customer_user.last_login == time_ouf_of_threshold
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_refresh_token_for_staff_user(api_client, staff_user, settings):
+ # given
+ csrf_token = _get_new_csrf_token()
+ refresh_token = create_refresh_token(staff_user, {"csrfToken": csrf_token})
+ variables = {"token": refresh_token, "csrf_token": None}
+
+ # when
+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["tokenRefresh"]
+ assert not data["errors"]
+ token = data["token"]
+ payload = jwt_decode(token)
+ assert payload["is_staff"] is True
+ assert payload["email"] == staff_user.email
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_refresh_token_when_password_login_disabled(
+ api_client, staff_user, site_settings
+):
+ # given
+ csrf_token = _get_new_csrf_token()
+ refresh_token = create_refresh_token(staff_user, {"csrfToken": csrf_token})
+ variables = {"token": refresh_token, "csrf_token": None}
+
+ site_settings.password_login_mode = PasswordLoginMode.DISABLED
+ site_settings.save(update_fields=["password_login_mode"])
+
+ # when
+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["tokenRefresh"]
+ assert len(data["errors"]) == 1
+ assert (
+ data["errors"][0]["code"]
+ == AccountErrorCode.DISABLED_AUTHENTICATION_METHOD.name
+ )
+ assert data["token"] is None
diff --git a/saleor/graphql/account/tests/mutations/staff/test_staff_delete.py b/saleor/graphql/account/tests/mutations/staff/test_staff_delete.py
index 9b7fea6bd0..cd570dbc60 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_staff_delete.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_staff_delete.py
@@ -50,6 +50,27 @@ def test_staff_delete(staff_api_client, permission_manage_staff):
assert not User.objects.filter(pk=staff_user.id).exists()
+def test_staff_delete_with_orders(staff_api_client, permission_manage_staff, order):
+ # given
+ staff_user = User.objects.create(email="[email protected]", is_staff=True)
+ order.user = staff_user
+ order.save(update_fields=["user"])
+
+ user_id = graphene.Node.to_global_id("User", staff_user.id)
+ variables = {"id": user_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ STAFF_DELETE_MUTATION, variables, permissions=[permission_manage_staff]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["staffDelete"]
+ assert data["errors"] == []
+ assert not User.objects.filter(pk=staff_user.id).exists()
+
+
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
diff --git a/saleor/graphql/app/tests/benchmarks/test_apps.py b/saleor/graphql/app/tests/benchmarks/test_apps.py
index 52e841f18a..38211b2727 100644
--- a/saleor/graphql/app/tests/benchmarks/test_apps.py
+++ b/saleor/graphql/app/tests/benchmarks/test_apps.py
@@ -2,6 +2,7 @@ import graphene
import pytest
from .....app.models import App, AppToken
+from .....site.models import Site
from .....webhook.models import Webhook
from ....tests.utils import get_graphql_content
@@ -44,7 +45,7 @@ def test_apps_for_federation_query_count(
}
staff_api_client.ensure_access_token()
- with django_assert_num_queries(4):
+ with django_assert_num_queries(6):
response = staff_api_client.post_graphql(
query,
variables,
@@ -54,6 +55,10 @@ def test_apps_for_federation_query_count(
content = get_graphql_content(response)
assert len(content["data"]["_entities"]) == 1
+ # Clear cache for proper query count comparison.
+ # Site and site settings are cached in `auth_backend` when querying the current site.
+ Site.objects.clear_cache()
+
variables = {
"representations": [
{
@@ -64,7 +69,7 @@ def test_apps_for_federation_query_count(
],
}
- with django_assert_num_queries(4):
+ with django_assert_num_queries(6):
response = staff_api_client.post_graphql(
query,
variables,
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 7e6646485f..c56fdce2c7 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -17,6 +17,7 @@ from .....plugins.manager import get_plugins_manager
from .....product.models import Product, ProductVariant, ProductVariantChannelListing
from .....product.utils.variant_prices import update_discounted_prices_for_promotion
from .....product.utils.variants import fetch_variants_for_promotion_rules
+from .....site.models import Site
from .....warehouse.models import Stock
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -838,6 +839,10 @@ def test_update_checkout_lines_with_reservations(
data = content["data"]["checkoutLinesUpdate"]
assert not data["errors"]
+ # Clear cache for proper query count comparison.
+ # Site and site settings are cached in `auth_backend` when querying the current site.
+ Site.objects.clear_cache()
+
# Updating multiple lines in checkout has same query count as updating one
with django_assert_num_queries(107):
variables = {
@@ -1110,6 +1115,10 @@ def test_add_checkout_lines_with_reservations(
data = content["data"]["checkoutLinesAdd"]
assert not data["errors"]
+ # Clear cache for proper query count comparison.
+ # Site and site settings are cached in `auth_backend` when querying the current site.
+ Site.objects.clear_cache()
+
checkout.lines.exclude(id=line.id).delete()
with django_assert_num_queries(104):
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
index 1fb57beed7..e5477cdf58 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
@@ -197,7 +197,7 @@ def test_promotion_create_order_promotion(
# when
staff_api_client.ensure_access_token()
- with django_assert_num_queries(36):
+ with django_assert_num_queries(38):
response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)
# then
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py b/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
index 00419b317c..bc2243ff9b 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
@@ -51,7 +51,7 @@ def test_gift_promotion_delete(
# when
staff_api_client.ensure_access_token()
- with django_assert_num_queries(24):
+ with django_assert_num_queries(26):
content = get_graphql_content(
staff_api_client.post_graphql(PROMOTION_DELETE_MUTATION, variables)
)
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py
index 29d9b136d6..3be3018965 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py
@@ -134,7 +134,7 @@ def test_promotion_rule_create_gift(
# when
staff_api_client.ensure_access_token()
- with django_assert_num_queries(16):
+ with django_assert_num_queries(18):
content = get_graphql_content(
staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
)
diff --git a/saleor/graphql/discount/tests/benchmark/test_voucher_code_bulk_delete.py b/saleor/graphql/discount/tests/benchmark/test_voucher_code_bulk_delete.py
index ac48a816e4..883750e686 100644
--- a/saleor/graphql/discount/tests/benchmark/test_voucher_code_bulk_delete.py
+++ b/saleor/graphql/discount/tests/benchmark/test_voucher_code_bulk_delete.py
@@ -1,6 +1,7 @@
import graphene
import pytest
+from .....site.models import Site
from ....tests.utils import get_graphql_content
VOUCHER_CODE_BULK_DELETE_MUTATION = """
@@ -30,16 +31,20 @@ def test_voucher_code_bulk_delete_queries(
# when
staff_api_client.ensure_access_token()
- with django_assert_num_queries(9):
+ with django_assert_num_queries(11):
response = staff_api_client.post_graphql(
VOUCHER_CODE_BULK_DELETE_MUTATION, variables
)
content = get_graphql_content(response)
assert content["data"]["voucherCodeBulkDelete"]["count"] == 1
+ # Clear cache for proper query count comparison.
+ # Site and site settings are cached in `auth_backend` when querying the current site.
+ Site.objects.clear_cache()
+
variables = {"ids": ids[1:]}
- with django_assert_num_queries(9):
+ with django_assert_num_queries(11):
response = staff_api_client.post_graphql(
VOUCHER_CODE_BULK_DELETE_MUTATION, variables
)
diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.py
index b0d17aeeb4..8f15301b76 100644
--- a/saleor/graphql/product/tests/benchmark/test_product.py
+++ b/saleor/graphql/product/tests/benchmark/test_product.py
@@ -13,6 +13,7 @@ from .....channel.models import Channel
from .....core.taxes import TaxType
from .....plugins.manager import PluginsManager
from .....product.models import ProductChannelListing, ProductMedia, ProductTranslation
+from .....site.models import Site
from ....tests.utils import get_graphql_content
@@ -322,7 +323,7 @@ def test_retrieve_channel_listings(
variables = {"channel": channel_USD.slug}
- expected_db_queries = 14
+ expected_db_queries = 16
with django_assert_num_queries(expected_db_queries):
get_graphql_content(
staff_api_client.post_graphql(
@@ -333,6 +334,10 @@ def test_retrieve_channel_listings(
)
)
+ # Clear cache for proper query count comparison.
+ # Site and site settings are cached in `auth_backend` when querying the current site.
+ Site.objects.clear_cache()
+
ProductChannelListing.objects.bulk_create(
[
ProductChannelListing(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 50b347520f..ad772c5d2f 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -15183,6 +15183,13 @@ type Shop implements ObjectWithMetadata {
"""
preserveAllAddressFields: Boolean!
+ """
+ Controls whether password-based authentication is allowed.
+
+ Added in Saleor 3.23.
+ """
+ passwordLoginMode: PasswordLoginModeEnum!
+
"""Include taxes in prices."""
includeTaxesInPrices: Boolean! @deprecated(reason: "Use `Channel.taxConfiguration.pricesEnteredWithTax` to determine whether prices are entered with tax.")
@@ -15286,6 +15293,21 @@ type Limits {
warehouses: Int
}
+"""
+Controls whether password-based authentication is allowed.
+
+ ENABLED - any user can log in with a password. This is the default behavior.
+ CUSTOMERS_ONLY - only customer users can log in with a password.
+ If a staff user logs in with a password, they will be treated as a customer
+ — the issued token will not contain any staff permissions.
+ DISABLED - no user can log in with a password.
+"""
+enum PasswordLoginModeEnum @doc(category: "Authentication") {
+ ENABLED
+ CUSTOMERS_ONLY
+ DISABLED
+}
+
"""Gift card related settings from site settings."""
type GiftCardSettings @doc(category: "Gift cards") {
"""The gift card expiry type settings."""
@@ -22942,6 +22964,7 @@ enum ShopErrorCode {
NOT_FOUND
REQUIRED
UNIQUE
+ PASSWORD_AUTH_RESTRICTION
}
input StaffNotificationRecipientInput {
@@ -23093,6 +23116,13 @@ input ShopSettingsInput {
"""
preserveAllAddressFields: Boolean
+ """
+ Controls whether password-based authentication is allowed.
+
+ Added in Saleor 3.23.
+ """
+ passwordLoginMode: PasswordLoginModeEnum
+
"""Include taxes in prices."""
includeTaxesInPrices: Boolean @deprecated(reason: "Use `taxConfigurationUpdate` mutation to configure this setting per channel or country.")
@@ -32655,6 +32685,7 @@ enum AccountErrorCode @doc(category: "Users") {
MISSING_CHANNEL_SLUG
ACCOUNT_NOT_CONFIRMED
LOGIN_ATTEMPT_DELAYED
+ DISABLED_AUTHENTICATION_METHOD
UNKNOWN_IP_ADDRESS
}
diff --git a/saleor/graphql/shop/enums.py b/saleor/graphql/shop/enums.py
index 5388c836fb..07395423f9 100644
--- a/saleor/graphql/shop/enums.py
+++ b/saleor/graphql/shop/enums.py
@@ -2,11 +2,18 @@ from typing import Final
import graphene
-from ...site import GiftCardSettingsExpiryType
-from ..core.doc_category import DOC_CATEGORY_GIFT_CARDS
+from ...site import GiftCardSettingsExpiryType, PasswordLoginMode
+from ..core.doc_category import DOC_CATEGORY_AUTH, DOC_CATEGORY_GIFT_CARDS
from ..core.enums import to_enum
GiftCardSettingsExpiryTypeEnum: Final[graphene.Enum] = to_enum(
GiftCardSettingsExpiryType
)
GiftCardSettingsExpiryTypeEnum.doc_category = DOC_CATEGORY_GIFT_CARDS
+
+PasswordLoginModeEnum: Final[graphene.Enum] = to_enum(
+ PasswordLoginMode,
+ type_name="PasswordLoginModeEnum",
+ description=PasswordLoginMode.__doc__,
+)
+PasswordLoginModeEnum.doc_category = DOC_CATEGORY_AUTH
diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.py
index b52c7ff465..a8eb5c9944 100644
--- a/saleor/graphql/shop/mutations/shop_settings_update.py
+++ b/saleor/graphql/shop/mutations/shop_settings_update.py
@@ -2,12 +2,14 @@ import graphene
from django.core.exceptions import ValidationError
from ....core.error_codes import ShopErrorCode
+from ....core.jwt import JWT_SALEOR_OWNER_NAME
from ....core.utils.url import validate_storefront_url
from ....permission.enums import SitePermissions
+from ....site import PasswordLoginMode
from ....site.models import DEFAULT_LIMIT_QUANTITY_PER_CHECKOUT
from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
-from ...core.descriptions import ADDED_IN_322, DEPRECATED_IN_3X_INPUT
+from ...core.descriptions import ADDED_IN_322, ADDED_IN_323, DEPRECATED_IN_3X_INPUT
from ...core.doc_category import DOC_CATEGORY_SHOP
from ...core.enums import WeightUnitsEnum
from ...core.mutations import BaseMutation
@@ -17,6 +19,7 @@ from ...core.utils import WebhookEventInfo
from ...meta.inputs import MetadataInput, MetadataInputDescription
from ...plugins.dataloaders import get_plugin_manager_promise
from ...site.dataloaders import get_site_promise
+from ..enums import PasswordLoginModeEnum
from ..types import Shop
@@ -99,6 +102,10 @@ class ShopSettingsInput(graphene.InputObjectType):
)
+ ADDED_IN_322,
)
+ password_login_mode = PasswordLoginModeEnum(
+ description="Controls whether password-based authentication is allowed."
+ + ADDED_IN_323,
+ )
# deprecated
include_taxes_in_prices = graphene.Boolean(
@@ -163,7 +170,27 @@ class ShopSettingsUpdate(BaseMutation):
]
@classmethod
- def clean_input(cls, _info, _instance, data):
+ def _validate_password_login_mode_restriction(cls, info, data):
+ if "password_login_mode" in data and data["password_login_mode"] in (
+ PasswordLoginMode.DISABLED,
+ PasswordLoginMode.CUSTOMERS_ONLY,
+ ):
+ decoded_token = info.context.decoded_auth_token or {}
+ if decoded_token.get("owner") == JWT_SALEOR_OWNER_NAME:
+ raise ValidationError(
+ {
+ "password_login_mode": ValidationError(
+ "Cannot restrict password login while authenticated "
+ "with a password.",
+ code=ShopErrorCode.PASSWORD_AUTH_RESTRICTION.value,
+ )
+ }
+ )
+
+ @classmethod
+ def clean_input(cls, info, _instance, data):
+ cls._validate_password_login_mode_restriction(info, data)
+
if data.get("customer_set_password_url"):
try:
validate_storefront_url(data["customer_set_password_url"])
diff --git a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
index 5a4ef01b81..c060d63f9d 100644
--- a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
+++ b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
@@ -1,10 +1,12 @@
-from unittest.mock import ANY
+from unittest.mock import ANY, patch
import pytest
from .....core.error_codes import ShopErrorCode
+from .....core.jwt import JWT_OWNER_FIELD
from .....site.models import Site
from ....tests.utils import get_graphql_content
+from ...enums import PasswordLoginModeEnum
SHOP_SETTINGS_UPDATE_MUTATION = """
mutation updateSettings($input: ShopSettingsInput!) {
@@ -476,3 +478,106 @@ def test_update_default_sender_settings_invalid_email(
assert errors == [
{"field": "defaultMailSenderAddress", "message": "Enter a valid email address."}
]
+
+
+MUTATION_UPDATE_PASSWORD_LOGIN_MODE = """
+ mutation updateSettings($input: ShopSettingsInput!) {
+ shopSettingsUpdate(input: $input) {
+ shop {
+ passwordLoginMode
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+ "mode",
+ [PasswordLoginModeEnum.DISABLED.name, PasswordLoginModeEnum.CUSTOMERS_ONLY.name],
+)
+def test_shop_settings_update_password_login_mode_blocked_for_password_auth(
+ staff_api_client, site_settings, permission_manage_settings, mode
+):
+ # given
+ variables = {"input": {"passwordLoginMode": mode}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_PASSWORD_LOGIN_MODE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["shopSettingsUpdate"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "passwordLoginMode"
+ assert error["code"] == ShopErrorCode.PASSWORD_AUTH_RESTRICTION.name
+ site_settings.refresh_from_db()
+ assert site_settings.password_login_mode == PasswordLoginModeEnum.ENABLED.value
+
+
+ "mode",
+ [
+ PasswordLoginModeEnum.ENABLED.name,
+ PasswordLoginModeEnum.DISABLED.name,
+ PasswordLoginModeEnum.CUSTOMERS_ONLY.name,
+ ],
+)
+def test_shop_settings_update_password_login_mode_allowed_for_oidc_auth(
+ staff_api_client, site_settings, permission_manage_settings, mode
+):
+ # given
+ oidc_owner = "mirumee.authentication.openidconnect"
+ oidc_token_payload = {JWT_OWNER_FIELD: oidc_owner}
+ variables = {"input": {"passwordLoginMode": mode}}
+
+ # when
+ with patch(
+ "saleor.graphql.context.jwt_decode_with_exception_handler",
+ return_value=oidc_token_payload,
+ ):
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_PASSWORD_LOGIN_MODE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["shopSettingsUpdate"]
+ assert not data["errors"]
+ assert data["shop"]["passwordLoginMode"] == mode
+
+
+def test_shop_settings_update_password_login_mode_preserves_when_not_provided(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ login_mode = PasswordLoginModeEnum.ENABLED.value
+ site_settings.password_login_mode = login_mode
+ site_settings.save(update_fields=["password_login_mode"])
+ variables = {"input": {"headerText": "New header"}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_PASSWORD_LOGIN_MODE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["shopSettingsUpdate"]
+ assert not data["errors"]
+ assert data["shop"]["passwordLoginMode"] == login_mode.upper()
+ site_settings.refresh_from_db()
+ assert site_settings.password_login_mode == login_mode
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 777f391d0b..e703b402f1 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -20,6 +20,7 @@ from ..core.context import get_database_connection_name
from ..core.descriptions import (
ADDED_IN_319,
ADDED_IN_322,
+ ADDED_IN_323,
DEFAULT_DEPRECATION_REASON,
DEPRECATED_IN_3X_INPUT,
)
@@ -51,7 +52,7 @@ from ..translations.fields import TranslationField
from ..translations.resolvers import resolve_translation
from ..translations.types import ShopTranslation
from ..utils import format_permissions_for_display
-from .enums import GiftCardSettingsExpiryTypeEnum
+from .enums import GiftCardSettingsExpiryTypeEnum, PasswordLoginModeEnum
from .filters import CountryFilterInput
from .resolvers import resolve_available_shipping_methods, resolve_countries
@@ -381,6 +382,12 @@ class Shop(graphene.ObjectType):
permissions=[SitePermissions.MANAGE_SETTINGS],
required=True,
)
+ password_login_mode = PermissionsField(
+ PasswordLoginModeEnum,
+ description="Controls whether password-based authentication is allowed."
+ + ADDED_IN_323,
+ required=True,
+ )
# deprecated
include_taxes_in_prices = graphene.Boolean(
@@ -692,6 +699,11 @@ class Shop(graphene.ObjectType):
def resolve_preserve_all_address_fields(_, _info, site):
return site.settings.preserve_all_address_fields
+ @staticmethod
+ @load_site_callback
+ def resolve_password_login_mode(_, _info, site):
+ return site.settings.password_login_mode
+
@staticmethod
@load_site_callback
def resolve_use_legacy_update_webhook_emission(_, _info, site):
diff --git a/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py
index ef0e299a65..2c7253d3cb 100644
--- a/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py
+++ b/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py
@@ -1,6 +1,7 @@
import pytest
from django.db import connection
+from .....site.models import Site
from .....warehouse.models import Stock
from ....tests.utils import get_graphql_content
@@ -72,7 +73,7 @@ def test_stocks_bulk_update_queries_count(
staff_api_client.ensure_access_token()
# test number of queries when single object is updated
- with django_assert_num_queries(11):
+ with django_assert_num_queries(13):
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(
STOCKS_BULK_UPDATE_MUTATION, {"stocks": stocks_input}
@@ -89,6 +90,10 @@ def test_stocks_bulk_update_queries_count(
)
assert webhook_queries_count == 1
+ # Clear cache for proper query count comparison.
+ # Site and site settings are cached in `auth_backend` when querying the current site.
+ Site.objects.clear_cache()
+
stocks_input += [
{
"variantExternalReference": variant_1.external_reference,
@@ -108,7 +113,7 @@ def test_stocks_bulk_update_queries_count(
]
# Test number of queries when multiple objects are updated
- with django_assert_num_queries(11):
+ with django_assert_num_queries(13):
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(
STOCKS_BULK_UPDATE_MUTATION, {"stocks": stocks_input}
diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.py
index e512e93f4f..948b0303b5 100644
--- a/saleor/plugins/openid_connect/tests/test_utils.py
+++ b/saleor/plugins/openid_connect/tests/test_utils.py
@@ -298,6 +298,66 @@ def test_get_or_create_user_from_payload_assigns_sub(
assert user_from_payload.id == customer_user.id
assert user_from_payload.private_metadata[f"oidc:{oauth_url}"] == sub_id
assert customer_user.is_staff is False
+ assert not user_from_payload.has_usable_password()
+
+
[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_clears_password_for_existing_user(
+ mocked_cache_get, mocked_cache_set, customer_user
+):
+ # When OIDC finds an existing user by email (not by sub), the old password
+ # should be invalidated to prevent login with stale credentials.
+
+ # given
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|new-sub"
+ assert customer_user.has_usable_password()
+
+ mocked_cache_get.side_effect = lambda cache_key: None
+
+ # when
+ user_from_payload, created, _ = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_user.email},
+ oauth_url=oauth_url,
+ )
+
+ # then
+ assert not created
+ assert user_from_payload.id == customer_user.id
+ assert not user_from_payload.has_usable_password()
+ customer_user.refresh_from_db()
+ assert not customer_user.has_usable_password()
+
+
[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_keeps_password_for_returning_oidc_user(
+ mocked_cache_get, mocked_cache_set, customer_user
+):
+ # When an existing OIDC user is found by email (cache miss on sub lookup),
+ # the password should NOT be cleared since they already have the OIDC identity.
+
+ # given
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|existing-sub"
+ oidc_key = f"oidc:{oauth_url}"
+ customer_user.store_value_in_private_metadata({oidc_key: sub_id})
+ customer_user.save(update_fields=["private_metadata"])
+ assert customer_user.has_usable_password()
+
+ mocked_cache_get.side_effect = lambda cache_key: None
+
+ # when
+ user_from_payload, created, _ = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_user.email},
+ oauth_url=oauth_url,
+ )
+
+ # then
+ assert not created
+ assert user_from_payload.id == customer_user.id
+ assert user_from_payload.has_usable_password()
@mock.patch("saleor.plugins.openid_connect.utils.cache.set")
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index 8a2992c268..8f3df64fe3 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -388,6 +388,21 @@ def get_parsed_id_token(token_data, jwks_url) -> CodeIDToken:
raise AuthenticationError("Token validation failed") from e
+def _invalidate_password_for_new_oidc_account(
+ user: User, oidc_metadata_key: str
+) -> None:
+ """Invalidate password for pre-existing user being claimed by OIDC for the first time.
+
+ When OIDC finds a user by email who wasn't previously linked to this OIDC provider,
+ the old password must be cleared to prevent login with stale credentials. This
+ handles the case where a staff account is deleted (soft-deleted with is_staff=False)
+ and later recreated via OIDC — without this, the old password would still work.
+ """
+ if not user.get_value_from_private_metadata(oidc_metadata_key):
+ user.set_unusable_password()
+ user.save(update_fields=["password"])
+
+
def get_or_create_user_from_payload(
payload: dict,
oauth_url: str,
@@ -429,14 +444,18 @@ def get_or_create_user_from_payload(
email=user_email,
defaults=defaults_create,
)
+ if not created:
+ _invalidate_password_for_new_oidc_account(user, oidc_metadata_key)
match_orders_with_new_user(user)
except User.MultipleObjectsReturned:
logger.warning("Multiple users returned for single OIDC sub ID")
- user, _ = User.objects.get_or_create(
+ user, created = User.objects.get_or_create(
email=user_email,
defaults=defaults_create,
)
+ if not created:
+ _invalidate_password_for_new_oidc_account(user, oidc_metadata_key)
# User logged in by OpenID are treated as confirmed by default so we only need to
# check if user is active
diff --git a/saleor/site/__init__.py b/saleor/site/__init__.py
index 5733110f94..f0e2be169f 100644
--- a/saleor/site/__init__.py
+++ b/saleor/site/__init__.py
@@ -1,3 +1,24 @@
+class PasswordLoginMode:
+ """Controls whether password-based authentication is allowed.
+
+ ENABLED - any user can log in with a password. This is the default behavior.
+ CUSTOMERS_ONLY - only customer users can log in with a password.
+ If a staff user logs in with a password, they will be treated as a customer
+ — the issued token will not contain any staff permissions.
+ DISABLED - no user can log in with a password.
+ """
+
+ ENABLED = "enabled"
+ CUSTOMERS_ONLY = "customers_only"
+ DISABLED = "disabled"
+
+ CHOICES = [
+ (ENABLED, "Enabled"),
+ (CUSTOMERS_ONLY, "Customers only"),
+ (DISABLED, "Disabled"),
+ ]
+
+
class GiftCardSettingsExpiryType:
NEVER_EXPIRE = "never_expire"
EXPIRY_PERIOD = "expiry_period"
diff --git a/saleor/site/migrations/0046_sitesettings_password_login_mode.py b/saleor/site/migrations/0046_sitesettings_password_login_mode.py
new file mode 100644
index 0000000000..8f8edcf6cc
--- /dev/null
+++ b/saleor/site/migrations/0046_sitesettings_password_login_mode.py
@@ -0,0 +1,26 @@
+# Generated by Django 5.2.11 on 2026-03-05 13:10
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("site", "0045_merge_20260223_0944"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="password_login_mode",
+ field=models.CharField(
+ choices=[
+ ("enabled", "Enabled"),
+ ("customers_only", "Customers only"),
+ ("disabled", "Disabled"),
+ ],
+ db_default="enabled",
+ default="enabled",
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index f32ff33cbe..c4230a52ee 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -14,7 +14,7 @@ from ..core.models import ModelWithMetadata
from ..core.units import WeightUnits
from ..core.utils.translations import Translation
from ..permission.enums import SitePermissions
-from . import GiftCardSettingsExpiryType
+from . import GiftCardSettingsExpiryType, PasswordLoginMode
from .error_codes import SiteErrorCode
from .patch_sites import patch_contrib_sites
@@ -68,6 +68,12 @@ class SiteSettings(ModelWithMetadata):
default_mail_sender_address = models.EmailField(blank=True, null=True)
enable_account_confirmation_by_email = models.BooleanField(default=True)
allow_login_without_confirmation = models.BooleanField(default=False)
+ password_login_mode = models.CharField(
+ max_length=32,
+ choices=PasswordLoginMode.CHOICES,
+ default=PasswordLoginMode.ENABLED,
+ db_default=PasswordLoginMode.ENABLED,
+ )
customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)
fulfillment_auto_approve = models.BooleanField(default=True)
fulfillment_allow_unpaid = models.BooleanField(default=True)
diff --git a/saleor/tests/e2e/account/account/test_staff_login_customers_only_mode.py b/saleor/tests/e2e/account/account/test_staff_login_customers_only_mode.py
new file mode 100644
index 0000000000..f67c976893
--- /dev/null
+++ b/saleor/tests/e2e/account/account/test_staff_login_customers_only_mode.py
@@ -0,0 +1,108 @@
+from unittest.mock import patch
+
+import pytest
+from django.contrib.sites.models import Site
+
+from .....site import PasswordLoginMode
+from ...account.utils.token_create import raw_token_create
+from ...conftest import E2eApiClient
+from ...product.utils.category import create_category
+from ...product.utils.product import PRODUCT_CREATE_MUTATION
+from ...product.utils.product_type import create_product_type
+from ...utils import assign_permissions, get_graphql_content
+
+ORDERS_QUERY = """
+query Orders {
+ orders(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+}
+"""
+
+
+@patch("saleor.account.throttling.cache")
+def test_staff_token_has_no_permissions_in_customers_only_mode(
+ _mocked_cache,
+ e2e_staff_api_client,
+ e2e_not_logged_api_client,
+ site_settings,
+ permission_manage_orders,
+ permission_manage_products,
+ permission_manage_product_types_and_attributes,
+):
+ # Step 1: Assign permissions and prepare product type and category
+ assign_permissions(
+ e2e_staff_api_client,
+ [
+ permission_manage_orders,
+ permission_manage_products,
+ permission_manage_product_types_and_attributes,
+ ],
+ )
+ product_type = create_product_type(e2e_staff_api_client)
+ category = create_category(e2e_staff_api_client)
+
+ staff_email = e2e_staff_api_client.user.email
+ staff_password = "password"
+ product_input = {
+ "input": {
+ "name": "Test product",
+ "productType": product_type["id"],
+ "category": category["id"],
+ }
+ }
+
+ # Step 2: Login with ENABLED mode and create a product, fetch orders — should succeed
+ login_response = raw_token_create(
+ e2e_not_logged_api_client, staff_email, staff_password
+ )
+ login_data = login_response["data"]["tokenCreate"]
+ assert login_data["errors"] == []
+ enabled_token = login_data["token"]
+
+ enabled_client = E2eApiClient()
+ enabled_client.token = enabled_token
+
+ response = enabled_client.post_graphql(PRODUCT_CREATE_MUTATION, product_input)
+ content = get_graphql_content(response)
+ assert content["data"]["productCreate"]["errors"] == []
+ assert content["data"]["productCreate"]["product"]["id"] is not None
+
+ response = enabled_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+ assert content["data"]["orders"] is not None
+
+ # Step 3: Switch to CUSTOMERS_ONLY mode
+ site_settings.password_login_mode = PasswordLoginMode.CUSTOMERS_ONLY
+ site_settings.save(update_fields=["password_login_mode"])
+ Site.objects.clear_cache()
+
+ # Step 4: Try to create a product and fetch orders — should fail
+ response = enabled_client.post_graphql(PRODUCT_CREATE_MUTATION, product_input)
+ content = get_graphql_content(response, ignore_errors=True)
+ assert "errors" in content
+ assert content["errors"][0]["extensions"]["exception"]["code"] == "PermissionDenied"
+
+ response = enabled_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response, ignore_errors=True)
+ assert "errors" in content
+ assert content["errors"][0]["extensions"]["exception"]["code"] == "PermissionDenied"
+
+ # Step 5: Switch back to ENABLED mode — should succeed again
+ site_settings.password_login_mode = PasswordLoginMode.ENABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ Site.objects.clear_cache()
+
+ response = enabled_client.post_graphql(PRODUCT_CREATE_MUTATION, product_input)
+ content = get_graphql_content(response)
+ assert content["data"]["productCreate"]["errors"] == []
+ assert content["data"]["productCreate"]["product"]["id"] is not None
+
+ response = enabled_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+ assert content["data"]["orders"] is not None
diff --git a/saleor/tests/e2e/account/account/test_staff_login_disabled_mode.py b/saleor/tests/e2e/account/account/test_staff_login_disabled_mode.py
new file mode 100644
index 0000000000..4b9eae415b
--- /dev/null
+++ b/saleor/tests/e2e/account/account/test_staff_login_disabled_mode.py
@@ -0,0 +1,112 @@
+from unittest.mock import patch
+
+import pytest
+from django.contrib.sites.models import Site
+
+from .....site import PasswordLoginMode
+from ...account.utils.token_create import raw_token_create
+from ...conftest import E2eApiClient
+from ...product.utils.category import create_category
+from ...product.utils.product import PRODUCT_CREATE_MUTATION
+from ...product.utils.product_type import create_product_type
+from ...utils import assign_permissions, get_graphql_content
+
+ORDERS_QUERY = """
+query Orders {
+ orders(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+}
+"""
+
+
+@patch("saleor.account.throttling.cache")
+def test_staff_token_is_rejected_in_disabled_mode(
+ _mocked_cache,
+ e2e_staff_api_client,
+ e2e_not_logged_api_client,
+ site_settings,
+ permission_manage_orders,
+ permission_manage_products,
+ permission_manage_product_types_and_attributes,
+):
+ # Step 1: Assign permissions and prepare product type and category
+ assign_permissions(
+ e2e_staff_api_client,
+ [
+ permission_manage_orders,
+ permission_manage_products,
+ permission_manage_product_types_and_attributes,
+ ],
+ )
+ product_type = create_product_type(e2e_staff_api_client)
+ category = create_category(e2e_staff_api_client)
+
+ staff_email = e2e_staff_api_client.user.email
+ staff_password = "password"
+ product_input = {
+ "input": {
+ "name": "Test product",
+ "productType": product_type["id"],
+ "category": category["id"],
+ }
+ }
+
+ # Step 2: Login with ENABLED mode and create a product, fetch orders — should succeed
+ login_response = raw_token_create(
+ e2e_not_logged_api_client, staff_email, staff_password
+ )
+ login_data = login_response["data"]["tokenCreate"]
+ assert login_data["errors"] == []
+ enabled_token = login_data["token"]
+
+ enabled_client = E2eApiClient()
+ enabled_client.token = enabled_token
+
+ response = enabled_client.post_graphql(PRODUCT_CREATE_MUTATION, product_input)
+ content = get_graphql_content(response)
+ assert content["data"]["productCreate"]["errors"] == []
+ assert content["data"]["productCreate"]["product"]["id"] is not None
+
+ response = enabled_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+ assert content["data"]["orders"] is not None
+
+ # Step 3: Switch to DISABLED mode
+ site_settings.password_login_mode = PasswordLoginMode.DISABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ Site.objects.clear_cache()
+
+ # Step 4: Try to create a product and fetch orders — should fail (user is not authenticated)
+ response = enabled_client.post_graphql(PRODUCT_CREATE_MUTATION, product_input)
+ content = get_graphql_content(response, ignore_errors=True)
+ assert "errors" in content
+ assert (
+ content["errors"][0]["extensions"]["exception"]["code"] == "InvalidTokenError"
+ )
+
+ response = enabled_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response, ignore_errors=True)
+ assert "errors" in content
+ assert (
+ content["errors"][0]["extensions"]["exception"]["code"] == "InvalidTokenError"
+ )
+
+ # Step 5: Switch back to ENABLED mode — should succeed again
+ site_settings.password_login_mode = PasswordLoginMode.ENABLED
+ site_settings.save(update_fields=["password_login_mode"])
+ Site.objects.clear_cache()
+
+ response = enabled_client.post_graphql(PRODUCT_CREATE_MUTATION, product_input)
+ content = get_graphql_content(response)
+ assert content["data"]["productCreate"]["errors"] == []
+ assert content["data"]["productCreate"]["product"]["id"] is not None
+
+ response = enabled_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+ assert content["data"]["orders"] is not None