Skip to content

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

Feature/extending dashboard with apps (#7701)

Maciej Korycinski79d1e70dc4e1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 412dba7999..6d62419b5b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,7 @@
All notable, unreleased changes to this project will be documented in this file. For the released changes, please visit the [Releases](https://github.com/mirumee/saleor/releases) page.
# 3.1.0 [Unreleased]
+- Extend app by `AppExtension` - #7701 by @korycins
# 3.0.0 [Unreleased]
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index 36ba92e909..ec08515a7b 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -1,9 +1,9 @@
import requests
from django.contrib.sites.models import Site
-from django.core.exceptions import ValidationError
-from ..app.validators import AppURLValidator
-from .models import App, AppInstallation
+from ..core.permissions import get_permission_names
+from .manifest_validations import clean_manifest_data
+from .models import App, AppExtension, AppInstallation
from .types import AppType
REQUEST_TIMEOUT = 25
@@ -19,24 +19,18 @@ def send_app_token(target_url: str, token: str):
response.raise_for_status()
-def validate_manifest_fields(manifest_data):
- token_target_url = manifest_data.get("tokenTargetUrl")
- try:
- url_validator = AppURLValidator()
- url_validator(token_target_url)
- except ValidationError:
- raise ValidationError({"tokenTargetUrl": "Incorrect format."})
-
-
def install_app(
app_installation: AppInstallation,
activate: bool = False,
):
response = requests.get(app_installation.manifest_url, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
+ assigned_permissions = app_installation.permissions.all()
manifest_data = response.json()
- validate_manifest_fields(manifest_data)
+ manifest_data["permissions"] = get_permission_names(assigned_permissions)
+
+ clean_manifest_data(manifest_data)
app = App.objects.create(
name=app_installation.app_name,
@@ -53,6 +47,17 @@ def install_app(
type=AppType.THIRDPARTY,
)
app.permissions.set(app_installation.permissions.all())
+ for extension_data in manifest_data.get("extensions", []):
+ extension = AppExtension.objects.create(
+ app=app,
+ label=extension_data.get("label"),
+ url=extension_data.get("url"),
+ view=extension_data.get("view"),
+ type=extension_data.get("type"),
+ target=extension_data.get("target"),
+ )
+ extension.permissions.set(extension_data.get("permissions", []))
+
token = app.tokens.create(name="Default token")
try:
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
new file mode 100644
index 0000000000..02c0d458b2
--- /dev/null
+++ b/saleor/app/manifest_validations.py
@@ -0,0 +1,207 @@
+from collections import defaultdict
+from typing import Dict, Iterable, List
+
+from django.contrib.auth.models import Permission
+from django.core.exceptions import ValidationError
+from django.db.models import Value
+from django.db.models.functions import Concat
+
+from ..core.permissions import (
+ get_permissions,
+ get_permissions_enum_list,
+ split_permission_codename,
+)
+from .error_codes import AppErrorCode
+from .types import AppExtensionTarget, AppExtensionType, AppExtensionView
+from .validators import AppURLValidator
+
+T_ERRORS = Dict[str, List[ValidationError]]
+
+
+AVAILABLE_APP_EXTENSION_CONFIGS = {
+ AppExtensionType.DETAILS: {
+ AppExtensionView.PRODUCT: [
+ AppExtensionTarget.CREATE,
+ AppExtensionTarget.MORE_ACTIONS,
+ ]
+ },
+ AppExtensionType.OVERVIEW: {
+ AppExtensionView.PRODUCT: [
+ AppExtensionTarget.CREATE,
+ AppExtensionTarget.MORE_ACTIONS,
+ ]
+ },
+}
+
+
+def _clean_app_url(url):
+ url_validator = AppURLValidator()
+ url_validator(url)
+
+
+def clean_manifest_url(manifest_url):
+ try:
+ _clean_app_url(manifest_url)
+ except (ValidationError, AttributeError):
+ msg = "Enter a valid URL."
+ code = AppErrorCode.INVALID_URL_FORMAT.value
+ raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
+
+
+def clean_permissions(
+ required_permissions: List[str], saleor_permissions: Iterable[Permission]
+) -> List[Permission]:
+ missing_permissions = []
+ all_permissions = {perm[0]: perm[1] for perm in get_permissions_enum_list()}
+ for perm in required_permissions:
+ if not all_permissions.get(perm):
+ missing_permissions.append(perm)
+ if missing_permissions:
+ error_msg = "Given permissions don't exist."
+ code = AppErrorCode.INVALID_PERMISSION.value
+ params = {"permissions": missing_permissions}
+ raise ValidationError(error_msg, code=code, params=params)
+
+ permissions = [all_permissions[perm] for perm in required_permissions]
+ permissions = split_permission_codename(permissions)
+ return [p for p in saleor_permissions if p.codename in permissions]
+
+
+def clean_manifest_data(manifest_data):
+ errors: T_ERRORS = defaultdict(list)
+
+ validate_required_fields(manifest_data, errors)
+ try:
+ _clean_app_url(manifest_data["tokenTargetUrl"])
+ except (ValidationError, AttributeError):
+ errors["tokenTargetUrl"].append(
+ ValidationError(
+ "Incorrect format.",
+ code=AppErrorCode.INVALID_URL_FORMAT.value,
+ )
+ )
+
+ saleor_permissions = get_permissions().annotate(
+ formated_codename=Concat("content_type__app_label", Value("."), "codename")
+ )
+ try:
+ app_permissions = clean_permissions(
+ manifest_data.get("permissions", []), saleor_permissions
+ )
+ except ValidationError as e:
+ errors["permissions"].append(e)
+ app_permissions = []
+
+ manifest_data["permissions"] = app_permissions
+
+ if not errors:
+ clean_extensions(manifest_data, app_permissions, errors)
+
+ if errors:
+ raise ValidationError(errors)
+
+
+def _clean_extension_permissions(extension, app_permissions, errors):
+ permissions_data = extension.get("permissions", [])
+ try:
+ extension_permissions = clean_permissions(permissions_data, app_permissions)
+ except ValidationError as e:
+ e.params["label"] = extension.get("label")
+ errors["extensions"].append(e)
+ return
+
+ if len(extension_permissions) != len(permissions_data):
+ errors["extensions"].append(
+ ValidationError(
+ "Extension permission must be listed in App's permissions.",
+ code=AppErrorCode.OUT_OF_SCOPE_PERMISSION.value,
+ )
+ )
+
+ extension["permissions"] = extension_permissions
+
+
+def _validate_configuration(extension, errors):
+
+ available_config_for_type = AVAILABLE_APP_EXTENSION_CONFIGS.get(
+ extension["type"], {}
+ )
+ available_config_for_type_and_view = available_config_for_type.get(
+ extension["view"], []
+ )
+
+ if extension["target"] not in available_config_for_type_and_view:
+ msg = (
+ "Incorrect configuration of app extension for fields: view, type and "
+ "target."
+ )
+ errors["extensions"].append(
+ ValidationError(
+ msg,
+ code=AppErrorCode.INVALID.value,
+ )
+ )
+
+
+def clean_extensions(manifest_data, app_permissions, errors):
+ extensions = manifest_data.get("extensions", [])
+ enum_map = [
+ (AppExtensionView, "view"),
+ (AppExtensionType, "type"),
+ (AppExtensionTarget, "target"),
+ ]
+ for extension in extensions:
+ for extension_enum, key in enum_map:
+ if extension[key] in [code.upper() for code, _ in extension_enum.CHOICES]:
+ extension[key] = getattr(extension_enum, extension[key])
+ else:
+ errors["extensions"].append(
+ ValidationError(
+ f"Incorrect value for field: {key}",
+ code=AppErrorCode.INVALID.value,
+ )
+ )
+
+ try:
+ _clean_app_url(extension["url"])
+ except (ValidationError, AttributeError):
+ errors["extensions"].append(
+ ValidationError(
+ "Incorrect value for field: url.",
+ code=AppErrorCode.INVALID_URL_FORMAT.value,
+ )
+ )
+ _validate_configuration(extension, errors)
+ _clean_extension_permissions(extension, app_permissions, errors)
+
+
+def validate_required_fields(manifest_data, errors):
+ manifest_required_fields = {"id", "version", "name", "tokenTargetUrl"}
+ extension_required_fields = {
+ "label",
+ "url",
+ "view",
+ "type",
+ "target",
+ }
+ manifest_missing_fields = manifest_required_fields.difference(manifest_data)
+ if manifest_missing_fields:
+ [
+ errors[missing_field].append(
+ ValidationError("Field required.", code=AppErrorCode.REQUIRED.value)
+ )
+ for missing_field in manifest_missing_fields
+ ]
+
+ app_extensions_data = manifest_data.get("extensions", [])
+ for extension in app_extensions_data:
+ extension_fields = set(extension.keys())
+ missing_fields = extension_required_fields.difference(extension_fields)
+ if missing_fields:
+ errors["extensions"].append(
+ ValidationError(
+ "Missing required fields for app extension: %s."
+ % ", ".join(missing_fields),
+ code=AppErrorCode.REQUIRED.value,
+ )
+ )
diff --git a/saleor/app/migrations/0005_appextension.py b/saleor/app/migrations/0005_appextension.py
new file mode 100644
index 0000000000..9a9ed03222
--- /dev/null
+++ b/saleor/app/migrations/0005_appextension.py
@@ -0,0 +1,68 @@
+# Generated by Django 3.2.5 on 2021-07-19 12:34
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("auth", "0012_alter_user_first_name_max_length"),
+ ("app", "0004_auto_20210308_1135"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="AppExtension",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("label", models.CharField(max_length=256)),
+ ("url", models.URLField()),
+ (
+ "view",
+ models.CharField(choices=[("product", "product")], max_length=128),
+ ),
+ (
+ "type",
+ models.CharField(
+ choices=[("overview", "overview"), ("details", "details")],
+ max_length=128,
+ ),
+ ),
+ (
+ "target",
+ models.CharField(
+ choices=[
+ ("more_actions", "more_actions"),
+ ("create", "create"),
+ ],
+ max_length=128,
+ ),
+ ),
+ (
+ "app",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="extensions",
+ to="app.app",
+ ),
+ ),
+ (
+ "permissions",
+ models.ManyToManyField(
+ blank=True,
+ help_text="Specific permissions for this app extension.",
+ to="auth.Permission",
+ ),
+ ),
+ ],
+ ),
+ ]
diff --git a/saleor/app/models.py b/saleor/app/models.py
index b104ff79ea..f96558dd3d 100644
--- a/saleor/app/models.py
+++ b/saleor/app/models.py
@@ -7,7 +7,7 @@ from oauthlib.common import generate_token
from ..core.models import Job, ModelWithMetadata
from ..core.permissions import AppPermission
from ..webhook.event_types import WebhookEventType
-from .types import AppType
+from .types import AppExtensionTarget, AppExtensionType, AppExtensionView, AppType
class AppQueryset(models.QuerySet):
@@ -103,6 +103,20 @@ class AppToken(models.Model):
auth_token = models.CharField(default=generate_token, unique=True, max_length=30)
+class AppExtension(models.Model):
+ app = models.ForeignKey(App, on_delete=models.CASCADE, related_name="extensions")
+ label = models.CharField(max_length=256)
+ url = models.URLField()
+ view = models.CharField(choices=AppExtensionView.CHOICES, max_length=128)
+ type = models.CharField(choices=AppExtensionType.CHOICES, max_length=128)
+ target = models.CharField(choices=AppExtensionTarget.CHOICES, max_length=128)
+ permissions = models.ManyToManyField(
+ Permission,
+ blank=True,
+ help_text="Specific permissions for this app extension.",
+ )
+
+
class AppInstallation(Job):
app_name = models.CharField(max_length=60)
manifest_url = models.URLField()
diff --git a/saleor/app/tasks.py b/saleor/app/tasks.py
index b7f72f08fe..3792971f34 100644
--- a/saleor/app/tasks.py
+++ b/saleor/app/tasks.py
@@ -1,3 +1,5 @@
+import logging
+
from django.core.exceptions import ValidationError
from requests import HTTPError, RequestException
@@ -6,6 +8,8 @@ from ..core import JobStatus
from .installation_utils import install_app
from .models import AppInstallation
+logger = logging.getLogger(__name__)
+
@celeryconf.app.task
def install_app_task(job_id, activate=False):
@@ -17,7 +21,8 @@ def install_app_task(job_id, activate=False):
except ValidationError as e:
msg = ", ".join([f"{name}: {err}" for name, err in e.message_dict.items()])
app_installation.message = msg
- except (RequestException, HTTPError):
+ except (RequestException, HTTPError) as e:
+ logger.warning("Failed to install an app. error: %s", e)
app_installation.message = (
"Failed to connect to app. Try later or contact with app support."
)
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
new file mode 100644
index 0000000000..8d40d4ace4
--- /dev/null
+++ b/saleor/app/tests/test_installation_utils.py
@@ -0,0 +1,224 @@
+from unittest.mock import Mock
+
+import pytest
+import requests
+from django.core.exceptions import ValidationError
+
+from ..installation_utils import install_app
+from ..models import App
+from ..types import AppExtensionTarget, AppExtensionType, AppExtensionView
+
+
+def test_install_app_created_app(
+ app_manifest, app_installation, monkeypatch, permission_manage_products
+):
+ # given
+ app_manifest["permissions"] = ["MANAGE_PRODUCTS"]
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
+
+ app_installation.permissions.set([permission_manage_products])
+
+ # when
+ app = install_app(app_installation, activate=True)
+
+ # then
+ assert App.objects.get().id == app.id
+ assert list(app.permissions.all()) == [permission_manage_products]
+
+
+def test_install_app_with_extension(
+ app_manifest,
+ app_installation,
+ monkeypatch,
+ permission_manage_products,
+ permission_manage_orders,
+):
+ # given
+ label = "Create product with app"
+ url = "http://127.0.0.1:8080/app-extension"
+ view = "PRODUCT"
+ type = "OVERVIEW"
+ target = "CREATE"
+ app_manifest["permissions"] = ["MANAGE_PRODUCTS", "MANAGE_ORDERS"]
+ app_manifest["extensions"] = [
+ {
+ "label": label,
+ "url": url,
+ "view": view,
+ "type": type,
+ "target": target,
+ "permissions": ["MANAGE_PRODUCTS"],
+ }
+ ]
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
+
+ app_installation.permissions.set(
+ [permission_manage_products, permission_manage_orders]
+ )
+
+ # when
+ app = install_app(app_installation, activate=True)
+
+ # then
+ assert App.objects.get().id == app.id
+ app_extension = app.extensions.get()
+
+ assert app_extension.label == label
+ assert app_extension.url == url
+ assert app_extension.view == AppExtensionView.PRODUCT
+ assert app_extension.type == AppExtensionType.OVERVIEW
+ assert app_extension.target == AppExtensionTarget.CREATE
+ assert list(app_extension.permissions.all()) == [permission_manage_products]
+
+
+ "app_permissions, extension_permissions",
+ [
+ ([], ["MANAGE_PRODUCTS"]),
+ (["MANAGE_PRODUCTS"], ["MANAGE_PRODUCTS", "MANAGE_APPS"]),
+ ],
+)
+def test_install_app_extension_permission_out_of_scope(
+ app_permissions, extension_permissions, app_manifest, app_installation, monkeypatch
+):
+ # given
+ label = "Create product with app"
+ url = "http://127.0.0.1:8080/app-extension"
+ view = "PRODUCT"
+ type = "OVERVIEW"
+ target = "CREATE"
+ app_manifest["permissions"] = app_permissions
+ app_manifest["extensions"] = [
+ {
+ "label": label,
+ "url": url,
+ "view": view,
+ "type": type,
+ "target": target,
+ "permissions": extension_permissions,
+ }
+ ]
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
+
+ # when & then
+ with pytest.raises(ValidationError):
+ install_app(app_installation, activate=True)
+
+
+ "url",
+ [
+ "http:/127.0.0.1:8080/app",
+ "127.0.0.1:8080/app",
+ "",
+ "/app",
+ "www.example.com/app",
+ ],
+)
+def test_install_app_extension_incorrect_url(
+ url, app_manifest, app_installation, monkeypatch
+):
+ # given
+ app_manifest["permissions"] = ["MANAGE_PRODUCTS"]
+ app_manifest["extensions"] = [
+ {
+ "url": url,
+ "label": "Create product with app",
+ "view": "PRODUCT",
+ "type": "OVERVIEW",
+ "target": "CREATE",
+ "permissions": ["MANAGE_PRODUCTS"],
+ }
+ ]
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
+
+ # when & then
+ with pytest.raises(ValidationError):
+ install_app(app_installation, activate=True)
+
+
+def test_install_app_extension_ivalid_permission(
+ app_manifest, app_installation, monkeypatch
+):
+ # given
+ label = "Create product with app"
+ url = "http://127.0.0.1:8080/app-extension"
+ view = "PRODUCT"
+ type = "OVERVIEW"
+ target = "CREATE"
+ app_manifest["permissions"] = ["MANAGE_PRODUCTS"]
+ app_manifest["extensions"] = [
+ {
+ "label": label,
+ "url": url,
+ "view": view,
+ "type": type,
+ "target": target,
+ "permissions": ["INVALID_PERM"],
+ }
+ ]
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
+
+ # when & then
+ with pytest.raises(ValidationError):
+ install_app(app_installation, activate=True)
+
+
+ "incorrect_field",
+ [
+ "view",
+ "type",
+ "target",
+ ],
+)
+def test_install_app_extension_incorrect_values(
+ incorrect_field, app_manifest, app_installation, monkeypatch
+):
+ # given
+ label = "Create product with app"
+ url = "http://127.0.0.1:8080/app-extension"
+ view = "PRODUCT"
+ type = "OVERVIEW"
+ target = "CREATE"
+ app_manifest["permissions"] = []
+ app_manifest["extensions"] = [
+ {
+ "label": label,
+ "url": url,
+ "view": view,
+ "type": type,
+ "target": target,
+ "permissions": ["MANAGE_PRODUCTS"],
+ }
+ ]
+ app_manifest["extensions"][0][incorrect_field] = "wrong-value"
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
+
+ # when & then
+ with pytest.raises(ValidationError):
+ install_app(app_installation, activate=True)
diff --git a/saleor/app/tests/test_manifest_validation.py b/saleor/app/tests/test_manifest_validation.py
new file mode 100644
index 0000000000..661f643959
--- /dev/null
+++ b/saleor/app/tests/test_manifest_validation.py
@@ -0,0 +1,51 @@
+from collections import defaultdict
+
+import pytest
+
+from ..manifest_validations import _validate_configuration
+from ..types import AppExtensionTarget, AppExtensionType, AppExtensionView
+
+
+ "view, type, target",
+ [
+ (
+ AppExtensionView.PRODUCT,
+ AppExtensionType.OVERVIEW,
+ AppExtensionTarget.CREATE,
+ ),
+ (
+ AppExtensionView.PRODUCT,
+ AppExtensionType.OVERVIEW,
+ AppExtensionTarget.MORE_ACTIONS,
+ ),
+ (AppExtensionView.PRODUCT, AppExtensionType.DETAILS, AppExtensionTarget.CREATE),
+ (
+ AppExtensionView.PRODUCT,
+ AppExtensionType.DETAILS,
+ AppExtensionTarget.MORE_ACTIONS,
+ ),
+ ],
+)
+def test_validate_configuration_accepts_correct_configuration(view, type, target):
+ errors = []
+ extension = {
+ "view": view,
+ "type": type,
+ "target": target,
+ }
+ _validate_configuration(extension, errors)
+
+ assert not errors
+
+
+def test_incorrect_configuration():
+ errors = defaultdict(list)
+ extension = {
+ "view": AppExtensionView.PRODUCT,
+ "type": AppExtensionType.DETAILS,
+ "target": "incorrect",
+ }
+ _validate_configuration(extension, errors)
+
+ assert len(errors["extensions"]) == 1
diff --git a/saleor/app/types.py b/saleor/app/types.py
index 732ba7af3f..7a4abf02ae 100644
--- a/saleor/app/types.py
+++ b/saleor/app/types.py
@@ -3,3 +3,40 @@ class AppType:
THIRDPARTY = "thirdparty"
CHOICES = [(LOCAL, "local"), (THIRDPARTY, "thirdparty")]
+
+
+class AppExtensionView:
+ """All available places where app's iframe can be mounted.
+
+ PRODUCT - app's iframe will be mounted in product section
+ """
+
+ PRODUCT = "product"
+
+ CHOICES = [(PRODUCT, "product")]
+
+
+class AppExtensionType:
+ """All available types where app's iframe can be mounted.
+
+ OVERVIEW - app's iframe will be mounted on list view.
+ DETAILS - app's iframe will be mounted on detail view
+ """
+
+ OVERVIEW = "overview"
+ DETAILS = "details"
+
+ CHOICES = [(OVERVIEW, "overview"), (DETAILS, "details")]
+
+
+class AppExtensionTarget:
+ """All available places where app's iframe can be mounted.
+
+ MORE_ACTIONS - more actions button
+ CREATE - create button
+ """
+
+ MORE_ACTIONS = "more_actions"
+ CREATE = "create"
+
+ CHOICES = [(MORE_ACTIONS, "more_actions"), (CREATE, "create")]
diff --git a/saleor/core/jwt.py b/saleor/core/jwt.py
index 2fd4ae9823..77e9c63f05 100644
--- a/saleor/core/jwt.py
+++ b/saleor/core/jwt.py
@@ -1,13 +1,14 @@
from datetime import datetime, timedelta
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Iterable, Optional
import graphene
import jwt
from django.conf import settings
+from django.contrib.auth.models import Permission
from django.core.handlers.wsgi import WSGIRequest
from ..account.models import User
-from ..app.models import App
+from ..app.models import App, AppExtension
from .permissions import (
get_permission_names,
get_permissions_from_codenames,
@@ -179,24 +180,22 @@ def get_user_from_access_payload(payload: dict) -> Optional[User]:
return user
-def create_access_token_for_app(app: "App", user: "User"):
- """Create access token for app.
-
- App can use user jwt token to proceed given operation on the Saleor side.
- The token which can be used by App has additional field defining the permissions
- assigned to it. The permissions set is the intersection of user permissions and
- app permissions.
- """
- app_permissions = app.permissions.all()
- app_permission_enums = get_permission_names(app_permissions)
+def _create_access_token_for_third_party_actions(
+ permissions: Iterable["Permission"],
+ user: "User",
+ type: str,
+ object_id: int,
+ object_payload_key: str,
+):
+ app_permission_enums = get_permission_names(permissions)
permissions = user.effective_permissions
user_permission_enums = get_permission_names(permissions)
- app_id = graphene.Node.to_global_id("App", app.id)
additional_payload = {
- "app": app_id,
+ object_payload_key: graphene.Node.to_global_id(type, object_id),
PERMISSIONS_FIELD: list(app_permission_enums & user_permission_enums),
}
+
payload = jwt_user_payload(
user,
JWT_THIRDPARTY_ACCESS_TYPE,
@@ -204,3 +203,33 @@ def create_access_token_for_app(app: "App", user: "User"):
additional_payload=additional_payload,
)
return jwt_encode(payload)
+
+
+def create_access_token_for_app(app: "App", user: "User"):
+ """Create access token for app.
+
+ App can use user's JWT token to proceed given operation in Saleor.
+ The token which can be used by App has additional field defining the permissions
+ assigned to it. The permissions set is the intersection of user permissions and
+ app permissions.
+ """
+ app_permissions = app.permissions.all()
+ return _create_access_token_for_third_party_actions(
+ permissions=app_permissions,
+ user=user,
+ type="App",
+ object_id=app.id,
+ object_payload_key="app",
+ )
+
+
+def create_access_token_for_app_extension(
+ app_extension: "AppExtension", permissions: Iterable["Permission"], user: "User"
+):
+ return _create_access_token_for_third_party_actions(
+ permissions=permissions,
+ user=user,
+ type="AppExtension",
+ object_id=app_extension.id,
+ object_payload_key="app_extension",
+ )
diff --git a/saleor/core/tests/test_jwt.py b/saleor/core/tests/test_jwt.py
new file mode 100644
index 0000000000..277bbfe47e
--- /dev/null
+++ b/saleor/core/tests/test_jwt.py
@@ -0,0 +1,65 @@
+import graphene
+
+from ..jwt import create_access_token_for_app_extension, jwt_decode
+
+
+def test_create_access_token_for_app_extension_staff_user_with_more_permissions(
+ app_with_extensions,
+ staff_user,
+ permission_manage_apps,
+ permission_manage_products,
+ permission_manage_channels,
+):
+ # given
+ staff_user.user_permissions.set(
+ [permission_manage_channels, permission_manage_apps, permission_manage_products]
+ )
+ app, extensions = app_with_extensions
+ extension = extensions[0]
+ extension.permissions.set([permission_manage_products])
+
+ # when
+ access_token = create_access_token_for_app_extension(
+ app_extension=extension,
+ permissions=extension.permissions.all(),
+ user=staff_user,
+ )
+
+ # then
+ decoded_token = jwt_decode(access_token, verify_expiration=False)
+ assert decoded_token["permissions"] == ["MANAGE_PRODUCTS"]
+ _, decode_extension_id = graphene.Node.from_global_id(
+ decoded_token["app_extension"]
+ )
+ assert int(decode_extension_id) == extension.id
+
+
+def test_create_access_token_for_app_extension_with_more_permissions(
+ app_with_extensions,
+ staff_user,
+ permission_manage_apps,
+ permission_manage_products,
+ permission_manage_channels,
+):
+ # given
+ staff_user.user_permissions.set([permission_manage_products])
+ app, extensions = app_with_extensions
+ extension = extensions[0]
+ extension.permissions.set(
+ [permission_manage_channels, permission_manage_apps, permission_manage_products]
+ )
+
+ # when
+ access_token = create_access_token_for_app_extension(
+ app_extension=extension,
+ permissions=extension.permissions.all(),
+ user=staff_user,
+ )
+
+ # then
+ decoded_token = jwt_decode(access_token, verify_expiration=False)
+ assert decoded_token["permissions"] == ["MANAGE_PRODUCTS"]
+ _, decode_extension_id = graphene.Node.from_global_id(
+ decoded_token["app_extension"]
+ )
+ assert int(decode_extension_id) == extension.id
diff --git a/saleor/graphql/app/dataloaders.py b/saleor/graphql/app/dataloaders.py
index 79ac12f45d..7f958b75bd 100644
--- a/saleor/graphql/app/dataloaders.py
+++ b/saleor/graphql/app/dataloaders.py
@@ -1,4 +1,6 @@
-from ...app.models import App
+from collections import defaultdict
+
+from ...app.models import App, AppExtension
from ..core.dataloaders import DataLoader
@@ -7,4 +9,25 @@ class AppByIdLoader(DataLoader):
def batch_load(self, keys):
apps = App.objects.in_bulk(keys)
- return [apps.get(app_id) for app_id in keys]
+ return [apps.get(key) for key in keys]
+
+
+class AppExtensionByIdLoader(DataLoader):
+ context_key = "app_extension_by_id"
+
+ def batch_load(self, keys):
+ extensions = AppExtension.objects.in_bulk(keys)
+ return [extensions.get(key) for key in keys]
+
+
+class AppExtensionByAppIdLoader(DataLoader):
+ context_key = "app_extension_by_app_id"
+
+ def batch_load(self, keys):
+ extensions = AppExtension.objects.filter(app_id__in=keys)
+ extensions_map = defaultdict(list)
+ app_extension_loader = AppExtensionByIdLoader(self.context)
+ for extension in extensions.iterator():
+ extensions_map[extension.app_id].append(extension)
+ app_extension_loader.prime(extension.id, extension)
+ return [extensions_map.get(app_id, []) for app_id in keys]
diff --git a/saleor/graphql/app/enums.py b/saleor/graphql/app/enums.py
index 299b2fca76..819d43cbc3 100644
--- a/saleor/graphql/app/enums.py
+++ b/saleor/graphql/app/enums.py
@@ -1,4 +1,4 @@
-from ...app.types import AppType
+from ...app.types import AppExtensionTarget, AppExtensionType, AppExtensionView, AppType
from ..core.enums import to_enum
@@ -20,3 +20,9 @@ def description(enum):
AppTypeEnum = to_enum(AppType, description=description)
+
+AppExtensionTypeEnum = to_enum(AppExtensionType, description=AppExtensionType.__doc__)
+AppExtensionViewEnum = to_enum(AppExtensionView, description=AppExtensionView.__doc__)
+AppExtensionTargetEnum = to_enum(
+ AppExtensionTarget, description=AppExtensionTarget.__doc__
+)
diff --git a/saleor/graphql/app/filters.py b/saleor/graphql/app/filters.py
index b2863be6e6..1d876e2575 100644
--- a/saleor/graphql/app/filters.py
+++ b/saleor/graphql/app/filters.py
@@ -1,10 +1,15 @@
import django_filters
from ...app import models
-from ...app.types import AppType
+from ...app.types import AppExtensionTarget, AppExtensionType, AppExtensionView, AppType
from ..core.filters import EnumFilter
from ..utils.filters import filter_by_query_param
-from .enums import AppTypeEnum
+from .enums import (
+ AppExtensionTargetEnum,
+ AppExtensionTypeEnum,
+ AppExtensionViewEnum,
+ AppTypeEnum,
+)
def filter_app_search(qs, _, value):
@@ -13,17 +18,55 @@ def filter_app_search(qs, _, value):
return qs
-def filter_type(qs, _, value):
+def filter_app_type(qs, _, value):
if value in [AppType.LOCAL, AppType.THIRDPARTY]:
qs = qs.filter(type=value)
return qs
+def filter_app_extension_view(qs, _, value):
+ if value in [view for view, _ in AppExtensionView.CHOICES]:
+ qs = qs.filter(view=value)
+ return qs
+
+
+def filter_app_extension_type(qs, _, value):
+ if value in [type for type, _ in AppExtensionType.CHOICES]:
+ qs = qs.filter(type=value)
+ return qs
+
+
+def filter_app_extension_target(qs, _, value):
+ if value in [target for target, _ in AppExtensionTarget.CHOICES]:
+ qs = qs.filter(target=value)
+ return qs
+
+
class AppFilter(django_filters.FilterSet):
- type = EnumFilter(input_class=AppTypeEnum, method=filter_type)
+ type = EnumFilter(input_class=AppTypeEnum, method=filter_app_type)
search = django_filters.CharFilter(method=filter_app_search)
is_active = django_filters.BooleanFilter()
class Meta:
model = models.App
fields = ["search", "is_active"]
+
+
+class AppExtensionFilter(django_filters.FilterSet):
+ view = EnumFilter(
+ input_class=AppExtensionViewEnum, method=filter_app_extension_view
+ )
+ type = EnumFilter(
+ input_class=AppExtensionTypeEnum, method=filter_app_extension_type
+ )
+ target = EnumFilter(
+ input_class=AppExtensionTargetEnum, method=filter_app_extension_target
+ )
+
+ class Meta:
+ model = models.AppExtension
+ fields = [
+ "view",
+ "type",
+ "target",
+ ]
diff --git a/saleor/graphql/app/mutations.py b/saleor/graphql/app/mutations.py
index 6507f18b14..6c2758cb7c 100644
--- a/saleor/graphql/app/mutations.py
+++ b/saleor/graphql/app/mutations.py
@@ -1,4 +1,4 @@
-from typing import List
+from typing import Dict, List
import graphene
import requests
@@ -7,26 +7,21 @@ from django.core.exceptions import ValidationError
from ...app import models
from ...app.error_codes import AppErrorCode
from ...app.installation_utils import REQUEST_TIMEOUT
+from ...app.manifest_validations import clean_manifest_data, clean_manifest_url
from ...app.tasks import install_app_task
-from ...app.validators import AppURLValidator
from ...core import JobStatus
-from ...core.permissions import (
- AppPermission,
- get_permissions,
- get_permissions_enum_list,
-)
+from ...core.permissions import AppPermission, get_permissions
from ..account.utils import can_manage_app
+from ..core import types as grapqhl_types
from ..core.enums import PermissionEnum
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types.common import AppError
-from ..utils import (
- format_permissions_for_display,
- get_user_or_app_from_context,
- requestor_is_superuser,
-)
+from ..utils import get_user_or_app_from_context, requestor_is_superuser
from .types import App, AppToken, Manifest
from .utils import ensure_can_manage_permissions
+T_ERRORS = Dict[str, List[ValidationError]]
+
class AppInput(graphene.InputObjectType):
name = graphene.String(description="Name of the app.")
@@ -371,20 +366,10 @@ class AppInstall(ModelMutation):
error_type_class = AppError
error_type_field = "app_errors"
- @classmethod
- def clean_manifest_url(self, url):
- url_validator = AppURLValidator()
- try:
- url_validator(url)
- except (ValidationError, AttributeError):
- msg = "Enter a valid URL."
- code = AppErrorCode.INVALID_URL_FORMAT.value
- raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
-
@classmethod
def clean_input(cls, info, instance, data, input_cls=None):
manifest_url = data.get("manifest_url")
- cls.clean_manifest_url(manifest_url)
+ clean_manifest_url(manifest_url)
cleaned_input = super().clean_input(info, instance, data, input_cls)
@@ -442,16 +427,6 @@ class AppFetchManifest(BaseMutation):
code = AppErrorCode.INVALID.value
raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
- @classmethod
- def clean_manifest_url(cls, manifest_url):
- url_validator = AppURLValidator()
- try:
- url_validator(manifest_url)
- except (ValidationError, AttributeError):
- msg = "Enter a valid URL."
- code = AppErrorCode.INVALID_URL_FORMAT.value
- raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
-
@classmethod
def construct_instance(cls, instance, cleaned_data):
return Manifest(
@@ -467,35 +442,34 @@ class AppFetchManifest(BaseMutation):
version=cleaned_data.get("version"),
token_target_url=cleaned_data.get("tokenTargetUrl"),
permissions=cleaned_data.get("permissions"),
+ extensions=cleaned_data.get("extensions", []),
)
@classmethod
- def clean_permissions(cls, required_permissions: List[str]):
- missing_permissions = []
- all_permissions = {perm[0]: perm[1] for perm in get_permissions_enum_list()}
- for perm in required_permissions:
- if not all_permissions.get(perm):
- missing_permissions.append(perm)
- if missing_permissions:
- error_msg = "Given permissions don't exist"
- code = AppErrorCode.INVALID_PERMISSION.value
- params = {"permissions": missing_permissions}
- raise ValidationError(
- {"permissions": ValidationError(error_msg, code=code, params=params)}
- )
+ def clean_manifest_data(cls, info, manifest_data):
+ clean_manifest_data(manifest_data)
- permissions = get_permissions(
- [all_permissions[perm] for perm in required_permissions]
- )
- return format_permissions_for_display(permissions)
+ manifest_data["permissions"] = [
+ grapqhl_types.Permission(
+ code=PermissionEnum.get(p.formated_codename), name=p.name
+ )
+ for p in manifest_data["permissions"]
+ ]
+ for extension in manifest_data.get("extensions", []):
+ extension["permissions"] = [
+ grapqhl_types.Permission(
+ code=PermissionEnum.get(p.formated_codename),
+ name=p.name,
+ )
+ for p in extension["permissions"]
+ ]
@classmethod
def perform_mutation(cls, root, info, **data):
manifest_url = data.get("manifest_url")
- cls.clean_manifest_url(manifest_url)
+ clean_manifest_url(manifest_url)
manifest_data = cls.fetch_manifest(manifest_url)
- manifest_data["permissions"] = cls.clean_permissions(
- manifest_data.get("permissions")
- )
+ cls.clean_manifest_data(info, manifest_data)
+
instance = cls.construct_instance(instance=None, cleaned_data=manifest_data)
return cls.success_response(instance)
diff --git a/saleor/graphql/app/resolvers.py b/saleor/graphql/app/resolvers.py
index 576d657a00..9d3f9e379b 100644
--- a/saleor/graphql/app/resolvers.py
+++ b/saleor/graphql/app/resolvers.py
@@ -1,6 +1,10 @@
from ...app import models
-from ...core.jwt import create_access_token_for_app
+from ...core.jwt import (
+ create_access_token_for_app,
+ create_access_token_for_app_extension,
+)
from ...core.permissions import AppPermission
+from ...core.utils.validators import user_is_valid
from ..core.utils import from_global_id_or_error
from ..decorators import permission_required
from .enums import AppTypeEnum
@@ -14,7 +18,7 @@ def resolve_apps(info, **_kwargs):
return models.App.objects.all()
-def resolve_access_token(info, root, **_kwargs):
+def resolve_access_token_for_app(info, root, **_kwargs):
if root.type != AppTypeEnum.THIRDPARTY.value:
return None
@@ -24,9 +28,26 @@ def resolve_access_token(info, root, **_kwargs):
return create_access_token_for_app(root, user)
+def resolve_access_token_for_app_extension(info, root, **_kwargs):
+ user = info.context.user
+ if not user_is_valid(user):
+ return None
+ extension_permissions = root.permissions.all()
+ user_permissions = user.effective_permissions
+ if set(extension_permissions).issubset(user_permissions):
+ return create_access_token_for_app_extension(
+ app_extension=root, permissions=extension_permissions, user=user
+ )
+ return None
+
+
@permission_required(AppPermission.MANAGE_APPS)
def resolve_app(_info, id):
if not id:
return None
_, id = from_global_id_or_error(id, "App")
return models.App.objects.filter(id=id).first()
+
+
+def resolve_app_extensions(_info):
+ return models.AppExtension.objects.filter(app__is_active=True)
diff --git a/saleor/graphql/app/schema.py b/saleor/graphql/app/schema.py
index 3696cbe225..4baa660ecf 100644
--- a/saleor/graphql/app/schema.py
+++ b/saleor/graphql/app/schema.py
@@ -3,8 +3,10 @@ import graphene
from ...core.permissions import AppPermission
from ..core.fields import FilterInputConnectionField
from ..core.types import FilterInputObjectType
-from ..decorators import permission_required
-from .filters import AppFilter
+from ..core.utils import from_global_id_or_error
+from ..decorators import permission_required, staff_member_or_app_required
+from .dataloaders import AppByIdLoader, AppExtensionByIdLoader
+from .filters import AppExtensionFilter, AppFilter
from .mutations import (
AppActivate,
AppCreate,
@@ -19,9 +21,14 @@ from .mutations import (
AppTokenVerify,
AppUpdate,
)
-from .resolvers import resolve_app, resolve_apps, resolve_apps_installations
+from .resolvers import (
+ resolve_app,
+ resolve_app_extensions,
+ resolve_apps,
+ resolve_apps_installations,
+)
from .sorters import AppSortingInput
-from .types import App, AppInstallation
+from .types import App, AppExtension, AppInstallation
class AppFilterInput(FilterInputObjectType):
@@ -29,6 +36,11 @@ class AppFilterInput(FilterInputObjectType):
filterset_class = AppFilter
+class AppExtensionFilterInput(FilterInputObjectType):
+ class Meta:
+ filterset_class = AppExtensionFilter
+
+
class AppQueries(graphene.ObjectType):
apps_installations = graphene.List(
graphene.NonNull(AppInstallation),
@@ -50,6 +62,21 @@ class AppQueries(graphene.ObjectType):
),
)
+ app_extensions = FilterInputConnectionField(
+ AppExtension,
+ filter=AppExtensionFilterInput(
+ description="Filtering options for apps extensions."
+ ),
+ description="List of all extensions",
+ )
+ app_extension = graphene.Field(
+ AppExtension,
+ id=graphene.Argument(
+ graphene.ID, description="ID of the app extension.", required=True
+ ),
+ description="Look up an app extension by ID.",
+ )
+
@permission_required(AppPermission.MANAGE_APPS)
def resolve_apps_installations(self, info, **kwargs):
return resolve_apps_installations(info, **kwargs)
@@ -64,6 +91,28 @@ class AppQueries(graphene.ObjectType):
return app
return resolve_app(info, id)
+ @staff_member_or_app_required
+ def resolve_app_extensions(self, info, **kwargs):
+ return resolve_app_extensions(info)
+
+ @staff_member_or_app_required
+ def resolve_app_extension(self, info, id):
+ def app_is_active(app_extension):
+ def is_active(app):
+ if app.is_active:
+ return app_extension
+ return None
+
+ if not app_extension:
+ return None
+
+ return (
+ AppByIdLoader(info.context).load(app_extension.app_id).then(is_active)
+ )
+
+ _, id = from_global_id_or_error(id, "AppExtension")
+ return AppExtensionByIdLoader(info.context).load(int(id)).then(app_is_active)
+
class AppMutations(graphene.ObjectType):
app_create = AppCreate.Field()
diff --git a/saleor/graphql/app/tests/benchmarks/__init__.py b/saleor/graphql/app/tests/benchmarks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/app/tests/benchmarks/test_app_extensions.py b/saleor/graphql/app/tests/benchmarks/test_app_extensions.py
new file mode 100644
index 0000000000..15b9b2e7d2
--- /dev/null
+++ b/saleor/graphql/app/tests/benchmarks/test_app_extensions.py
@@ -0,0 +1,172 @@
+import pytest
+
+from .....app.models import AppExtension
+from .....app.types import AppExtensionTarget, AppExtensionType, AppExtensionView
+from ....tests.utils import get_graphql_content
+from ...enums import AppExtensionTargetEnum, AppExtensionTypeEnum, AppExtensionViewEnum
+
+
[email protected]_queries(autouse=False)
+def test_app_extensions(
+ staff_api_client,
+ app,
+ permission_manage_products,
+ count_queries,
+):
+ # given
+ query = """
+ query{
+ appExtensions(first: 10){
+ edges{
+ node{
+ label
+ url
+ view
+ target
+ id
+ type
+ accessToken
+ permissions{
+ code
+ }
+ }
+ }
+ }
+ }
+ """
+
+ app_extensions = AppExtension.objects.bulk_create(
+ [
+ AppExtension(
+ app=app,
+ label="Create product with App1",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ ),
+ AppExtension(
+ app=app,
+ label="Create product with App2",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.DETAILS,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ ),
+ AppExtension(
+ app=app,
+ label="Create product with App3",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.CREATE,
+ ),
+ ]
+ )
+ app_extensions[0].permissions.add(permission_manage_products)
+ app_extensions[1].permissions.add(permission_manage_products)
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_products], check_no_permissions=False
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ extensions_data = content["data"]["appExtensions"]["edges"]
+
+ assert len(extensions_data) == 3
+
+
+ "filter",
+ [
+ {},
+ {"view": AppExtensionViewEnum.PRODUCT.name},
+ {"target": AppExtensionTargetEnum.CREATE.name},
+ {"type": AppExtensionTypeEnum.OVERVIEW.name},
+ {
+ "type": AppExtensionTypeEnum.OVERVIEW.name,
+ "view": AppExtensionViewEnum.PRODUCT.name,
+ },
+ {
+ "type": AppExtensionTypeEnum.DETAILS.name,
+ "target": AppExtensionTargetEnum.CREATE.name,
+ },
+ {
+ "type": AppExtensionTypeEnum.DETAILS.name,
+ "target": AppExtensionTargetEnum.MORE_ACTIONS.name,
+ },
+ ],
+)
[email protected]_queries(autouse=False)
+def test_app_extensions_with_filter(
+ filter,
+ staff_api_client,
+ app,
+ permission_manage_products,
+ count_queries,
+):
+ # given
+ query = """
+ query ($filter: AppExtensionFilterInput){
+ appExtensions(first: 10, filter: $filter){
+ edges{
+ node{
+ label
+ url
+ view
+ target
+ id
+ type
+ accessToken
+ permissions{
+ code
+ }
+ }
+ }
+ }
+ }
+ """
+ app_extensions = AppExtension.objects.bulk_create(
+ [
+ AppExtension(
+ app=app,
+ label="Create product with App1",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ ),
+ AppExtension(
+ app=app,
+ label="Create product with App2",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.DETAILS,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ ),
+ AppExtension(
+ app=app,
+ label="Create product with App3",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.CREATE,
+ ),
+ ]
+ )
+ app_extensions[0].permissions.add(permission_manage_products)
+ variables = {"filter": filter}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ get_graphql_content(response)
diff --git a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
index 190477dfc5..eafb2774d8 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -4,6 +4,7 @@ import pytest
import requests
from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import AppExtensionTargetEnum, AppExtensionTypeEnum, AppExtensionViewEnum
APP_FETCH_MANIFEST_MUTATION = """
mutation AppFetchManifest($manifest_url: String!){
@@ -23,6 +24,17 @@ mutation AppFetchManifest($manifest_url: String!){
permissions{
code
}
+ extensions{
+ label
+ url
+ view
+ type
+ target
+ permissions{
+ code
+ name
+ }
+ }
}
errors{
field
@@ -100,7 +112,7 @@ def test_app_fetch_manifest_incorrect_permission_in_manifest(
assert len(errors) == 1
assert errors[0] == {
"field": "permissions",
- "message": "Given permissions don't exist",
+ "message": "Given permissions don't exist.",
"code": "INVALID_PERMISSION",
}
assert not manifest
@@ -209,3 +221,361 @@ def test_app_fetch_manifest_handle_exception(
"field": "manifestUrl",
"message": "Can't fetch manifest data. Please try later.",
}
+
+
+ "missing_field",
+ [
+ "id",
+ "version",
+ "name",
+ ],
+)
+def test_app_fetch_manifest_missing_fields(
+ missing_field, app_manifest, monkeypatch, staff_api_client, permission_manage_apps
+):
+ # given
+ del app_manifest[missing_field]
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ query = APP_FETCH_MANIFEST_MUTATION
+ manifest_url = "http://localhost:3000/configuration/manifest"
+ variables = {
+ "manifest_url": manifest_url,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0] == {
+ "code": "REQUIRED",
+ "field": missing_field,
+ "message": "Field required.",
+ }
+
+
+ "missing_field",
+ [
+ "label",
+ "url",
+ "view",
+ "type",
+ "target",
+ ],
+)
+def test_app_fetch_manifest_missing_extension_fields(
+ missing_field, app_manifest, monkeypatch, staff_api_client, permission_manage_apps
+):
+ # given
+ app_manifest["extensions"] = [
+ {
+ "permissions": ["MANAGE_PRODUCTS"],
+ "label": "Create product with App",
+ "url": "http://127.0.0.1:9090/app-extension",
+ "view": AppExtensionViewEnum.PRODUCT.name,
+ "type": AppExtensionTypeEnum.OVERVIEW.name,
+ "target": AppExtensionTargetEnum.CREATE.name,
+ }
+ ]
+ del app_manifest["extensions"][0][missing_field]
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ query = APP_FETCH_MANIFEST_MUTATION
+ manifest_url = "http://localhost:3000/configuration/manifest"
+ variables = {
+ "manifest_url": manifest_url,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0] == {
+ "code": "REQUIRED",
+ "field": "extensions",
+ "message": f"Missing required fields for app extension: {missing_field}.",
+ }
+
+
+ "incorrect_field",
+ [
+ "view",
+ "type",
+ "target",
+ ],
+)
+def test_app_fetch_manifest_extensions_incorrect_enum_values(
+ incorrect_field, app_manifest, monkeypatch, staff_api_client, permission_manage_apps
+):
+ # given
+ app_manifest["extensions"] = [
+ {
+ "permissions": ["MANAGE_PRODUCTS"],
+ "label": "Create product with App",
+ "url": "http://127.0.0.1:9090/app-extension",
+ "view": AppExtensionViewEnum.PRODUCT.name,
+ "type": AppExtensionTypeEnum.OVERVIEW.name,
+ "target": AppExtensionTargetEnum.CREATE.name,
+ }
+ ]
+ app_manifest["extensions"][0][incorrect_field] = "INCORRECT_VALUE"
+
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ query = APP_FETCH_MANIFEST_MUTATION
+ manifest_url = "http://localhost:3000/configuration/manifest"
+ variables = {
+ "manifest_url": manifest_url,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+
+ assert len(errors) == 2
+ expected_errors = [
+ {
+ "code": "INVALID",
+ "field": "extensions",
+ "message": f"Incorrect value for field: {incorrect_field}",
+ },
+ {
+ "field": "extensions",
+ "message": (
+ "Incorrect configuration of app extension for fields: view, type and "
+ "target."
+ ),
+ "code": "INVALID",
+ },
+ ]
+
+ assert errors[0] in expected_errors
+ assert errors[1] in expected_errors
+
+
+ "url",
+ [
+ "http:/127.0.0.1:8080/app",
+ "127.0.0.1:8080/app",
+ "",
+ "/app",
+ "www.example.com/app",
+ ],
+)
+def test_app_fetch_manifest_extensions_incorrect_url(
+ url, app_manifest, monkeypatch, staff_api_client, permission_manage_apps
+):
+ # given
+ app_manifest["extensions"] = [
+ {
+ "permissions": ["MANAGE_PRODUCTS"],
+ "label": "Create product with App",
+ "url": url,
+ "view": AppExtensionViewEnum.PRODUCT.name,
+ "type": AppExtensionTypeEnum.OVERVIEW.name,
+ "target": AppExtensionTargetEnum.CREATE.name,
+ }
+ ]
+
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ query = APP_FETCH_MANIFEST_MUTATION
+ manifest_url = "http://localhost:3000/configuration/manifest"
+ variables = {
+ "manifest_url": manifest_url,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0] == {
+ "code": "INVALID_URL_FORMAT",
+ "field": "extensions",
+ "message": "Incorrect value for field: url.",
+ }
+
+
+ "app_permissions, extension_permissions",
+ [
+ ([], ["MANAGE_PRODUCTS"]),
+ (["MANAGE_PRODUCTS"], ["MANAGE_PRODUCTS", "MANAGE_APPS"]),
+ ],
+)
+def test_app_fetch_manifest_extensions_permission_out_of_scope(
+ app_permissions,
+ extension_permissions,
+ app_manifest,
+ monkeypatch,
+ staff_api_client,
+ permission_manage_apps,
+):
+ # given
+ app_manifest["permissions"] = app_permissions
+ app_manifest["extensions"] = [
+ {
+ "permissions": extension_permissions,
+ "label": "Create product with App",
+ "url": "http://127.0.0.1:8080/app",
+ "view": AppExtensionViewEnum.PRODUCT.name,
+ "type": AppExtensionTypeEnum.OVERVIEW.name,
+ "target": AppExtensionTargetEnum.CREATE.name,
+ }
+ ]
+
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ query = APP_FETCH_MANIFEST_MUTATION
+ manifest_url = "http://localhost:3000/configuration/manifest"
+ variables = {
+ "manifest_url": manifest_url,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0] == {
+ "code": "OUT_OF_SCOPE_PERMISSION",
+ "field": "extensions",
+ "message": "Extension permission must be listed in App's permissions.",
+ }
+
+
+def test_app_fetch_manifest_extensions_invalid_permission(
+ app_manifest, monkeypatch, staff_api_client, permission_manage_apps
+):
+ # given
+ app_manifest["permissions"] = ["MANAGE_ORDERS"]
+ app_manifest["extensions"] = [
+ {
+ "permissions": ["incorrect_permission"],
+ "label": "Create product with App",
+ "url": "http://127.0.0.1:8080/app",
+ "view": AppExtensionViewEnum.PRODUCT.name,
+ "type": AppExtensionTypeEnum.OVERVIEW.name,
+ "target": AppExtensionTargetEnum.CREATE.name,
+ }
+ ]
+
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ query = APP_FETCH_MANIFEST_MUTATION
+ manifest_url = "http://localhost:3000/configuration/manifest"
+ variables = {
+ "manifest_url": manifest_url,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0] == {
+ "code": "INVALID_PERMISSION",
+ "field": "extensions",
+ "message": "Given permissions don't exist.",
+ }
+
+
+def test_app_fetch_manifest_with_extensions(
+ staff_api_client, staff_user, app_manifest, permission_manage_apps, monkeypatch
+):
+ # given
+ manifest_url = "http://localhost:3000/manifest"
+
+ app_manifest["extensions"] = [
+ {
+ "permissions": ["MANAGE_PRODUCTS"],
+ "label": "Create product with App",
+ "url": "http://127.0.0.1:8080/app",
+ "view": AppExtensionViewEnum.PRODUCT.name,
+ "type": AppExtensionTypeEnum.OVERVIEW.name,
+ "target": AppExtensionTargetEnum.CREATE.name,
+ }
+ ]
+
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+
+ query = APP_FETCH_MANIFEST_MUTATION
+ variables = {
+ "manifest_url": manifest_url,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+ manifest = content["data"]["appFetchManifest"]["manifest"]
+ extensions = manifest["extensions"]
+
+ assert not errors
+ assert len(extensions) == 1
+
+ extension = extensions[0]
+ assert extension["permissions"] == [
+ {"code": "MANAGE_PRODUCTS", "name": "Manage products."}
+ ]
+ assert extension["label"] == "Create product with App"
+ assert extension["url"] == "http://127.0.0.1:8080/app"
+ assert extension["view"] == AppExtensionViewEnum.PRODUCT.name
+ assert extension["type"] == AppExtensionTypeEnum.OVERVIEW.name
+ assert extension["target"] == AppExtensionTargetEnum.CREATE.name
diff --git a/saleor/graphql/app/tests/queries/test_app.py b/saleor/graphql/app/tests/queries/test_app.py
index f4841265f2..b4273078d5 100644
--- a/saleor/graphql/app/tests/queries/test_app.py
+++ b/saleor/graphql/app/tests/queries/test_app.py
@@ -30,6 +30,17 @@ QUERY_APP = """
configurationUrl
appUrl
accessToken
+ extensions{
+ id
+ label
+ url
+ view
+ type
+ target
+ permissions{
+ code
+ }
+ }
}
}
"""
@@ -222,3 +233,40 @@ def test_app_query_with_permission(
assert app_data["supportUrl"] == app.support_url
assert app_data["configurationUrl"] == app.configuration_url
assert app_data["appUrl"] == app.app_url
+
+
+def test_app_with_extensions_query(
+ staff_api_client,
+ permission_manage_apps,
+ permission_manage_orders,
+ app_with_extensions,
+):
+ app, app_extensions = app_with_extensions
+ id = graphene.Node.to_global_id("App", app.id)
+ variables = {"id": id}
+ response = staff_api_client.post_graphql(
+ QUERY_APP,
+ variables=variables,
+ permissions=[permission_manage_apps, permission_manage_orders],
+ )
+ content = get_graphql_content(response)
+ app_data = content["data"]["app"]
+ extensions_data = app_data["extensions"]
+ returned_ids = {e["id"] for e in extensions_data}
+ returned_labels = {e["label"] for e in extensions_data}
+ returned_urls = {e["url"] for e in extensions_data}
+ returned_views = {e["view"].lower() for e in extensions_data}
+ returned_types = {e["type"].lower() for e in extensions_data}
+ returned_targets = {e["target"].lower() for e in extensions_data}
+ returned_permission_codes = [e["permissions"] for e in extensions_data]
+ for app_extension in app_extensions:
+ global_id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ assert global_id in returned_ids
+ assert app_extension.label in returned_labels
+ assert app_extension.url in returned_urls
+ assert app_extension.view in returned_views
+ assert app_extension.type in returned_types
+ assert app_extension.target in returned_targets
+ assigned_permissions = [p.codename for p in app_extension.permissions.all()]
+ assigned_permissions = [{"code": p.upper()} for p in assigned_permissions]
+ assert assigned_permissions in returned_permission_codes
diff --git a/saleor/graphql/app/tests/queries/test_app_extension.py b/saleor/graphql/app/tests/queries/test_app_extension.py
new file mode 100644
index 0000000000..24382e71f9
--- /dev/null
+++ b/saleor/graphql/app/tests/queries/test_app_extension.py
@@ -0,0 +1,379 @@
+import graphene
+
+from .....app.models import AppExtension
+from .....app.types import AppExtensionTarget, AppExtensionType, AppExtensionView
+from .....core.jwt import jwt_decode
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+QUERY_APP_EXTENSION = """
+query ($id: ID!){
+ appExtension(id: $id){
+ label
+ url
+ view
+ target
+ type
+ id
+ accessToken
+ permissions{
+ code
+ }
+ }
+}
+"""
+
+
+def test_app_extension_staff_user(app, staff_api_client, permission_manage_products):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ extension_data = content["data"]["appExtension"]
+ assert app_extension.label == extension_data["label"]
+ assert app_extension.url == extension_data["url"]
+ assert app_extension.view == extension_data["view"].lower()
+ assert app_extension.target == extension_data["target"].lower()
+ assert app_extension.type == extension_data["type"].lower()
+
+ assert app_extension.permissions.count() == 1
+ assert len(extension_data["permissions"]) == 1
+ permission_code = extension_data["permissions"][0]["code"].lower()
+ assert app_extension.permissions.first().codename == permission_code
+
+
+def test_app_extension_by_app(app, app_api_client, permission_manage_products):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_APP_EXTENSION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ extension_data = content["data"]["appExtension"]
+ assert app_extension.label == extension_data["label"]
+ assert app_extension.url == extension_data["url"]
+ assert app_extension.view == extension_data["view"].lower()
+ assert app_extension.target == extension_data["target"].lower()
+ assert app_extension.type == extension_data["type"].lower()
+
+ assert app_extension.permissions.count() == 1
+ assert len(extension_data["permissions"]) == 1
+ permission_code = extension_data["permissions"][0]["code"].lower()
+ assert app_extension.permissions.first().codename == permission_code
+
+
+def test_app_extension_normal_user(app, user_api_client, permission_manage_products):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_APP_EXTENSION,
+ variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_app_extension_staff_user_without_all_permissions(
+ app, staff_api_client, permission_manage_products, permission_manage_orders
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSION,
+ variables,
+ permissions=[permission_manage_orders],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ extension_data = content["data"]["appExtension"]
+ assert extension_data["accessToken"] is None
+
+
+def test_app_extension_staff_user_fetching_access_token(
+ app,
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_products,
+ permission_manage_apps,
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products, permission_manage_orders)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSION,
+ variables,
+ permissions=[
+ permission_manage_orders,
+ permission_manage_products,
+ permission_manage_apps,
+ ],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ extension_data = content["data"]["appExtension"]
+
+ assert extension_data["accessToken"]
+ decoded_token = jwt_decode(extension_data["accessToken"])
+ assert set(decoded_token["permissions"]) == set(
+ ["MANAGE_PRODUCTS", "MANAGE_ORDERS"]
+ )
+
+
+def test_app_extension_staff_user_partial_permission(
+ app,
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_products,
+ permission_manage_apps,
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products, permission_manage_orders)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSION,
+ variables,
+ permissions=[permission_manage_orders, permission_manage_apps],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ extension_data = content["data"]["appExtension"]
+
+ assert extension_data["accessToken"] is None
+
+
+QUERY_APP_EXTENSION_WITH_APP = """
+query ($id: ID!){
+ appExtension(id: $id){
+ label
+ url
+ view
+ target
+ type
+ id
+ permissions{
+ code
+ }
+ app{
+ id
+ }
+ }
+}
+"""
+
+
+def test_app_extension_with_app_query_by_staff_without_permissions(
+ app, staff_api_client, permission_manage_products
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSION_WITH_APP,
+ variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_app_extension_with_app_query_by_app_without_permissions(
+ external_app, app_api_client, permission_manage_products
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=external_app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_APP_EXTENSION_WITH_APP,
+ variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_app_extension_with_app_query_by_app_with_permissions(
+ external_app,
+ app,
+ permission_manage_apps,
+ app_api_client,
+ permission_manage_products,
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=external_app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ app.permissions.add(permission_manage_apps)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_APP_EXTENSION_WITH_APP,
+ variables,
+ )
+
+ # then
+ get_graphql_content(response)
+
+
+def test_app_extension_with_app_query_by_owner_app(
+ app, app_api_client, permission_manage_products
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_APP_EXTENSION_WITH_APP,
+ variables,
+ )
+
+ # then
+ get_graphql_content(response)
+
+
+def test_app_extension_with_app_query_by_staff_with_permissions(
+ external_app, app, permission_manage_apps, staff_api_client
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=external_app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSION_WITH_APP, variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ get_graphql_content(response)
diff --git a/saleor/graphql/app/tests/queries/test_app_extensions.py b/saleor/graphql/app/tests/queries/test_app_extensions.py
new file mode 100644
index 0000000000..872f5b2502
--- /dev/null
+++ b/saleor/graphql/app/tests/queries/test_app_extensions.py
@@ -0,0 +1,207 @@
+import pytest
+
+from .....app.models import AppExtension
+from .....app.types import AppExtensionTarget, AppExtensionType, AppExtensionView
+from .....core.jwt import jwt_decode
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import AppExtensionTargetEnum, AppExtensionTypeEnum, AppExtensionViewEnum
+
+QUERY_APP_EXTENSIONS = """
+query ($filter: AppExtensionFilterInput){
+ appExtensions(first: 10, filter: $filter){
+ edges{
+ node{
+ label
+ url
+ view
+ target
+ id
+ type
+ accessToken
+ permissions{
+ code
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_app_extensions(staff_api_client, app, permission_manage_products):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ variables = {}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSIONS,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ extensions_data = content["data"]["appExtensions"]["edges"]
+
+ assert len(extensions_data) == 1
+ extension_data = extensions_data[0]["node"]
+ assert app_extension.label == extension_data["label"]
+ assert app_extension.url == extension_data["url"]
+ assert app_extension.view == extension_data["view"].lower()
+ assert app_extension.target == extension_data["target"].lower()
+ assert app_extension.type == extension_data["type"].lower()
+
+ assert app_extension.permissions.count() == 1
+ assert len(extension_data["permissions"]) == 1
+ permission_code = extension_data["permissions"][0]["code"].lower()
+ assert app_extension.permissions.first().codename == permission_code
+
+ assert extension_data["accessToken"]
+ decode_token = jwt_decode(extension_data["accessToken"])
+ decode_token["permissions"] = ["MANAGE_PRODUCTS"]
+
+
+def test_app_extensions_app_not_active(
+ staff_api_client, app, permission_manage_products
+):
+ # given
+ app.is_active = False
+ app.save()
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ variables = {}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSIONS,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ extensions_data = content["data"]["appExtensions"]["edges"]
+
+ assert len(extensions_data) == 0
+
+
+def test_app_extensions_user_not_staff(
+ user_api_client, app, permission_manage_products
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ variables = {}
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_APP_EXTENSIONS,
+ variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+ "filter, expected_count",
+ [
+ ({}, 3),
+ ({"view": AppExtensionViewEnum.PRODUCT.name}, 3),
+ ({"target": AppExtensionTargetEnum.CREATE.name}, 1),
+ ({"type": AppExtensionTypeEnum.OVERVIEW.name}, 2),
+ (
+ {
+ "type": AppExtensionTypeEnum.OVERVIEW.name,
+ "view": AppExtensionViewEnum.PRODUCT.name,
+ },
+ 2,
+ ),
+ (
+ {
+ "type": AppExtensionTypeEnum.DETAILS.name,
+ "target": AppExtensionTargetEnum.CREATE.name,
+ },
+ 0,
+ ),
+ (
+ {
+ "type": AppExtensionTypeEnum.DETAILS.name,
+ "target": AppExtensionTargetEnum.MORE_ACTIONS.name,
+ },
+ 1,
+ ),
+ ],
+)
+def test_app_extensions_with_filter(
+ filter, expected_count, staff_api_client, app, permission_manage_products
+):
+ # given
+ app_extensions = AppExtension.objects.bulk_create(
+ [
+ AppExtension(
+ app=app,
+ label="Create product with App1",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ ),
+ AppExtension(
+ app=app,
+ label="Create product with App2",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.DETAILS,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ ),
+ AppExtension(
+ app=app,
+ label="Create product with App3",
+ url="https://www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.CREATE,
+ ),
+ ]
+ )
+ app_extensions[0].permissions.add(permission_manage_products)
+ variables = {"filter": filter}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSIONS,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ extensions_data = content["data"]["appExtensions"]["edges"]
+
+ assert len(extensions_data) == expected_count
diff --git a/saleor/graphql/app/tests/queries/test_apps.py b/saleor/graphql/app/tests/queries/test_apps.py
index ccbab61c36..6cd96fefcc 100644
--- a/saleor/graphql/app/tests/queries/test_apps.py
+++ b/saleor/graphql/app/tests/queries/test_apps.py
@@ -1,3 +1,4 @@
+import graphene
import pytest
from freezegun import freeze_time
@@ -32,6 +33,17 @@ QUERY_APPS_WITH_FILTER = """
supportUrl
configurationUrl
appUrl
+ extensions{
+ id
+ label
+ url
+ view
+ type
+ target
+ permissions{
+ code
+ }
+ }
}
}
}
@@ -53,11 +65,12 @@ def test_apps_query(
staff_api_client,
permission_manage_apps,
permission_manage_orders,
- app,
+ app_with_extensions,
external_app,
app_filter,
count,
):
+ app, app_extensions = app_with_extensions
external_app.is_active = False
external_app.save()
webhooks = Webhook.objects.bulk_create(
@@ -87,6 +100,50 @@ def test_apps_query(
assert len(apps_data) == count
+def test_apps_with_extensions_query(
+ staff_api_client,
+ permission_manage_apps,
+ permission_manage_orders,
+ app_with_extensions,
+):
+ # given
+ app, app_extensions = app_with_extensions
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APPS_WITH_FILTER,
+ permissions=[permission_manage_apps, permission_manage_orders],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ apps_data = content["data"]["apps"]["edges"]
+
+ assert len(apps_data) == 1
+ app_data = apps_data[0]["node"]
+
+ extensions_data = app_data["extensions"]
+ returned_ids = {e["id"] for e in extensions_data}
+ returned_labels = {e["label"] for e in extensions_data}
+ returned_urls = {e["url"] for e in extensions_data}
+ returned_views = {e["view"].lower() for e in extensions_data}
+ returned_types = {e["type"].lower() for e in extensions_data}
+ returned_targets = {e["target"].lower() for e in extensions_data}
+ returned_permission_codes = [e["permissions"] for e in extensions_data]
+ for app_extension in app_extensions:
+ global_id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ assert global_id in returned_ids
+ assert app_extension.label in returned_labels
+ assert app_extension.url in returned_urls
+ assert app_extension.view in returned_views
+ assert app_extension.type in returned_types
+ assert app_extension.target in returned_targets
+ assigned_permissions = [p.codename for p in app_extension.permissions.all()]
+ assigned_permissions = [{"code": p.upper()} for p in assigned_permissions]
+ assert assigned_permissions in returned_permission_codes
+
+
QUERY_APPS_WITH_SORT = """
query ($sort_by: AppSortingInput!) {
apps(first:5, sortBy: $sort_by) {
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index bce3a39e3e..2e0c944260 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -2,15 +2,88 @@ import graphene
from graphene_federation import key
from ...app import models
+from ...core.exceptions import PermissionDenied
from ...core.permissions import AppPermission
from ..core.connection import CountableDjangoObjectType
from ..core.types import Permission
from ..core.types.common import Job
from ..meta.types import ObjectWithMetadata
-from ..utils import format_permissions_for_display
+from ..utils import format_permissions_for_display, get_user_or_app_from_context
from ..webhook.types import Webhook
-from .enums import AppTypeEnum
-from .resolvers import resolve_access_token
+from .dataloaders import AppByIdLoader, AppExtensionByAppIdLoader
+from .enums import (
+ AppExtensionTargetEnum,
+ AppExtensionTypeEnum,
+ AppExtensionViewEnum,
+ AppTypeEnum,
+)
+from .resolvers import (
+ resolve_access_token_for_app,
+ resolve_access_token_for_app_extension,
+)
+
+
+class AppManifestExtension(graphene.ObjectType):
+ permissions = graphene.List(
+ graphene.NonNull(Permission),
+ description="List of the app extension's permissions.",
+ required=True,
+ )
+ label = graphene.String(
+ description="Label of the extension to show in the dashboard.", required=True
+ )
+ url = graphene.String(
+ description="URL of a view where extension's iframe is placed.", required=True
+ )
+ view = AppExtensionViewEnum(
+ description="Name of a view where extension's iframe will be mounted.",
+ required=True,
+ )
+ type = AppExtensionTypeEnum(
+ description="Type of a view where extension's iframe will be mounted.",
+ required=True,
+ )
+ target = AppExtensionTargetEnum(
+ description="Place where extension's iframe will be mounted.", required=True
+ )
+
+
+class AppExtension(AppManifestExtension, CountableDjangoObjectType):
+ app = graphene.Field("saleor.graphql.app.types.App", required=True)
+ access_token = graphene.String(
+ description="JWT token used to authenticate by thridparty app extension."
+ )
+
+ class Meta:
+ description = "Represents app data."
+ interfaces = [graphene.relay.Node]
+ model = models.AppExtension
+
+ @staticmethod
+ def resolve_app(root, info):
+ app_id = None
+ app = info.context.app
+ if app and app.id == root.app_id:
+ app_id = root.app_id
+ else:
+ requestor = get_user_or_app_from_context(info.context)
+ if requestor.has_perm(AppPermission.MANAGE_APPS):
+ app_id = root.app_id
+
+ if not app_id:
+ raise PermissionDenied()
+ return AppByIdLoader(info.context).load(app_id)
+
+ @staticmethod
+ def resolve_permissions(root: models.AppExtension, _info, **_kwargs):
+ permissions = root.permissions.prefetch_related("content_type").order_by(
+ "codename"
+ )
+ return format_permissions_for_display(permissions)
+
+ @staticmethod
+ def resolve_access_token(root: models.App, info):
+ return resolve_access_token_for_app_extension(info, root)
class Manifest(graphene.ObjectType):
@@ -26,6 +99,7 @@ class Manifest(graphene.ObjectType):
data_privacy_url = graphene.String()
homepage_url = graphene.String()
support_url = graphene.String()
+ extensions = graphene.List(graphene.NonNull(AppManifestExtension), required=True)
class Meta:
description = "The manifest definition."
@@ -83,6 +157,11 @@ class App(CountableDjangoObjectType):
access_token = graphene.String(
description="JWT token used to authenticate by thridparty app."
)
+ extensions = graphene.List(
+ graphene.NonNull(AppExtension),
+ description="App's dashboard extensions.",
+ required=True,
+ )
class Meta:
description = "Represents app data."
@@ -120,7 +199,11 @@ class App(CountableDjangoObjectType):
@staticmethod
def resolve_access_token(root: models.App, info):
- return resolve_access_token(info, root)
+ return resolve_access_token_for_app(info, root)
+
+ @staticmethod
+ def resolve_extensions(root: models.App, info):
+ return AppExtensionByAppIdLoader(info.context).load(root.id)
class AppInstallation(CountableDjangoObjectType):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 72651bd5de..7a1ac56552 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -222,6 +222,7 @@ type App implements Node & ObjectWithMetadata {
appUrl: String
version: String
accessToken: String
+ extensions: [AppExtension!]!
}
type AppActivate {
@@ -289,6 +290,49 @@ enum AppErrorCode {
OUT_OF_SCOPE_PERMISSION
}
+type AppExtension implements Node {
+ id: ID!
+ app: App!
+ label: String!
+ url: String!
+ view: AppExtensionViewEnum!
+ type: AppExtensionTypeEnum!
+ target: AppExtensionTargetEnum!
+ permissions: [Permission!]!
+ accessToken: String
+}
+
+type AppExtensionCountableConnection {
+ pageInfo: PageInfo!
+ edges: [AppExtensionCountableEdge!]!
+ totalCount: Int
+}
+
+type AppExtensionCountableEdge {
+ node: AppExtension!
+ cursor: String!
+}
+
+input AppExtensionFilterInput {
+ view: AppExtensionViewEnum
+ type: AppExtensionTypeEnum
+ target: AppExtensionTargetEnum
+}
+
+enum AppExtensionTargetEnum {
+ MORE_ACTIONS
+ CREATE
+}
+
+enum AppExtensionTypeEnum {
+ OVERVIEW
+ DETAILS
+}
+
+enum AppExtensionViewEnum {
+ PRODUCT
+}
+
type AppFetchManifest {
manifest: Manifest
appErrors: [AppError!]! @deprecated(reason: "Use errors field instead. This field will be removed in Saleor 4.0.")
@@ -329,6 +373,15 @@ type AppInstallation implements Node & Job {
message: String
}
+type AppManifestExtension {
+ permissions: [Permission!]!
+ label: String!
+ url: String!
+ view: AppExtensionViewEnum!
+ type: AppExtensionTypeEnum!
+ target: AppExtensionTargetEnum!
+}
+
type AppRetryInstall {
appErrors: [AppError!]! @deprecated(reason: "Use errors field instead. This field will be removed in Saleor 4.0.")
errors: [AppError!]!
@@ -3243,6 +3296,7 @@ type Manifest {
dataPrivacyUrl: String
homepageUrl: String
supportUrl: String
+ extensions: [AppManifestExtension!]!
}
type Margin {
@@ -5626,6 +5680,8 @@ type Query {
appsInstallations: [AppInstallation!]!
apps(filter: AppFilterInput, sortBy: AppSortingInput, before: String, after: String, first: Int, last: Int): AppCountableConnection
app(id: ID): App
+ appExtensions(filter: AppExtensionFilterInput, before: String, after: String, first: Int, last: Int): AppExtensionCountableConnection
+ appExtension(id: ID!): AppExtension
addressValidationRules(countryCode: CountryCode!, countryArea: String, city: String, cityArea: String): AddressValidationData
address(id: ID!): Address
customers(filter: CustomerFilterInput, sortBy: UserSortingInput, before: String, after: String, first: Int, last: Int): UserCountableConnection
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index ee57734c91..8638f735bd 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -25,8 +25,8 @@ from PIL import Image
from prices import Money, TaxedMoney, fixed_discount
from ..account.models import Address, StaffNotificationRecipient, User
-from ..app.models import App, AppInstallation
-from ..app.types import AppType
+from ..app.models import App, AppExtension, AppInstallation
+from ..app.types import AppExtensionTarget, AppExtensionType, AppExtensionView, AppType
from ..attribute import AttributeEntityType, AttributeInputType, AttributeType
from ..attribute.models import (
Attribute,
@@ -4054,6 +4054,33 @@ def app(db):
return app
+def app_with_extensions(app, permission_manage_products):
+ first_app_extension = AppExtension(
+ app=app,
+ label="Create product with App",
+ url="www.example.com/app-product",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.OVERVIEW,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ )
+ extensions = AppExtension.objects.bulk_create(
+ [
+ first_app_extension,
+ AppExtension(
+ app=app,
+ label="Update product with App",
+ url="www.example.com/app-product-update",
+ view=AppExtensionView.PRODUCT,
+ type=AppExtensionType.DETAILS,
+ target=AppExtensionTarget.MORE_ACTIONS,
+ ),
+ ]
+ )
+ first_app_extension.permissions.add(permission_manage_products)
+ return app, extensions
+
+
@pytest.fixture
def payment_app(db, permission_manage_payments):
app = App.objects.create(name="Payment App", is_active=True)
@@ -4363,3 +4390,21 @@ def app_export_event(app_export_file):
app=app_export_file.app,
parameters={"message": "Example error message"},
)
+
+
+def app_manifest():
+ return {
+ "name": "Sample Saleor App",
+ "version": "0.1",
+ "about": "Sample Saleor App serving as an example.",
+ "dataPrivacy": "",
+ "dataPrivacyUrl": "",
+ "homepageUrl": "http://172.17.0.1:5000/homepageUrl",
+ "supportUrl": "http://172.17.0.1:5000/supportUrl",
+ "id": "saleor-complex-sample",
+ "permissions": ["MANAGE_PRODUCTS", "MANAGE_USERS"],
+ "appUrl": "",
+ "configurationUrl": "http://127.0.0.1:5000/configuration/",
+ "tokenTargetUrl": "http://127.0.0.1:5000/configuration/install",
+ }