Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add possibility for plugins to execute code before each mutation (#9193)
Mika7bd135e0f109
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 4bd0231c54..31a4322aee 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -12,6 +12,7 @@ from ....account.notifications import ()from ....account.search import prepare_user_search_document_valuefrom ....checkout import AddressType+from ....core.db.utils import set_mutation_flag_in_contextfrom ....core.exceptions import PermissionDeniedfrom ....core.permissions import AccountPermissionsfrom ....core.tracing import traced_atomic_transaction@@ -70,6 +71,13 @@ class SetPassword(CreateToken):@classmethoddef mutate(cls, root, info, **data):+ set_mutation_flag_in_context(info.context)+ result = info.context.plugins.perform_mutation(+ mutation_cls=cls, root=root, info=info, data=data+ )+ if result is not None:+ return result+email = data["email"]password = data["password"]token = data["token"]diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 38eef9c36f..a175c479e8 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -335,6 +335,12 @@ class BaseMutation(graphene.Mutation):if not cls.check_permissions(info.context):raise PermissionDenied()+ result = info.context.plugins.perform_mutation(+ mutation_cls=cls, root=root, info=info, data=data+ )+ if result is not None:+ return result+try:response = cls.perform_mutation(root, info, **data)if response.errors is None:@@ -669,9 +675,16 @@ class BaseBulkMutation(BaseMutation):@classmethoddef mutate(cls, root, info, **data):+ set_mutation_flag_in_context(info.context)if not cls.check_permissions(info.context):raise PermissionDenied()+ result = info.context.plugins.perform_mutation(+ mutation_cls=cls, root=root, info=info, data=data+ )+ if result is not None:+ return result+count, errors = cls.perform_mutation(root, info, **data)if errors:return cls.handle_errors(errors, count=count)diff --git a/saleor/graphql/core/tests/test_base_mutation.py b/saleor/graphql/core/tests/test_base_mutation.pyindex c2534f9754..db34ed8a56 100644--- a/saleor/graphql/core/tests/test_base_mutation.py+++ b/saleor/graphql/core/tests/test_base_mutation.py@@ -1,8 +1,13 @@-from unittest.mock import Mock+from unittest import mockimport grapheneimport pytestfrom django.core.exceptions import ImproperlyConfigured+from graphql import GraphQLError+from graphql.execution import ExecutionResult++from saleor.core.permissions import ProductPermissions+from saleor.plugins.tests.sample_plugins import PluginSamplefrom ...product import types as product_typesfrom ..mutations import BaseMutation@@ -38,9 +43,23 @@ class MutationWithCustomErrors(Mutation):error_type_field = "custom_errors"+class RestrictedMutation(Mutation):+ """A mutation requiring the user to have given permissions"""++ auth_token = graphene.types.String(+ description="The newly created authentication token."+ )++ class Meta:+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ description = "Mutation requiring manage product user permission"+ error_type_class = ErrorTest++class Mutations(graphene.ObjectType):test = Mutation.Field()test_with_custom_errors = MutationWithCustomErrors.Field()+ restricted_mutation = RestrictedMutation.Field()schema = graphene.Schema(@@ -146,6 +165,144 @@ def test_user_error_id_of_different_type(product, schema_context, channel_USD):def test_get_node_or_error_returns_null_for_empty_id():- info = Mock()+ info = mock.Mock()response = Mutation.get_node_or_error(info, "", field="")assert response is None+++def test_mutation_plugin_perform_mutation_handles_graphql_error(+ request,+ settings,+ plugin_configuration,+ product,+ channel_USD,+):+ """Ensure when the mutation calls the method 'perform_mutation' on plugins,+ the returned error "GraphQLError" is properly returned and transformed into a dict+ """+ settings.PLUGINS = [+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]++ schema_context = request.getfixturevalue("schema_context")++ product_id = graphene.Node.to_global_id("Product", product.pk)+ variables = {"productId": product_id, "channel": channel_USD.slug}++ with mock.patch.object(+ PluginSample,+ "perform_mutation",+ return_value=GraphQLError("My Custom Error"),+ ):+ result = schema.execute(+ TEST_MUTATION, variables=variables, context_value=schema_context+ )+ assert result.to_dict() == {+ "data": {"test": None},+ "errors": [+ {+ "locations": [{"column": 9, "line": 3}],+ "message": "My Custom Error",+ "path": ["test"],+ }+ ],+ }+++def test_mutation_plugin_perform_mutation_handles_custom_execution_result(+ request,+ settings,+ plugin_configuration,+ product,+ channel_USD,+):+ """Ensure when the mutation calls the method 'perform_mutation' on plugins,+ if a "ExecutionResult" object is returned, then the GraphQL response contains it+ """+ settings.PLUGINS = [+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]++ schema_context = request.getfixturevalue("schema_context")++ product_id = graphene.Node.to_global_id("Product", product.pk)+ variables = {"productId": product_id, "channel": channel_USD.slug}++ with mock.patch.object(+ PluginSample,+ "perform_mutation",+ return_value=ExecutionResult(data={}, errors=[GraphQLError("My Custom Error")]),+ ):+ result = schema.execute(+ TEST_MUTATION, variables=variables, context_value=schema_context+ )+ assert result.to_dict() == {+ "data": {"test": None},+ "errors": [+ {+ "locations": [{"column": 13, "line": 5}],+ "message": "My Custom Error",+ "path": ["test", "errors", 0],+ }+ ],+ }+++ PluginSample,+ "perform_mutation",+ return_value=ExecutionResult(data={}, errors=[GraphQLError("My Custom Error")]),+)+def test_mutation_calls_plugin_perform_mutation_after_permission_checks(+ mocked_plugin,+ request,+ settings,+ staff_user,+ plugin_configuration,+ product,+ channel_USD,+ permission_manage_products,+):+ """+ Ensure the mutation calls the method 'perform_mutation' on plugins only once the+ user/app permissions are verified+ """+ mutation_query = """+ mutation testRestrictedMutation($productId: ID!, $channel: String) {+ restrictedMutation(productId: $productId, channel: $channel) {+ name+ errors {+ field+ message+ }+ }+ }+ """++ settings.PLUGINS = [+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]++ schema_context = request.getfixturevalue("schema_context")+ schema_context.user = staff_user++ product_id = graphene.Node.to_global_id("Product", product.pk)+ variables = {"productId": product_id, "channel": channel_USD.slug}++ # When permission is missing, it should not return the custom error from plugin+ result = schema.execute(+ mutation_query, variables=variables, context_value=schema_context+ )+ assert len(result.errors) == 1, result.to_dict()+ assert result.errors[0].message == (+ "You do not have permission to perform this action"+ )++ # When permission is not missing, the execution of the plugin should happen+ staff_user.user_permissions.set([permission_manage_products])+ del staff_user._perm_cache # force django to re-fetch permissions+ result = schema.execute(+ mutation_query, variables=variables, context_value=schema_context+ )+ assert len(result.errors) == 1, result.to_dict()+ assert result.errors[0].message == "My Custom Error"diff --git a/saleor/graphql/product/mutations/digital_contents.py b/saleor/graphql/product/mutations/digital_contents.pyindex f5c22ebe9e..fa3d3b1a25 100644--- a/saleor/graphql/product/mutations/digital_contents.py+++ b/saleor/graphql/product/mutations/digital_contents.py@@ -1,6 +1,7 @@import graphenefrom django.core.exceptions import ValidationError+from ....core.db.utils import set_mutation_flag_in_contextfrom ....core.permissions import ProductPermissionsfrom ....product import modelsfrom ....product.error_codes import ProductErrorCode@@ -135,9 +136,16 @@ class DigitalContentDelete(BaseMutation):@classmethod@permission_required(ProductPermissions.MANAGE_PRODUCTS)- def mutate(cls, _root, info, variant_id):+ def mutate(cls, root, info, **data):+ set_mutation_flag_in_context(info.context)+ result = info.context.plugins.perform_mutation(+ mutation_cls=cls, root=root, info=info, data=data+ )+ if result is not None:+ return result+variant = cls.get_node_or_error(- info, variant_id, "id", only_type=ProductVariant+ info, data["variant_id"], "id", only_type=ProductVariant)if hasattr(variant, "digital_content"):diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex cb753c608e..7cc8a0c552 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -7,6 +7,9 @@ from django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponsefrom django.utils.functional import SimpleLazyObjectfrom django_countries.fields import Country+from graphene import Mutation+from graphql import GraphQLError, ResolveInfo+from graphql.execution import ExecutionResultfrom prices import Money, TaxedMoneyfrom promise.promise import Promise@@ -539,6 +542,26 @@ class BasePlugin:# Triggers retry mechanism for event deliveryevent_delivery_retry: Callable[["EventDelivery", Any], EventDelivery]+ # Invoked before each mutation is executed+ #+ # This allows to trigger specific logic before the mutation is executed+ # but only once the permissions are checked.+ #+ # Returns one of:+ # - null if the execution shall continue+ # - an execution result+ # - graphql.GraphQLError+ perform_mutation: Callable[+ [+ Optional[Union[ExecutionResult, GraphQLError]], # previous value+ Mutation, # mutation class+ Any, # mutation root+ ResolveInfo, # resolve info+ dict, # mutation data+ ],+ Optional[Union[ExecutionResult, GraphQLError]],+ ]+def token_is_required_as_payment_input(self, previous_value):return previous_valuediff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex a97a5cde7d..7f915aa1f9 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -19,6 +19,9 @@ from django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponse, HttpResponseNotFoundfrom django.utils.module_loading import import_stringfrom django_countries.fields import Country+from graphene import Mutation+from graphql import GraphQLError, ResolveInfo+from graphql.execution import ExecutionResultfrom prices import Money, TaxedMoneyfrom ..channel.models import Channel@@ -1206,6 +1209,28 @@ class PluginsManager(PaymentInterface):available_shipping_methods,)+ def perform_mutation(+ self, mutation_cls: Mutation, root, info: ResolveInfo, data: dict+ ) -> Optional[Union[ExecutionResult, GraphQLError]]:+ """Invoke before each mutation is executed.++ This allows to trigger specific logic before the mutation is executed+ but only once the permissions are checked.++ Returns one of:+ - null if the execution shall continue+ - graphql.GraphQLError+ - graphql.execution.ExecutionResult+ """+ return self.__run_method_on_plugins(+ "perform_mutation",+ default_value=None,+ mutation_cls=mutation_cls,+ root=root,+ info=info,+ data=data,+ )+def get_plugins_manager(requestor_getter: Optional[Callable[[], "Requestor"]] = Nonediff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.pyindex d52119784d..75b1977e22 100644--- a/saleor/plugins/tests/sample_plugins.py+++ b/saleor/plugins/tests/sample_plugins.py@@ -4,6 +4,9 @@ from typing import TYPE_CHECKING, Any, Iterable, Optional, Tuple, Unionfrom django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponse, HttpResponseNotFound, JsonResponsefrom django_countries.fields import Country+from graphene import Mutation+from graphql import GraphQLError, ResolveInfo+from graphql.execution import ExecutionResultfrom prices import Money, TaxedMoneyfrom ...account.models import User@@ -261,6 +264,16 @@ class PluginSample(BasePlugin):def event_delivery_retry(self, delivery: "EventDelivery", previous_value: Any):return True+ def perform_mutation(+ self,+ mutation_cls: Mutation,+ root,+ info: ResolveInfo,+ data: dict,+ previous_value: Optional[Union[ExecutionResult, GraphQLError]],+ ) -> Optional[Union[ExecutionResult, GraphQLError]]:+ return None+class ChannelPluginSample(PluginSample):PLUGIN_ID = "channel.plugin.sample"