Skip to content

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

Add `STAFF_SET_PASSWORD_REQUESTED` webhook (#13575)

Artur676b42e61962
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05937405f3..aab883e8d0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -100,6 +100,8 @@ Shipping methods can be removed by the user after it has been assigned to a chec
- Called when `confirmEmailChange` mutation is triggered.
- Add `ACCOUNT_SET_PASSWORD_REQUESTED` webhook - #13486, by @Air-t
- Called after `requestPasswordReset` or `customerCreate` mutation.
+- Add `STAFF_SET_PASSWORD_REQUESTED` webhook - #13486, by @Air-t
+ - Called after `requestPasswordReset` or `customerCreate` mutation for staff users.
### Other changes
- Add possibility to log without confirming email - #13059 by @kadewu
diff --git a/saleor/graphql/account/mutations/authentication/request_password_reset.py b/saleor/graphql/account/mutations/authentication/request_password_reset.py
index ecdc6e3e50..25fdcb236c 100644
--- a/saleor/graphql/account/mutations/authentication/request_password_reset.py
+++ b/saleor/graphql/account/mutations/authentication/request_password_reset.py
@@ -55,6 +55,12 @@ class RequestPasswordReset(BaseMutation):
type=WebhookEventAsyncType.ACCOUNT_SET_PASSWORD_REQUESTED,
description="Setting a new password for the account is requested.",
),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.STAFF_SET_PASSWORD_REQUESTED,
+ description=(
+ "Setting a new password for the staff account is requested."
+ ),
+ ),
]
@classmethod
@@ -128,13 +134,23 @@ class RequestPasswordReset(BaseMutation):
channel_slug=channel_slug,
staff=user.is_staff,
)
- cls.call_event(
- manager.account_set_password_requested,
- user,
- channel_slug,
- token,
- prepare_url(params, redirect_url),
- )
+ if user.is_staff:
+ cls.call_event(
+ manager.staff_set_password_requested,
+ user,
+ channel_slug,
+ token,
+ prepare_url(params, redirect_url),
+ )
+ else:
+ cls.call_event(
+ manager.account_set_password_requested,
+ user,
+ channel_slug,
+ token,
+ prepare_url(params, redirect_url),
+ )
+
user.last_password_reset_request = timezone.now()
user.save(update_fields=["last_password_reset_request"])
diff --git a/saleor/graphql/account/mutations/staff/staff_create.py b/saleor/graphql/account/mutations/staff/staff_create.py
index 9189e37f4e..6bcc4fc157 100644
--- a/saleor/graphql/account/mutations/staff/staff_create.py
+++ b/saleor/graphql/account/mutations/staff/staff_create.py
@@ -1,7 +1,9 @@
from collections import defaultdict
from typing import cast
+from urllib.parse import urlencode
import graphene
+from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import ValidationError
from .....account import models
@@ -10,7 +12,7 @@ from .....account.notifications import send_set_password_notification
from .....account.search import USER_SEARCH_FIELDS, prepare_user_search_document_value
from .....core.exceptions import PermissionDenied
from .....core.tracing import traced_atomic_transaction
-from .....core.utils.url import validate_storefront_url
+from .....core.utils.url import prepare_url, validate_storefront_url
from .....permission.enums import AccountPermissions
from .....webhook.event_types import WebhookEventAsyncType
from ....account.types import User
@@ -75,6 +77,12 @@ class StaffCreate(ModelMutation):
type=WebhookEventAsyncType.NOTIFY_USER,
description="A notification for setting the password.",
),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.STAFF_SET_PASSWORD_REQUESTED,
+ description=(
+ "Setting a new password for the staff account is requested."
+ ),
+ ),
]
@classmethod
@@ -151,21 +159,38 @@ class StaffCreate(ModelMutation):
pass
@classmethod
- def save(cls, info: ResolveInfo, user, cleaned_input, send_notification=True):
+ def save(
+ cls,
+ info: ResolveInfo,
+ user,
+ cleaned_input,
+ send_notification=True,
+ redirect_url=None,
+ ):
if any([field in cleaned_input for field in USER_SEARCH_FIELDS]):
user.search_document = prepare_user_search_document_value(
user, attach_addresses_data=False
)
user.save()
- if cleaned_input.get("redirect_url") and send_notification:
+ redirect_url = cleaned_input.get("redirect_url")
+ if redirect_url and send_notification:
manager = get_plugin_manager_promise(info.context).get()
send_set_password_notification(
- redirect_url=cleaned_input.get("redirect_url"),
+ redirect_url=redirect_url,
user=user,
manager=manager,
channel_slug=None,
staff=True,
)
+ token = default_token_generator.make_token(user)
+ params = urlencode({"email": user.email, "token": token})
+ cls.call_event(
+ manager.staff_set_password_requested,
+ user,
+ None,
+ token,
+ prepare_url(params, redirect_url),
+ )
@classmethod
def _save_m2m(cls, info: ResolveInfo, instance, cleaned_data):
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 affe1e8cbe..43fc65db76 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
@@ -324,3 +324,29 @@ def test_account_reset_password_subdomain(
payload=expected_payload,
channel_slug=channel_PLN.slug,
)
+
+
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_account_reset_password_event_triggered(
+ mocked_trigger_webhooks_async,
+ settings,
+ user_api_client,
+ customer_user,
+ channel_PLN,
+ subscription_account_set_password_requested_webhook,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "email": customer_user.email,
+ "redirectUrl": redirect_url,
+ "channel": channel_PLN.slug,
+ }
+
+ # when
+ user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
+
+ # then
+ mocked_trigger_webhooks_async.assert_called()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 55dac618cf..8ae303e646 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2137,6 +2137,9 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""A staff user is deleted."""
STAFF_DELETED
+ """Setting a new password for the staff account is requested."""
+ STAFF_SET_PASSWORD_REQUESTED
+
"""
Transaction item metadata is updated.
@@ -2796,6 +2799,9 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
"""A staff user is deleted."""
STAFF_DELETED
+ """Setting a new password for the staff account is requested."""
+ STAFF_SET_PASSWORD_REQUESTED
+
"""
Transaction item metadata is updated.
@@ -3508,6 +3514,7 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
STAFF_CREATED
STAFF_UPDATED
STAFF_DELETED
+ STAFF_SET_PASSWORD_REQUESTED
TRANSACTION_ITEM_METADATA_UPDATED
TRANSLATION_CREATED
TRANSLATION_UPDATED
@@ -17908,6 +17915,7 @@ type Mutation {
Triggers the following webhook events:
- NOTIFY_USER (async): A notification for password reset.
- ACCOUNT_SET_PASSWORD_REQUESTED (async): Setting a new password for the account is requested.
+ - STAFF_SET_PASSWORD_REQUESTED (async): Setting a new password for the staff account is requested.
"""
requestPasswordReset(
"""
@@ -17922,7 +17930,7 @@ type Mutation {
URL of a view where users should be redirected to reset the password. URL in RFC 1808 format.
"""
redirectUrl: String!
- ): RequestPasswordReset @doc(category: "Users") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, ACCOUNT_SET_PASSWORD_REQUESTED], syncEvents: [])
+ ): RequestPasswordReset @doc(category: "Users") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, ACCOUNT_SET_PASSWORD_REQUESTED, STAFF_SET_PASSWORD_REQUESTED], syncEvents: [])
"""
Sends a notification confirmation.
@@ -18320,11 +18328,12 @@ type Mutation {
Triggers the following webhook events:
- STAFF_CREATED (async): A new staff account was created.
- NOTIFY_USER (async): A notification for setting the password.
+ - STAFF_SET_PASSWORD_REQUESTED (async): Setting a new password for the staff account is requested.
"""
staffCreate(
"""Fields required to create a staff user."""
input: StaffCreateInput!
- ): StaffCreate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [STAFF_CREATED, NOTIFY_USER], syncEvents: [])
+ ): StaffCreate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [STAFF_CREATED, NOTIFY_USER, STAFF_SET_PASSWORD_REQUESTED], syncEvents: [])
"""
Updates an existing staff user. Apps are not allowed to perform this mutation.
@@ -28117,8 +28126,9 @@ Sends an email with the account password modification link.
Triggers the following webhook events:
- NOTIFY_USER (async): A notification for password reset.
- ACCOUNT_SET_PASSWORD_REQUESTED (async): Setting a new password for the account is requested.
+- STAFF_SET_PASSWORD_REQUESTED (async): Setting a new password for the staff account is requested.
"""
-type RequestPasswordReset @doc(category: "Users") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, ACCOUNT_SET_PASSWORD_REQUESTED], syncEvents: []) {
+type RequestPasswordReset @doc(category: "Users") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, ACCOUNT_SET_PASSWORD_REQUESTED, STAFF_SET_PASSWORD_REQUESTED], syncEvents: []) {
accountErrors: [AccountError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [AccountError!]!
}
@@ -28725,8 +28735,9 @@ Requires one of the following permissions: MANAGE_STAFF.
Triggers the following webhook events:
- STAFF_CREATED (async): A new staff account was created.
- NOTIFY_USER (async): A notification for setting the password.
+- STAFF_SET_PASSWORD_REQUESTED (async): Setting a new password for the staff account is requested.
"""
-type StaffCreate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [STAFF_CREATED, NOTIFY_USER], syncEvents: []) {
+type StaffCreate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [STAFF_CREATED, NOTIFY_USER, STAFF_SET_PASSWORD_REQUESTED], syncEvents: []) {
staffErrors: [StaffError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [StaffError!]!
user: User
@@ -31834,6 +31845,40 @@ type StaffDeleted implements Event @doc(category: "Users") {
user: User
}
+"""
+Event sent when setting a new password for staff is requested.
+
+Added in Saleor 3.15.
+"""
+type StaffSetPasswordRequested implements Event {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The URL to redirect the user after he accepts the request."""
+ redirectUrl: String
+
+ """The user the event relates to."""
+ user: User
+
+ """The channel data."""
+ channel: Channel
+
+ """The token required to confirm request."""
+ token: String
+
+ """Shop data."""
+ shop: Shop
+}
+
"""
Event sent when transaction item metadata is updated.
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 5199228477..a3a73b5749 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -192,6 +192,9 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.SHIPPING_ZONE_METADATA_UPDATED: (
"A shipping zone metadata is updated." + ADDED_IN_38
),
+ WebhookEventAsyncType.STAFF_SET_PASSWORD_REQUESTED: (
+ "Setting a new password for the staff account is requested."
+ ),
WebhookEventAsyncType.STAFF_CREATED: "A new staff user is created.",
WebhookEventAsyncType.STAFF_UPDATED: "A staff user is updated.",
WebhookEventAsyncType.STAFF_DELETED: "A staff user is deleted.",
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 6c7c615f43..3206cdcc03 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -1551,6 +1551,17 @@ class StaffDeleted(SubscriptionObjectType, UserBase):
description = "Event sent when staff user is deleted." + ADDED_IN_35
+class StaffSetPasswordRequested(SubscriptionObjectType, AccountOperationBase):
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when setting a new password for staff is requested."
+ + ADDED_IN_315
+ )
+
+
class TransactionAction(SubscriptionObjectType, AbstractType):
action_type = graphene.Field(
TransactionActionEnum,
@@ -2281,6 +2292,7 @@ WEBHOOK_TYPES_MAP = {
WebhookEventAsyncType.STAFF_CREATED: StaffCreated,
WebhookEventAsyncType.STAFF_UPDATED: StaffUpdated,
WebhookEventAsyncType.STAFF_DELETED: StaffDeleted,
+ WebhookEventAsyncType.STAFF_SET_PASSWORD_REQUESTED: StaffSetPasswordRequested,
WebhookEventAsyncType.TRANSACTION_ITEM_METADATA_UPDATED: (
TransactionItemMetadataUpdated
),
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 7a842dcf50..0ca6e10008 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -1046,6 +1046,12 @@ class BasePlugin:
# deleted.
staff_deleted: Callable[["User", Any], Any]
+ # Trigger when setting a password for staff is requested.
+ #
+ # Overwrite this method if you need to trigger specific logic after set
+ # password for staff is requested.
+ staff_set_password_requested: Callable[["User", str, str, str, None], None]
+
# Trigger when thumbnail is updated.
thumbnail_created: Callable[["Thumbnail", Any], Any]
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 7326130ed6..6cb0cf47de 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -1357,6 +1357,19 @@ class PluginsManager(PaymentInterface):
default_value = None
return self.__run_method_on_plugins("staff_deleted", default_value, staff_user)
+ def staff_set_password_requested(
+ self, user: "User", channel_slug: str, token: str, redirect_url: str
+ ):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "staff_set_password_requested",
+ default_value,
+ user,
+ channel_slug,
+ token=token,
+ redirect_url=redirect_url,
+ )
+
def thumbnail_created(
self,
thumbnail: "Thumbnail",
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 84e25f6bfe..155fd294ee 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1485,6 +1485,24 @@ class WebhookPlugin(BasePlugin):
return previous_value
self._trigger_staff_event(WebhookEventAsyncType.STAFF_DELETED, staff_user)
+ def staff_set_password_requested(
+ self,
+ user: "User",
+ channel_slug: str,
+ token: str,
+ redirect_url: str,
+ previous_value: None,
+ ) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_account_request_event(
+ WebhookEventAsyncType.STAFF_SET_PASSWORD_REQUESTED,
+ user,
+ channel_slug,
+ token,
+ redirect_url,
+ )
+
def thumbnail_created(
self,
thumbnail: Thumbnail,
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index e56f2759b1..2053da3b5e 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -838,6 +838,14 @@ def subscription_staff_deleted_webhook(subscription_webhook):
)
+def subscription_staff_set_password_requested_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.STAFF_SET_PASSWORD_REQUESTED,
+ WebhookEventAsyncType.STAFF_SET_PASSWORD_REQUESTED,
+ )
+
+
@pytest.fixture
def subscription_transaction_item_metadata_updated_webhook(subscription_webhook):
return subscription_webhook(
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py
index 04ce15b9e0..cc0fd5155f 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py
@@ -26,7 +26,9 @@ def generate_account_requested_events_payload(customer_user, channel, new_email=
"channel": {
"slug": channel.slug,
"id": graphene.Node.to_global_id("Channel", channel.id),
- },
+ }
+ if channel
+ else None,
"shop": {"domain": {"host": "mirumee.com", "url": "http://mirumee.com/"}},
},
}
@@ -148,7 +150,7 @@ def generate_customer_payload(customer):
"email": customer.email,
"firstName": customer.first_name,
"lastName": customer.last_name,
- "isStaff": False,
+ "isStaff": customer.is_staff,
"isActive": customer.is_active,
"addresses": [
{"id": graphene.Node.to_global_id("Address", address.pk)}
@@ -157,9 +159,13 @@ def generate_customer_payload(customer):
"languageCode": customer.language_code.upper(),
"defaultShippingAddress": (
generate_address_payload(customer.default_shipping_address)
+ if customer.default_shipping_address
+ else None
),
"defaultBillingAddress": (
generate_address_payload(customer.default_billing_address)
+ if customer.default_billing_address
+ else None
),
}
}
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
index c91fff2d11..ec44f04c13 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -829,6 +829,34 @@ STAFF_DELETED = (
)
+STAFF_SET_PASSWORD_REQUESTED = (
+ fragments.CUSTOMER_DETAILS
+ + """
+ subscription{
+ event{
+ ...on StaffSetPasswordRequested{
+ user{
+ ...CustomerDetails
+ }
+ token
+ redirectUrl
+ channel{
+ slug
+ id
+ }
+ shop{
+ domain{
+ host
+ url
+ }
+ }
+ }
+ }
+ }
+"""
+)
+
+
PRODUCT_UPDATED = """
subscription{
event{
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index 5093ba8b3e..b249218901 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -1123,6 +1123,35 @@ def test_staff_deleted(staff_user, subscription_staff_deleted_webhook):
assert deliveries[0].webhook == webhooks[0]
+def test_staff_set_password_requested(
+ staff_user, channel_USD, subscription_staff_set_password_requested_webhook
+):
+ # given
+ webhooks = [subscription_staff_set_password_requested_webhook]
+ event_type = WebhookEventAsyncType.STAFF_SET_PASSWORD_REQUESTED
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(
+ event_type,
+ {
+ "user": staff_user,
+ "channel_slug": channel_USD.slug,
+ "token": "token",
+ "redirect_url": "http://www.mirumee.com?token=token",
+ },
+ webhooks,
+ )
+
+ # then
+ expected_payload = generate_account_requested_events_payload(
+ staff_user, channel_USD
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_product_created(product, subscription_product_created_webhook):
webhooks = [subscription_product_created_webhook]
event_type = WebhookEventAsyncType.PRODUCT_CREATED
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 1ff06a32a9..2ce3f6ae38 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -161,6 +161,7 @@ class WebhookEventAsyncType:
STAFF_CREATED = "staff_created"
STAFF_UPDATED = "staff_updated"
STAFF_DELETED = "staff_deleted"
+ STAFF_SET_PASSWORD_REQUESTED = "staff_set_password_requested"
TRANSACTION_ITEM_METADATA_UPDATED = "transaction_item_metadata_updated"
@@ -632,6 +633,10 @@ class WebhookEventAsyncType:
"name": "Staff deleted",
"permission": AccountPermissions.MANAGE_STAFF,
},
+ STAFF_SET_PASSWORD_REQUESTED: {
+ "name": "Setting a password for a staff is requested",
+ "permission": AccountPermissions.MANAGE_STAFF,
+ },
TRANSACTION_ITEM_METADATA_UPDATED: {
"name": "Transaction item metadata updated",
"permission": PaymentPermissions.HANDLE_PAYMENTS,