Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add WebhookEvent model and api endpoints
Maciej Korycinski852f10071e84
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 6d270049bb..5c9412d76f 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1767,9 +1767,9 @@ input MoveProductInput {}type Mutations {- webhookCreate(input: WebhookSubscribeInput!): WebhookCreate+ webhookCreate(input: WebhookCreateInput!): WebhookCreatewebhookDelete(id: ID!): WebhookDelete- webhookUpdate(id: ID!, input: WebhookSubscribeInput!): WebhookUpdate+ webhookUpdate(id: ID!, input: WebhookUpdateInput!): WebhookUpdateauthorizationKeyAdd(input: AuthorizationKeyInput!, keyType: AuthorizationKeyType!): AuthorizationKeyAddauthorizationKeyDelete(keyType: AuthorizationKeyType!): AuthorizationKeyDeletehomepageCollectionUpdate(collection: ID): HomepageCollectionUpdate@@ -3770,10 +3770,11 @@ type VoucherUpdate {type Webhook implements Node {serviceAccount: ServiceAccount!- event: String!targetUrl: String!isActive: Boolean!+ secretKey: Stringid: ID!+ events: [WebhookEvent]}type WebhookCountableConnection {@@ -3792,16 +3793,25 @@ type WebhookCreate {webhook: Webhook}+input WebhookCreateInput {+ targetUrl: String+ events: [WebhookEventTypeEnum]+ serviceAccount: ID+ isActive: Boolean+ secretKey: String+}+type WebhookDelete {errors: [Error!]webhook: Webhook}-input WebhookSubscribeInput {- targetUrl: String- event: String- serviceAccount: ID- isActive: Boolean+type WebhookEvent {+ eventType: String+}++enum WebhookEventTypeEnum {+ ORDER_CREATED}type WebhookUpdate {@@ -3809,6 +3819,14 @@ type WebhookUpdate {webhook: Webhook}+input WebhookUpdateInput {+ targetUrl: String+ events: [WebhookEventTypeEnum]+ serviceAccount: ID+ isActive: Boolean+ secretKey: String+}+type Weight {unit: String!value: Float!diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pynew file mode 100644index 0000000000..55882622db--- /dev/null+++ b/saleor/graphql/webhook/enums.py@@ -0,0 +1,9 @@+import graphene++from ...webhook import WebhookEventType+from ..core.utils import str_to_enum++WebhookEventTypeEnum = graphene.Enum(+ "WebhookEventTypeEnum",+ [(str_to_enum(e_type[0]), e_type[0]) for e_type in WebhookEventType.CHOICES],+)diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.pyindex df2a5f2885..b5f74756a2 100644--- a/saleor/graphql/webhook/mutations.py+++ b/saleor/graphql/webhook/mutations.py@@ -3,23 +3,29 @@ from django.core.exceptions import ValidationErrorfrom ...webhook import modelsfrom ..core.mutations import ModelDeleteMutation, ModelMutation+from .enums import WebhookEventTypeEnumfrom .types import Webhook-class WebhookSubscribeInput(graphene.InputObjectType):+class WebhookCreateInput(graphene.InputObjectType):target_url = graphene.String(description="The url to receive the payload")- event = graphene.String(description="The event that webhook wants to subscribe")+ events = graphene.List(+ WebhookEventTypeEnum, description="The event that webhook wants to subscribe"+ )service_account = graphene.ID(required=False, description="serviceAccount ID of which webhook belongs to")is_active = graphene.Boolean(description="Determine if webhook will be set active or not.", required=False)+ secret_key = graphene.String(+ description="Use to create a hash signature with each payload", required=False+ )class WebhookCreate(ModelMutation):class Arguments:- input = WebhookSubscribeInput(+ input = WebhookCreateInput(description="Fields required to create a webhook.", required=True)@@ -50,9 +56,6 @@ class WebhookCreate(ModelMutation):raise ValidationError({"serviceAccount": "Service account doesn't exist or is disabled"})-- # FIXME Confirm that service_account has permissions to fetch resources- # for given event.return cleaned_data@classmethod@@ -68,13 +71,44 @@ class WebhookCreate(ModelMutation):has_perm = bool(context.service_account) or has_permreturn has_perm+ @classmethod+ def save(cls, info, instance, cleaned_input):+ instance.save()+ events = cleaned_input.get("events", [])+ models.WebhookEvent.objects.bulk_create(+ [+ models.WebhookEvent(webhook=instance, event_type=event)+ for event in events+ ]+ )+++class WebhookUpdateInput(graphene.InputObjectType):+ target_url = graphene.String(+ description="The url to receive the payload", required=False+ )+ events = graphene.List(+ WebhookEventTypeEnum,+ description="The event that webhook wants to subscribe",+ required=False,+ )+ service_account = graphene.ID(+ required=False, description="serviceAccount ID of which webhook belongs to"+ )+ is_active = graphene.Boolean(+ description="Determine if webhook will be set active or not.", required=False+ )+ secret_key = graphene.String(+ description="Use to create a hash signature with each payload", required=False+ )+class WebhookUpdate(ModelMutation):webhook = graphene.Field(Webhook)class Arguments:id = graphene.ID(required=True, description="ID of a webhook to update.")- input = WebhookSubscribeInput(+ input = WebhookUpdateInput(description="Fields required to update a webhook.", required=True)diff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.pyindex e8b29ec2c0..42670e7747 100644--- a/saleor/graphql/webhook/types.py+++ b/saleor/graphql/webhook/types.py@@ -1,18 +1,30 @@import graphene+import graphene_django_optimizer as gql_optimizerfrom ...webhook import modelsfrom ..core.connection import CountableDjangoObjectType+class WebhookEvent(graphene.ObjectType):+ event_type = graphene.String(description="Name of the event type")++ class Meta:+ description = "Webhook event"++class Webhook(CountableDjangoObjectType):+ events = gql_optimizer.field(+ graphene.List(WebhookEvent, description="List of webhook events"),+ model_field="events",+ )+class Meta:description = "Webhook"model = models.Webhookinterfaces = [graphene.relay.Node]- only_fields = [- "service_account",- "service_account",- "target_url",- "event",- "is_active",- ]+ only_fields = ["service_account", "target_url", "is_active", "secret_key"]++ @staticmethod+ @gql_optimizer.resolver_hints(prefetch_related=("events",))+ def resolve_events(root: models.Webhook, *_args, **_kwargs):+ return root.events.all()diff --git a/saleor/webhook/__init__.py b/saleor/webhook/__init__.pyindex e69de29bb2..bea9757ab6 100644--- a/saleor/webhook/__init__.py+++ b/saleor/webhook/__init__.py@@ -0,0 +1,31 @@+from typing import TYPE_CHECKING, Dict++from django.core.exceptions import ValidationError+from django.utils.translation import pgettext_lazy++if TYPE_CHECKING:+ from ..account.models import ServiceAccount+++class WebhookEventType:+ ORDER_CREATED = "order_created"++ CHOICES = [(ORDER_CREATED, pgettext_lazy("Order has been placed", "Order created"))]++ PERMISSIONS = {ORDER_CREATED: "order.manage_orders"}+++def service_account_has_required_permissions_for_events(+ service_account: "ServiceAccount", events: Dict[str, str]+):+ """Confirm that service account has all permissions required by events."""+ errors = {}+ for event in events:+ required_permission = WebhookEventType.PERMISSIONS.get(event)+ if not service_account.has_perm(required_permission):+ errors[+ event+ ] = "serviceAccount doesn't have expected permissions required by the event"++ if errors:+ raise ValidationError(errors)diff --git a/saleor/webhook/migrations/0001_initial.py b/saleor/webhook/migrations/0001_initial.pyindex 7c4b3329bc..649800ee77 100644--- a/saleor/webhook/migrations/0001_initial.py+++ b/saleor/webhook/migrations/0001_initial.py@@ -1,4 +1,4 @@-# Generated by Django 2.2.4 on 2019-09-06 11:22+# Generated by Django 2.2.4 on 2019-09-12 12:39import django.db.models.deletionfrom django.db import migrations, models@@ -23,17 +23,12 @@ class Migration(migrations.Migration):verbose_name="ID",),),- (- "event",- models.CharField(- db_index=True, max_length=128, verbose_name="Event"- ),- ),("target_url",models.URLField(max_length=255, verbose_name="Target URL"),),("is_active", models.BooleanField(default=True)),+ ("secret_key", models.CharField(blank=True, max_length=255, null=True)),("service_account",models.ForeignKey(@@ -44,5 +39,33 @@ class Migration(migrations.Migration):),],options={"permissions": (("manage_webhooks", "Manage webhooks"),)},- )+ ),+ migrations.CreateModel(+ name="WebhookEvent",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "event_type",+ models.CharField(+ db_index=True, max_length=128, verbose_name="Event type"+ ),+ ),+ (+ "webhook",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="events",+ to="webhook.Webhook",+ ),+ ),+ ],+ ),]diff --git a/saleor/webhook/models.py b/saleor/webhook/models.pyindex 3b00c5760c..e83423a468 100644--- a/saleor/webhook/models.py+++ b/saleor/webhook/models.py@@ -8,9 +8,9 @@ class Webhook(models.Model):service_account = models.ForeignKey(ServiceAccount, related_name="webhooks", on_delete=models.CASCADE)- event = models.CharField("Event", max_length=128, db_index=True)target_url = models.URLField("Target URL", max_length=255)is_active = models.BooleanField(default=True)+ secret_key = models.CharField(max_length=255, null=True, blank=True)class Meta:permissions = (@@ -20,10 +20,12 @@ class Webhook(models.Model):),)- def to_dict(self):- return {- "id": self.id,- "event": self.event,- "target": self.target_url,- "service_account_name": self.service_account.name,- }++class WebhookEvent(models.Model):+ webhook = models.ForeignKey(+ Webhook, related_name="events", on_delete=models.CASCADE+ )+ event_type = models.CharField("Event type", max_length=128, db_index=True)++ def __repr__(self):+ return self.event_typediff --git a/tests/api/test_webhook.py b/tests/api/test_webhook.pyindex 381885757b..3df5d03379 100644--- a/tests/api/test_webhook.py+++ b/tests/api/test_webhook.py@@ -1,13 +1,14 @@import graphenefrom saleor.account.models import ServiceAccount+from saleor.graphql.webhook.enums import WebhookEventTypeEnumfrom saleor.webhook.models import Webhookfrom .utils import assert_no_permission, get_graphql_contentWEBHOOK_CREATE_BY_SERVICE_ACCOUNT = """- mutation webhookCreate($target_url: String, $event: String){- webhookCreate(input:{targetUrl:$target_url, event:$event}){+ mutation webhookCreate($target_url: String, $events: [WebhookEventTypeEnum]){+ webhookCreate(input:{targetUrl:$target_url, events:$events}){errors{fieldmessage@@ -20,23 +21,36 @@ WEBHOOK_CREATE_BY_SERVICE_ACCOUNT = """"""-def test_webhook_create_by_service_account(service_account_api_client):+def test_webhook_create_by_service_account(+ service_account_api_client, service_account, permission_manage_orders+):+ service_account.permissions.add(permission_manage_orders)query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT- variables = {"target_url": "https://www.example.com", "event": "Sample Order"}+ variables = {+ "target_url": "https://www.example.com",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ }response = service_account_api_client.post_graphql(query, variables=variables)get_graphql_content(response)new_webhook = Webhook.objects.get()assert new_webhook.target_url == "https://www.example.com"- assert new_webhook.event == "Sample Order"+ events = new_webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.valuedef test_webhook_create_inactive_service_account(- service_account_api_client, service_account+ service_account_api_client, service_account, permission_manage_orders):+ service_account.permissions.add(permission_manage_orders)service_account.is_active = Falseservice_account.save()query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT- variables = {"target_url": "https://www.example.com", "event": "Sample Order"}+ variables = {+ "target_url": "https://www.example.com",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ }+response = service_account_api_client.post_graphql(query, variables=variables)assert_no_permission(response)@@ -47,7 +61,10 @@ def test_webhook_create_without_service_account(service_account_api_client.service_account = Noneservice_account_api_client.service_token = Nonequery = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT- variables = {"target_url": "https://www.example.com", "event": "Sample Order"}+ variables = {+ "target_url": "https://www.example.com",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ }response = service_account_api_client.post_graphql(query, variables=variables)assert_no_permission(response)@@ -58,15 +75,19 @@ def test_webhook_create_service_account_doesnt_exist(service_account.delete()query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT- variables = {"target_url": "https://www.example.com", "event": "Sample Order"}+ variables = {+ "target_url": "https://www.example.com",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ }response = service_account_api_client.post_graphql(query, variables=variables)assert_no_permission(response)WEBHOOK_CREATE_BY_STAFF = """- mutation webhookCreate($target_url: String, $event: String, $service_account: ID){+ mutation webhookCreate(+ $target_url: String, $events: [WebhookEventTypeEnum], $service_account: ID){webhookCreate(input:{- targetUrl:$target_url, event:$event, serviceAccount: $service_account}){+ targetUrl:$target_url, events:$events, serviceAccount: $service_account}){errors{fieldmessage@@ -80,15 +101,19 @@ WEBHOOK_CREATE_BY_STAFF = """def test_webhook_create_by_staff(- staff_api_client, service_account, permission_manage_webhooks+ staff_api_client,+ service_account,+ permission_manage_webhooks,+ permission_manage_orders,):query = WEBHOOK_CREATE_BY_STAFF+ service_account.permissions.add(permission_manage_orders)service_account_id = graphene.Node.to_global_id("ServiceAccount", service_account.pk)variables = {"target_url": "https://www.example.com",- "event": "Sample Order",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],"service_account": service_account_id,}staff_api_client.user.user_permissions.add(permission_manage_webhooks)@@ -96,8 +121,10 @@ def test_webhook_create_by_staff(get_graphql_content(response)new_webhook = Webhook.objects.get()assert new_webhook.target_url == "https://www.example.com"- assert new_webhook.event == "Sample Order"assert new_webhook.service_account == service_account+ events = new_webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.valuedef test_webhook_create_by_staff_with_inactive_service_account(@@ -110,7 +137,7 @@ def test_webhook_create_by_staff_with_inactive_service_account()variables = {"target_url": "https://www.example.com",- "event": "Sample Order",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],"service_account": service_account_id,}response = staff_api_client.post_graphql(query, variables=variables)@@ -125,7 +152,7 @@ def test_webhook_create_by_staff_without_permission(staff_api_client, service_ac)variables = {"target_url": "https://www.example.com",- "event": "Sample Order",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],"service_account": service_account_id,}response = staff_api_client.post_graphql(query, variables=variables)@@ -211,14 +238,17 @@ def test_webhook_delete_service_account_doesnt_exist(WEBHOOK_UPDATE = """- mutation webhookUpdate($id: ID!, $event: String, $is_active: Boolean){- webhookUpdate(id: $id, input:{event: $event, isActive: $is_active}){+ mutation webhookUpdate(+ $id: ID!, $events: [WebhookEventTypeEnum], $is_active: Boolean){+ webhookUpdate(id: $id, input:{events: $events, isActive: $is_active}){errors{fieldmessage}webhook{- event+ events{+ eventType+ }isActive}}@@ -231,7 +261,11 @@ def test_webhook_update_not_allowed_by_service_account():query = WEBHOOK_UPDATEwebhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id, "event": "TestEvent", "is_active": False}+ variables = {+ "id": webhook_id,+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ "is_active": False,+ }response = service_account_api_client.post_graphql(query, variables=variables)assert_no_permission(response)@@ -241,13 +275,19 @@ def test_webhook_update_by_staff():query = WEBHOOK_UPDATEwebhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id, "event": "TestEvent", "is_active": False}+ variables = {+ "id": webhook_id,+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ "is_active": False,+ }staff_api_client.user.user_permissions.add(permission_manage_webhooks)response = staff_api_client.post_graphql(query, variables=variables)get_graphql_content(response)webhook.refresh_from_db()assert webhook.is_active is False- assert webhook.event == "TestEvent"+ events = webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.valuedef test_webhook_update_by_staff_without_permission(@@ -255,7 +295,11 @@ def test_webhook_update_by_staff_without_permission():query = WEBHOOK_UPDATEwebhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id, "event": "TestEvent", "is_active": False}+ variables = {+ "id": webhook_id,+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ "is_active": False,+ }response = staff_api_client.post_graphql(query, variables=variables)assert_no_permission(response)@@ -270,7 +314,9 @@ QUERY_WEBHOOKS = """}targetUrlid- event+ events{+ eventType+ }}}}@@ -301,7 +347,9 @@ QUERY_WEBHOOK = """webhook(id: $id){idisActive- event+ events{+ eventType+ }}}"""@@ -309,8 +357,6 @@ QUERY_WEBHOOK = """def test_query_webhook_by_staff(staff_api_client, webhook, permission_manage_webhooks):query = QUERY_WEBHOOK- webhook.id = None- webhook.save()webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)variables = {"id": webhook_id}@@ -321,7 +367,9 @@ def test_query_webhook_by_staff(staff_api_client, webhook, permission_manage_webwebhook_response = content["data"]["webhook"]assert webhook_response["id"] == webhook_idassert webhook_response["isActive"] == webhook.is_active- assert webhook_response["event"] == webhook.event+ events = webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.valuedef test_query_webhook_by_staff_without_permission(staff_api_client, webhook):diff --git a/tests/conftest.py b/tests/conftest.pyindex f3678633a4..3231dde513 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -51,6 +51,7 @@ from saleor.product.models import (from saleor.shipping.models import ShippingMethod, ShippingMethodType, ShippingZonefrom saleor.site import AuthenticationBackendsfrom saleor.site.models import AuthorizationKey, SiteSettings+from saleor.webhook import WebhookEventTypefrom saleor.webhook.models import Webhookfrom tests.utils import create_image@@ -1434,8 +1435,7 @@ def other_description_raw():@pytest.fixturedef webhook(service_account):webhook = Webhook.objects.create(- service_account=service_account,- target_url="http://www.example.com/test",- event="New Event",+ service_account=service_account, target_url="http://www.example.com/test")+ webhook.events.create(event_type=WebhookEventType.ORDER_CREATED)return webhook