Skip to content

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

Add api to subscribe/unsubscribe/update webhooks

Maciej Korycinski98de23d30268
diff --git a/saleor/core/permissions.py b/saleor/core/permissions.py
index 034930139b..de70c32442 100644
--- a/saleor/core/permissions.py
+++ b/saleor/core/permissions.py
@@ -15,6 +15,7 @@ MODELS_PERMISSIONS = [
"shipping.manage_shipping",
"site.manage_settings",
"site.manage_translations",
+ "webhook.manage_webhooks",
]
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index ef41f2fb41..34a8c28bce 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -64,8 +64,8 @@ class AccountUpdate(BaseCustomerCreate):
model = models.User
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def perform_mutation(cls, root, info, **data):
@@ -90,8 +90,8 @@ class AccountRequestDeletion(BaseMutation):
)
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def perform_mutation(cls, root, info, **data):
@@ -117,8 +117,8 @@ class AccountDelete(ModelDeleteMutation):
model = models.User
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def clean_instance(cls, info, instance):
@@ -167,8 +167,8 @@ class AccountAddressCreate(ModelMutation):
model = models.Address
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def perform_mutation(cls, root, info, **data):
@@ -213,8 +213,8 @@ class AccountSetDefaultAddress(BaseMutation):
description = "Sets a default address for the authenticated user."
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def perform_mutation(cls, _root, info, **data):
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index b51fd43bfd..aad6df1a3b 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -127,8 +127,8 @@ class PasswordChange(BaseMutation):
description = "Change the password of the logged in user."
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def perform_mutation(cls, _root, info, **data):
@@ -204,7 +204,7 @@ class BaseAddressDelete(ModelDeleteMutation):
@classmethod
def perform_mutation(cls, _root, info, **data):
- if not cls.check_permissions(info.context.user):
+ if not cls.check_permissions(info.context):
raise PermissionDenied()
node_id = data.get("id")
diff --git a/saleor/graphql/account/mutations/deprecated_account.py b/saleor/graphql/account/mutations/deprecated_account.py
index b35c63f258..2bce0f18dc 100644
--- a/saleor/graphql/account/mutations/deprecated_account.py
+++ b/saleor/graphql/account/mutations/deprecated_account.py
@@ -54,8 +54,8 @@ class LoggedUserUpdate(BaseCustomerCreate):
model = models.User
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def perform_mutation(cls, root, info, **data):
@@ -91,8 +91,8 @@ class CustomerAddressCreate(ModelMutation):
exclude = ["user_addresses"]
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def perform_mutation(cls, root, info, **data):
@@ -128,8 +128,8 @@ class CustomerSetDefaultAddress(BaseMutation):
)
@classmethod
- def check_permissions(cls, user):
- return user.is_authenticated
+ def check_permissions(cls, context):
+ return context.user.is_authenticated
@classmethod
def perform_mutation(cls, _root, info, **data):
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index 2e69ebc07d..8487ab4a5d 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -221,7 +221,7 @@ class StaffDelete(StaffDeleteMixin, UserDelete):
@classmethod
def perform_mutation(cls, _root, info, **data):
- if not cls.check_permissions(info.context.user):
+ if not cls.check_permissions(info.context):
raise PermissionDenied()
user_id = data.get("id")
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index e3e18c8c21..f7f810c613 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -14,6 +14,7 @@ from .product.schema import ProductMutations, ProductQueries
from .shipping.schema import ShippingMutations, ShippingQueries
from .shop.schema import ShopMutations, ShopQueries
from .translations.schema import TranslationQueries
+from .webhook.schema import WebhookMutations, WebhookQueries
class Query(
@@ -31,6 +32,7 @@ class Query(
ShippingQueries,
ShopQueries,
TranslationQueries,
+ WebhookQueries,
):
node = graphene.Node.Field()
@@ -49,6 +51,7 @@ class Mutations(
ProductMutations,
ShippingMutations,
ShopMutations,
+ WebhookMutations,
):
pass
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index f9af4e6c22..99cdc34e6e 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -185,22 +185,27 @@ class BaseMutation(graphene.Mutation):
return instance
@classmethod
- def check_permissions(cls, user):
- """Determine whether user has rights to perform this mutation.
+ def check_permissions(cls, context):
+ """Determine whether user or service account has rights to perform this mutation.
- Default implementation assumes that user is allowed to perform any
+ Default implementation assumes that account is allowed to perform any
mutation. By overriding this method or defining required permissions
in the meta-class, you can restrict access to it.
- The `user` parameter is the User instance associated with the request.
+ The `context` parameter is the Context instance associated with the request.
"""
- if cls._meta.permissions:
- return user.has_perms(cls._meta.permissions)
- return True
+ if not cls._meta.permissions:
+ return True
+ if context.user.has_perms(cls._meta.permissions):
+ return True
+ service_account = getattr(context, "service_account", None)
+ if service_account and service_account.has_perms(cls._meta.permissions):
+ return True
+ return False
@classmethod
def mutate(cls, root, info, **data):
- if not cls.check_permissions(info.context.user):
+ if not cls.check_permissions(info.context):
raise PermissionDenied()
try:
@@ -373,7 +378,7 @@ class ModelDeleteMutation(ModelMutation):
@classmethod
def perform_mutation(cls, _root, info, **data):
"""Perform a mutation that deletes a model instance."""
- if not cls.check_permissions(info.context.user):
+ if not cls.check_permissions(info.context):
raise PermissionDenied()
node_id = data.get("id")
@@ -462,7 +467,7 @@ class BaseBulkMutation(BaseMutation):
@classmethod
def mutate(cls, root, info, **data):
- if not cls.check_permissions(info.context.user):
+ if not cls.check_permissions(info.context):
raise PermissionDenied()
count, errors = cls.perform_mutation(root, info, **data)
diff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.py
index 0b2043788a..228435863b 100644
--- a/saleor/graphql/middleware.py
+++ b/saleor/graphql/middleware.py
@@ -46,6 +46,7 @@ def service_account_middleware(get_response):
def middleware(request):
if request.path == reverse("api"):
+ request.service_account = None
auth = request.META.get(service_account_auth_header, "").split()
if len(auth) == 2:
auth_prefix, auth_token = auth
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 5e2c67431c..2fa4564069 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -288,8 +288,8 @@ class AttributeAssign(BaseMutation):
description = "Assign attributes to a given product type."
@classmethod
- def check_permissions(cls, user):
- return user.has_perm("product.manage_products")
+ def check_permissions(cls, context):
+ return context.user.has_perm("product.manage_products")
@classmethod
def get_operations(cls, info, operations: List[AttributeAssignInput]):
@@ -418,8 +418,8 @@ class AttributeUnassign(BaseMutation):
description = "Un-assign attributes from a given product type."
@classmethod
- def check_permissions(cls, user):
- return user.has_perm("product.manage_products")
+ def check_permissions(cls, context):
+ return context.user.has_perm("product.manage_products")
@classmethod
def save_field_values(cls, product_type, field, pks):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 1831ea233c..6d270049bb 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1767,6 +1767,9 @@ input MoveProductInput {
}
type Mutations {
+ webhookCreate(input: WebhookSubscribeInput!): WebhookCreate
+ webhookDelete(id: ID!): WebhookDelete
+ webhookUpdate(id: ID!, input: WebhookSubscribeInput!): WebhookUpdate
authorizationKeyAdd(input: AuthorizationKeyInput!, keyType: AuthorizationKeyType!): AuthorizationKeyAdd
authorizationKeyDelete(keyType: AuthorizationKeyType!): AuthorizationKeyDelete
homepageCollectionUpdate(collection: ID): HomepageCollectionUpdate
@@ -2449,6 +2452,7 @@ enum PermissionEnum {
MANAGE_SHIPPING
MANAGE_SETTINGS
MANAGE_TRANSLATIONS
+ MANAGE_WEBHOOKS
}
type Plugin implements Node {
@@ -2922,6 +2926,8 @@ type ProductVariantUpdatePrivateMeta {
}
type Query {
+ webhook(id: ID!): Webhook
+ webhooks(before: String, after: String, first: Int, last: Int): WebhookCountableConnection
translations(kind: TranslatableKinds!, before: String, after: String, first: Int, last: Int): TranslatableItemConnection
shop: Shop
shippingZone(id: ID!): ShippingZone
@@ -3762,6 +3768,47 @@ type VoucherUpdate {
voucher: Voucher
}
+type Webhook implements Node {
+ serviceAccount: ServiceAccount!
+ event: String!
+ targetUrl: String!
+ isActive: Boolean!
+ id: ID!
+}
+
+type WebhookCountableConnection {
+ pageInfo: PageInfo!
+ edges: [WebhookCountableEdge!]!
+ totalCount: Int
+}
+
+type WebhookCountableEdge {
+ node: Webhook!
+ cursor: String!
+}
+
+type WebhookCreate {
+ errors: [Error!]
+ webhook: Webhook
+}
+
+type WebhookDelete {
+ errors: [Error!]
+ webhook: Webhook
+}
+
+input WebhookSubscribeInput {
+ targetUrl: String
+ event: String
+ serviceAccount: ID
+ isActive: Boolean
+}
+
+type WebhookUpdate {
+ errors: [Error!]
+ webhook: Webhook
+}
+
type Weight {
unit: String!
value: Float!
diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.py
index 1c0ba7545f..e065be4ba4 100644
--- a/saleor/graphql/translations/mutations.py
+++ b/saleor/graphql/translations/mutations.py
@@ -18,8 +18,8 @@ class BaseTranslateMutation(ModelMutation):
abstract = True
@classmethod
- def check_permissions(cls, user):
- return user.has_perm("site.manage_translations")
+ def check_permissions(cls, context):
+ return context.user.has_perm("site.manage_translations")
@classmethod
def perform_mutation(cls, _root, info, **data):
diff --git a/saleor/graphql/webhook/__init__.py b/saleor/graphql/webhook/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.py
new file mode 100644
index 0000000000..df2a5f2885
--- /dev/null
+++ b/saleor/graphql/webhook/mutations.py
@@ -0,0 +1,125 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ...webhook import models
+from ..core.mutations import ModelDeleteMutation, ModelMutation
+from .types import Webhook
+
+
+class WebhookSubscribeInput(graphene.InputObjectType):
+ target_url = graphene.String(description="The url to receive the payload")
+ event = graphene.String(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
+ )
+
+
+class WebhookCreate(ModelMutation):
+ class Arguments:
+ input = WebhookSubscribeInput(
+ description="Fields required to create a webhook.", required=True
+ )
+
+ class Meta:
+ description = "Creates a new webhook subscription"
+ model = models.Webhook
+ permissions = ("webhook.manage_webhooks",)
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ cleaned_data = super().clean_input(info, instance, data)
+
+ service_account = cleaned_data.get("service_account")
+
+ # We are not able to check it in `check_permission`.
+ # We need to confirm that cleaned_data has service_account_id or
+ # context has assigned service account instance
+ if not instance.service_account_id and not service_account:
+ raise ValidationError("Missing token or serviceAccount")
+
+ if instance.service_account_id:
+ # Let's skip service_account id in case when context has
+ # service_account instance
+ service_account = instance.service_account
+ cleaned_data.pop("service_account", None)
+
+ if not service_account or not service_account.is_active:
+ 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
+ def get_instance(cls, info, **data):
+ instance = super().get_instance(info, **data)
+ service_account = info.context.service_account
+ instance.service_account = service_account
+ return instance
+
+ @classmethod
+ def check_permissions(cls, context):
+ has_perm = super().check_permissions(context)
+ has_perm = bool(context.service_account) or has_perm
+ return has_perm
+
+
+class WebhookUpdate(ModelMutation):
+ webhook = graphene.Field(Webhook)
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a webhook to update.")
+ input = WebhookSubscribeInput(
+ description="Fields required to update a webhook.", required=True
+ )
+
+ class Meta:
+ description = "Updates a webhook subscription"
+ model = models.Webhook
+ permissions = ("webhook.manage_webhooks",)
+
+
+class WebhookDelete(ModelDeleteMutation):
+ webhook = graphene.Field(Webhook)
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a webhook to delete.")
+
+ class Meta:
+ description = "Deletes a webhook subscription."
+ model = models.Webhook
+ permissions = ("webhook.manage_webhooks",)
+
+ @classmethod
+ def check_permissions(cls, context):
+ has_perm = super().check_permissions(context)
+ has_perm = bool(context.service_account) or has_perm
+ return has_perm
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ node_id = data["id"]
+ _, object_id = graphene.Node.from_global_id(node_id)
+
+ service_account = info.context.service_account
+ if service_account:
+ if not service_account.is_active:
+ raise ValidationError(
+ {
+ "serviceAccount": "Service account needs to be active to "
+ "delete webhook"
+ }
+ )
+ try:
+ service_account.webhooks.get(id=object_id)
+ except models.Webhook.DoesNotExist:
+ raise ValidationError(
+ {"id": "Couldn't resolve to a node: %s" % node_id}
+ )
+
+ return super().perform_mutation(_root, info, **data)
diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.py
new file mode 100644
index 0000000000..b370122c99
--- /dev/null
+++ b/saleor/graphql/webhook/resolvers.py
@@ -0,0 +1,5 @@
+from ...webhook.models import Webhook
+
+
+def resolve_webhooks():
+ return Webhook.objects.all()
diff --git a/saleor/graphql/webhook/schema.py b/saleor/graphql/webhook/schema.py
new file mode 100644
index 0000000000..ebc885915b
--- /dev/null
+++ b/saleor/graphql/webhook/schema.py
@@ -0,0 +1,30 @@
+import graphene
+
+from ..core.fields import PrefetchingConnectionField
+from ..decorators import permission_required
+from .mutations import WebhookCreate, WebhookDelete, WebhookUpdate
+from .resolvers import resolve_webhooks
+from .types import Webhook
+
+
+class WebhookQueries(graphene.ObjectType):
+ webhook = graphene.Field(
+ Webhook,
+ id=graphene.Argument(graphene.ID, required=True),
+ description="Lookup a webhook by ID.",
+ )
+ webhooks = PrefetchingConnectionField(Webhook, description="List of webhooks")
+
+ @permission_required("webhook.manage_webhooks")
+ def resolve_webhooks(self, _info, **_kwargs):
+ return resolve_webhooks()
+
+ @permission_required("webhook.manage_webhooks")
+ def resolve_webhook(self, info, **data):
+ return graphene.Node.get_node_from_global_id(info, data["id"], Webhook)
+
+
+class WebhookMutations(graphene.ObjectType):
+ webhook_create = WebhookCreate.Field()
+ webhook_delete = WebhookDelete.Field()
+ webhook_update = WebhookUpdate.Field()
diff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.py
new file mode 100644
index 0000000000..e8b29ec2c0
--- /dev/null
+++ b/saleor/graphql/webhook/types.py
@@ -0,0 +1,18 @@
+import graphene
+
+from ...webhook import models
+from ..core.connection import CountableDjangoObjectType
+
+
+class Webhook(CountableDjangoObjectType):
+ class Meta:
+ description = "Webhook"
+ model = models.Webhook
+ interfaces = [graphene.relay.Node]
+ only_fields = [
+ "service_account",
+ "service_account",
+ "target_url",
+ "event",
+ "is_active",
+ ]
diff --git a/saleor/settings.py b/saleor/settings.py
index b2477287b9..737959a4db 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -254,6 +254,7 @@ INSTALLED_APPS = [
"saleor.data_feeds",
"saleor.page",
"saleor.payment",
+ "saleor.webhook",
# External apps
"versatileimagefield",
"django_babel",
diff --git a/saleor/webhook/__init__.py b/saleor/webhook/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/webhook/migrations/0001_initial.py b/saleor/webhook/migrations/0001_initial.py
new file mode 100644
index 0000000000..7c4b3329bc
--- /dev/null
+++ b/saleor/webhook/migrations/0001_initial.py
@@ -0,0 +1,48 @@
+# Generated by Django 2.2.4 on 2019-09-06 11:22
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [("account", "0033_serviceaccount")]
+
+ operations = [
+ migrations.CreateModel(
+ name="Webhook",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ 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)),
+ (
+ "service_account",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="webhooks",
+ to="account.ServiceAccount",
+ ),
+ ),
+ ],
+ options={"permissions": (("manage_webhooks", "Manage webhooks"),)},
+ )
+ ]
diff --git a/saleor/webhook/migrations/__init__.py b/saleor/webhook/migrations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/webhook/models.py b/saleor/webhook/models.py
new file mode 100644
index 0000000000..3b00c5760c
--- /dev/null
+++ b/saleor/webhook/models.py
@@ -0,0 +1,29 @@
+from django.db import models
+from django.utils.translation import pgettext_lazy
+
+from ..account.models import ServiceAccount
+
+
+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)
+
+ class Meta:
+ permissions = (
+ (
+ "manage_webhooks",
+ pgettext_lazy("Webhook description", "Manage webhooks"),
+ ),
+ )
+
+ def to_dict(self):
+ return {
+ "id": self.id,
+ "event": self.event,
+ "target": self.target_url,
+ "service_account_name": self.service_account.name,
+ }
diff --git a/tests/api/test_webhook.py b/tests/api/test_webhook.py
new file mode 100644
index 0000000000..381885757b
--- /dev/null
+++ b/tests/api/test_webhook.py
@@ -0,0 +1,332 @@
+import graphene
+
+from saleor.account.models import ServiceAccount
+from saleor.webhook.models import Webhook
+
+from .utils import assert_no_permission, get_graphql_content
+
+WEBHOOK_CREATE_BY_SERVICE_ACCOUNT = """
+ mutation webhookCreate($target_url: String, $event: String){
+ webhookCreate(input:{targetUrl:$target_url, event:$event}){
+ errors{
+ field
+ message
+ }
+ webhook{
+ id
+ }
+ }
+ }
+"""
+
+
+def test_webhook_create_by_service_account(service_account_api_client):
+ query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT
+ variables = {"target_url": "https://www.example.com", "event": "Sample Order"}
+ 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"
+
+
+def test_webhook_create_inactive_service_account(
+ service_account_api_client, service_account
+):
+ service_account.is_active = False
+ service_account.save()
+ query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT
+ variables = {"target_url": "https://www.example.com", "event": "Sample Order"}
+ response = service_account_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
+
+
+def test_webhook_create_without_service_account(
+ service_account_api_client, service_account
+):
+ service_account_api_client.service_account = None
+ service_account_api_client.service_token = None
+ query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT
+ variables = {"target_url": "https://www.example.com", "event": "Sample Order"}
+ response = service_account_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
+
+
+def test_webhook_create_service_account_doesnt_exist(
+ service_account_api_client, service_account
+):
+ service_account.delete()
+
+ query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT
+ variables = {"target_url": "https://www.example.com", "event": "Sample Order"}
+ 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){
+ webhookCreate(input:{
+ targetUrl:$target_url, event:$event, serviceAccount: $service_account}){
+ errors{
+ field
+ message
+ }
+ webhook{
+ id
+ }
+ }
+ }
+"""
+
+
+def test_webhook_create_by_staff(
+ staff_api_client, service_account, permission_manage_webhooks
+):
+ query = WEBHOOK_CREATE_BY_STAFF
+ service_account_id = graphene.Node.to_global_id(
+ "ServiceAccount", service_account.pk
+ )
+ variables = {
+ "target_url": "https://www.example.com",
+ "event": "Sample Order",
+ "service_account": service_account_id,
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_webhooks)
+ response = staff_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"
+ assert new_webhook.service_account == service_account
+
+
+def test_webhook_create_by_staff_with_inactive_service_account(
+ staff_api_client, service_account
+):
+ service_account.is_active = False
+ query = WEBHOOK_CREATE_BY_STAFF
+ service_account_id = graphene.Node.to_global_id(
+ "ServiceAccount", service_account.pk
+ )
+ variables = {
+ "target_url": "https://www.example.com",
+ "event": "Sample Order",
+ "service_account": service_account_id,
+ }
+ response = staff_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
+ assert Webhook.objects.count() == 0
+
+
+def test_webhook_create_by_staff_without_permission(staff_api_client, service_account):
+ query = WEBHOOK_CREATE_BY_STAFF
+ service_account_id = graphene.Node.to_global_id(
+ "ServiceAccount", service_account.pk
+ )
+ variables = {
+ "target_url": "https://www.example.com",
+ "event": "Sample Order",
+ "service_account": service_account_id,
+ }
+ response = staff_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
+ assert Webhook.objects.count() == 0
+
+
+WEBHOOK_DELETE_BY_SERVICE_ACCOUNT = """
+ mutation webhookDelete($id: ID!){
+ webhookDelete(id: $id){
+ errors{
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_webhook_delete_by_service_account(service_account_api_client, webhook):
+ query = WEBHOOK_DELETE_BY_SERVICE_ACCOUNT
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id}
+ response = service_account_api_client.post_graphql(query, variables=variables)
+ get_graphql_content(response)
+ assert Webhook.objects.count() == 0
+
+
+def test_webhook_delete_by_service_account_with_wrong_webhook(
+ service_account_api_client, webhook
+):
+ second_service_account = ServiceAccount.objects.create(name="second")
+ webhook.service_account = second_service_account
+ webhook.save()
+
+ query = WEBHOOK_DELETE_BY_SERVICE_ACCOUNT
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id}
+ response = service_account_api_client.post_graphql(query, variables=variables)
+ get_graphql_content(response)
+
+ webhook.refresh_from_db()
+ assert Webhook.objects.count() == 1
+
+
+def test_webhook_delete_by_service_account_wrong_webhook(
+ service_account_api_client, webhook
+):
+ query = WEBHOOK_DELETE_BY_SERVICE_ACCOUNT
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id}
+ webhook.delete()
+
+ response = service_account_api_client.post_graphql(query, variables=variables)
+ content = get_graphql_content(response)
+ errors = content["data"]["webhookDelete"]["errors"]
+ assert errors[0]["field"] == "id"
+
+
+def test_webhook_delete_by_inactive_service_account(
+ service_account_api_client, webhook
+):
+ service_account = webhook.service_account
+ service_account.is_active = False
+ service_account.save()
+ query = WEBHOOK_DELETE_BY_SERVICE_ACCOUNT
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id}
+ response = service_account_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
+
+
+def test_webhook_delete_service_account_doesnt_exist(
+ service_account_api_client, service_account
+):
+ service_account.delete()
+
+ query = WEBHOOK_DELETE_BY_SERVICE_ACCOUNT
+ webhook_id = graphene.Node.to_global_id("Webhook", 1)
+ variables = {"id": webhook_id}
+ response = service_account_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
+
+
+WEBHOOK_UPDATE = """
+ mutation webhookUpdate($id: ID!, $event: String, $is_active: Boolean){
+ webhookUpdate(id: $id, input:{event: $event, isActive: $is_active}){
+ errors{
+ field
+ message
+ }
+ webhook{
+ event
+ isActive
+ }
+ }
+ }
+"""
+
+
+def test_webhook_update_not_allowed_by_service_account(
+ service_account_api_client, service_account, webhook
+):
+ query = WEBHOOK_UPDATE
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id, "event": "TestEvent", "is_active": False}
+ response = service_account_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
+
+
+def test_webhook_update_by_staff(
+ staff_api_client, service_account, webhook, permission_manage_webhooks
+):
+ query = WEBHOOK_UPDATE
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id, "event": "TestEvent", "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"
+
+
+def test_webhook_update_by_staff_without_permission(
+ staff_api_client, service_account, webhook
+):
+ query = WEBHOOK_UPDATE
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id, "event": "TestEvent", "is_active": False}
+ response = staff_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
+
+
+QUERY_WEBHOOKS = """
+ query webhooks{
+ webhooks(first:5){
+ edges{
+ node{
+ serviceAccount{
+ id
+ }
+ targetUrl
+ id
+ event
+ }
+ }
+ }
+ }
+"""
+
+
+def test_query_webhooks_by_staff(staff_api_client, webhook, permission_manage_webhooks):
+ query = QUERY_WEBHOOKS
+ webhook.id = None
+ webhook.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_webhooks)
+ response = staff_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+ webhooks = content["data"]["webhooks"]["edges"]
+ assert len(webhooks) == 2
+
+
+def test_query_webhooks_by_staff_without_permission(staff_api_client, webhook):
+ query = QUERY_WEBHOOKS
+ response = staff_api_client.post_graphql(query)
+ assert_no_permission(response)
+
+
+QUERY_WEBHOOK = """
+ query webhook($id: ID!){
+ webhook(id: $id){
+ id
+ isActive
+ event
+ }
+ }
+"""
+
+
+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}
+ staff_api_client.user.user_permissions.add(permission_manage_webhooks)
+ response = staff_api_client.post_graphql(query, variables=variables)
+
+ content = get_graphql_content(response)
+ webhook_response = content["data"]["webhook"]
+ assert webhook_response["id"] == webhook_id
+ assert webhook_response["isActive"] == webhook.is_active
+ assert webhook_response["event"] == webhook.event
+
+
+def test_query_webhook_by_staff_without_permission(staff_api_client, webhook):
+ query = QUERY_WEBHOOK
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id}
+ response = staff_api_client.post_graphql(query, variables=variables)
+ assert_no_permission(response)
diff --git a/tests/conftest.py b/tests/conftest.py
index 2b718483fb..f3678633a4 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, ShippingZone
from saleor.site import AuthenticationBackends
from saleor.site.models import AuthorizationKey, SiteSettings
+from saleor.webhook.models import Webhook
from tests.utils import create_image
@@ -1056,6 +1057,11 @@ def permission_manage_translations():
return Permission.objects.get(codename="manage_translations")
+def permission_manage_webhooks():
+ return Permission.objects.get(codename="manage_webhooks")
+
+
@pytest.fixture
def collection(db):
collection = Collection.objects.create(
@@ -1423,3 +1429,13 @@ def other_description_raw():
"Saleor is powered by a GraphQL server running on top of Python 3 "
"and a Django 2 framework."
)
+
+
+def webhook(service_account):
+ webhook = Webhook.objects.create(
+ service_account=service_account,
+ target_url="http://www.example.com/test",
+ event="New Event",
+ )
+ return webhook