Skip to content

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

Move ServiceAccount to App. Prepare to depreceate ServiceAccount Api

Maciej Korycinskiffbf19944130
diff --git a/saleor/account/migrations/0040_auto_20200416_0100.py b/saleor/account/migrations/0040_auto_20200416_0100.py
new file mode 100644
index 0000000000..355f169300
--- /dev/null
+++ b/saleor/account/migrations/0040_auto_20200416_0100.py
@@ -0,0 +1,42 @@
+# Generated by Django 3.0.5 on 2020-04-16 06:00
+
+from django.db import migrations, models
+
+
+# TODO Apply step to move SA permission to MANAFGE APPS
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("core", "0001_migrate_metadata"),
+ ("auth", "0011_update_proxy_permissions"),
+ ("webhook", "0002_webhook_name"),
+ ("account", "0039_auto_20200221_0257"),
+ ]
+
+ operations = [
+ migrations.RenameModel(old_name="ServiceAccount", new_name="App",),
+ migrations.RenameModel(old_name="ServiceAccountToken", new_name="AppToken",),
+ migrations.AlterModelOptions(
+ name="app",
+ options={"permissions": (("manage_app", "Manage service account"),)},
+ ),
+ migrations.AlterModelTable(name="app", table="app_app",),
+ migrations.AlterModelTable(name="apptoken", table="app_apptoken",),
+ migrations.RenameField(
+ model_name="apptoken", old_name="service_account", new_name="app",
+ ),
+ migrations.AlterModelOptions(
+ name="app", options={"permissions": (("manage_app", "Manage app"),)},
+ ),
+ migrations.AlterField(
+ model_name="app",
+ name="permissions",
+ field=models.ManyToManyField(
+ blank=True,
+ help_text="Specific permissions for this app.",
+ related_name="app_set",
+ related_query_name="app",
+ to="auth.Permission",
+ ),
+ ),
+ ]
diff --git a/saleor/account/migrations/0041_auto_20200416_0107.py b/saleor/account/migrations/0041_auto_20200416_0107.py
new file mode 100644
index 0000000000..ff6ed5024e
--- /dev/null
+++ b/saleor/account/migrations/0041_auto_20200416_0107.py
@@ -0,0 +1,21 @@
+# Generated by Django 3.0.5 on 2020-04-16 06:07
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("account", "0040_auto_20200416_0100"),
+ ("webhook", "0003_unmount_service_account"),
+ ]
+
+ state_operations = [
+ migrations.RemoveField(model_name="apptoken", name="app",),
+ migrations.DeleteModel(name="App",),
+ migrations.DeleteModel(name="AppToken",),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(state_operations=state_operations)
+ ]
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 819f5f416d..d0470c7b35 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -1,10 +1,7 @@
-from typing import Set
-
from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
- Permission,
PermissionsMixin,
)
from django.contrib.postgres.fields import JSONField
@@ -13,7 +10,6 @@ from django.db.models import Q, Value
from django.forms.models import model_to_dict
from django.utils import timezone
from django_countries.fields import Country, CountryField
-from oauthlib.common import generate_token
from phonenumber_field.modelfields import PhoneNumber, PhoneNumberField
from versatileimagefield.fields import VersatileImageField
@@ -179,63 +175,6 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):
return super().has_perm(perm.value, obj)
-class ServiceAccount(ModelWithMetadata):
- name = models.CharField(max_length=60)
- created = models.DateTimeField(auto_now_add=True)
- is_active = models.BooleanField(default=True)
- permissions = models.ManyToManyField(
- Permission,
- blank=True,
- help_text="Specific permissions for this service.",
- related_name="service_set",
- related_query_name="service",
- )
-
- class Meta:
- permissions = (
- (
- AccountPermissions.MANAGE_SERVICE_ACCOUNTS.codename,
- "Manage service account",
- ),
- )
-
- def _get_permissions(self) -> Set[str]:
- """Return the permissions of the service."""
- if not self.is_active:
- return set()
- perm_cache_name = "_service_perm_cache"
- if not hasattr(self, perm_cache_name):
- perms = self.permissions.all()
- perms = perms.values_list("content_type__app_label", "codename").order_by()
- setattr(self, perm_cache_name, {f"{ct}.{name}" for ct, name in perms})
- return getattr(self, perm_cache_name)
-
- def has_perms(self, perm_list):
- """Return True if the service has each of the specified permissions."""
- if not self.is_active:
- return False
-
- wanted_perms = {perm.value for perm in perm_list}
- actual_perms = self._get_permissions()
-
- return (wanted_perms & actual_perms) == wanted_perms
-
- def has_perm(self, perm):
- """Return True if the service has the specified permission."""
- if not self.is_active:
- return False
-
- return perm.value in self._get_permissions()
-
-
-class ServiceAccountToken(models.Model):
- service_account = models.ForeignKey(
- ServiceAccount, on_delete=models.CASCADE, related_name="tokens"
- )
- name = models.CharField(blank=True, default="", max_length=128)
- auth_token = models.CharField(default=generate_token, unique=True, max_length=30)
-
-
class CustomerNote(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL
diff --git a/saleor/app/__init__.py b/saleor/app/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/app/management/__init__.py b/saleor/app/management/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/app/management/commands/__init__.py b/saleor/app/management/commands/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/account/management/commands/createserviceaccount.py b/saleor/app/management/commands/create_app.py
similarity index 77%
rename from saleor/account/management/commands/createserviceaccount.py
rename to saleor/app/management/commands/create_app.py
index 535074e9a5..2364e5ea94 100644
--- a/saleor/account/management/commands/createserviceaccount.py
+++ b/saleor/app/management/commands/create_app.py
@@ -9,11 +9,11 @@ from django.core.management.base import CommandParser
from requests.exceptions import RequestException
from ....core.permissions import get_permissions, get_permissions_enum_list
-from ...models import ServiceAccount
+from ...models import App
class Command(BaseCommand):
- help = "Used to create service account."
+ help = "Used to create new app."
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument("name", type=str)
@@ -22,15 +22,15 @@ class Command(BaseCommand):
action="append",
default=[],
dest="permissions",
- help="Assign new permission to Service Account. "
+ help="Assign new permission to App. "
"Argument can be specified multiple times.",
)
parser.add_argument("--is_active", default=True, dest="is_active")
parser.add_argument(
"--target_url",
dest="target_url",
- help="Url which will receive newly created data of service account object. "
- "Command doesn't return service account data to stdout when this "
+ help="Url which will receive newly created data of App object. "
+ "Command doesn't return app data to stdout when this "
"argument is provided.",
)
@@ -47,7 +47,7 @@ class Command(BaseCommand):
permissions = get_permissions(required_permissions)
return permissions
- def send_service_account_data(self, target_url, data: Dict[str, Any]):
+ def send_app_data(self, target_url, data: Dict[str, Any]):
domain = Site.objects.get_current().domain
headers = {"x-saleor-domain": domain}
try:
@@ -56,7 +56,7 @@ class Command(BaseCommand):
raise CommandError(f"Request failed. Exception: {e}")
if response.status_code != 200:
raise CommandError(
- f"Failed to send service account data to {target_url}. " # type: ignore
+ f"Failed to send app data to {target_url}. " # type: ignore
f"Status code: {response.status_code}, content: {response.content}"
)
@@ -67,14 +67,14 @@ class Command(BaseCommand):
permissions = list(set(options["permissions"]))
self.validate_permissions(permissions)
- service_account = ServiceAccount.objects.create(name=name, is_active=is_active)
+ app = App.objects.create(name=name, is_active=is_active)
permissions_qs = self.clean_permissions(permissions)
- service_account.permissions.add(*permissions_qs)
- token_obj = service_account.tokens.create()
+ app.permissions.add(*permissions_qs)
+ token_obj = app.tokens.create()
data = {
"auth_token": token_obj.auth_token,
}
if target_url:
- self.send_service_account_data(target_url, data)
+ self.send_app_data(target_url, data)
return json.dumps(data) if not target_url else ""
diff --git a/saleor/app/migrations/0001_initial.py b/saleor/app/migrations/0001_initial.py
new file mode 100644
index 0000000000..a76c082198
--- /dev/null
+++ b/saleor/app/migrations/0001_initial.py
@@ -0,0 +1,144 @@
+# Generated by Django 3.0.5 on 2020-04-15 06:21
+
+import django.contrib.postgres.fields.jsonb
+import django.db.models.deletion
+import oauthlib.common
+from django.db import migrations, models
+
+import saleor.core.utils.json_serializer
+
+
+def update_contentypes(apps, schema_editor):
+ """Update content types.
+
+ We want to have the same content type id, when the model is moved.
+ """
+ ContentType = apps.get_model("contenttypes", "ContentType")
+ db_alias = schema_editor.connection.alias
+ # Move the ServiceAccount to app module
+ qs = ContentType.objects.using(db_alias).filter(app_label="account", model="app")
+ qs.update(app_label="app")
+
+ # Move the ServiceAccountToken to app module
+ qs = ContentType.objects.using(db_alias).filter(
+ app_label="account", model="apptoken"
+ )
+ qs.update(app_label="app")
+
+
+def update_contentypes_reverse(apps, schema_editor):
+ """Revert changes in content types."""
+ ContentType = apps.get_model("contenttypes", "ContentType")
+ db_alias = schema_editor.connection.alias
+
+ qs = ContentType.objects.using(db_alias).filter(app_label="app", model="app")
+ qs.update(app_label="account")
+
+ qs = ContentType.objects.using(db_alias).filter(app_label="app", model="apptoken")
+ qs.update(app_label="account")
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ("auth", "0011_update_proxy_permissions"),
+ ("account", "0041_auto_20200416_0107"),
+ ]
+
+ state_operations = [
+ migrations.CreateModel(
+ name="App",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=60)),
+ ("created", models.DateTimeField(auto_now_add=True)),
+ ("is_active", models.BooleanField(default=True)),
+ (
+ "permissions",
+ models.ManyToManyField(
+ blank=True,
+ help_text="Specific permissions for this app.",
+ related_name="app_set",
+ related_query_name="app",
+ to="auth.Permission",
+ ),
+ ),
+ (
+ "metadata",
+ django.contrib.postgres.fields.jsonb.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ (
+ "private_metadata",
+ django.contrib.postgres.fields.jsonb.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "app_app",
+ "permissions": (("manage_apps", "Manage app"),),
+ },
+ ),
+ migrations.CreateModel(
+ name="AppToken",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(blank=True, default="", max_length=128)),
+ (
+ "auth_token",
+ models.CharField(
+ default=oauthlib.common.generate_token,
+ max_length=30,
+ unique=True,
+ ),
+ ),
+ (
+ "app",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="tokens",
+ to="app.App",
+ ),
+ ),
+ ],
+ options={"db_table": "app_apptoken"},
+ ),
+ ]
+
+ database_operations = [
+ migrations.RunPython(update_contentypes, update_contentypes_reverse),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=state_operations, database_operations=database_operations
+ ),
+ migrations.AlterModelTable(name="app", table=None,),
+ migrations.AlterModelTable(name="apptoken", table=None,),
+ ]
diff --git a/saleor/app/migrations/__init__.py b/saleor/app/migrations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/app/models.py b/saleor/app/models.py
new file mode 100644
index 0000000000..337d58aab9
--- /dev/null
+++ b/saleor/app/models.py
@@ -0,0 +1,62 @@
+from typing import Set
+
+from django.contrib.auth.models import Permission
+from django.db import models
+from oauthlib.common import generate_token
+
+from ..core.models import ModelWithMetadata
+from ..core.permissions import AppPermission
+
+#
+
+
+class App(ModelWithMetadata):
+ name = models.CharField(max_length=60)
+ created = models.DateTimeField(auto_now_add=True)
+ is_active = models.BooleanField(default=True)
+ permissions = models.ManyToManyField(
+ Permission,
+ blank=True,
+ help_text="Specific permissions for this app.",
+ related_name="app_set",
+ related_query_name="app",
+ )
+
+ class Meta:
+ permissions = ((AppPermission.MANAGE_APPS.codename, "Manage app",),)
+
+ def _get_permissions(self) -> Set[str]:
+ """Return the permissions of the app."""
+ if not self.is_active:
+ return set()
+ perm_cache_name = "_app_perm_cache"
+ if not hasattr(self, perm_cache_name):
+ perms = self.permissions.all()
+ perms = perms.values_list("content_type__app_label", "codename").order_by()
+ setattr(self, perm_cache_name, {f"{ct}.{name}" for ct, name in perms})
+ return getattr(self, perm_cache_name)
+
+ def has_perms(self, perm_list):
+ """Return True if the app has each of the specified permissions."""
+ if not self.is_active:
+ return False
+
+ wanted_perms = {perm.value for perm in perm_list}
+ actual_perms = self._get_permissions()
+
+ return (wanted_perms & actual_perms) == wanted_perms
+
+ def has_perm(self, perm):
+ """Return True if the app has the specified permission."""
+ if not self.is_active:
+ return False
+
+ return perm.value in self._get_permissions()
+
+
+#
+#
+class AppToken(models.Model):
+ app = models.ForeignKey(App, on_delete=models.CASCADE, related_name="tokens")
+ name = models.CharField(blank=True, default="", max_length=128)
+ auth_token = models.CharField(default=generate_token, unique=True, max_length=30)
diff --git a/saleor/core/permissions.py b/saleor/core/permissions.py
index 40c1cfac78..7d6851cbe5 100644
--- a/saleor/core/permissions.py
+++ b/saleor/core/permissions.py
@@ -12,7 +12,12 @@ class BasePermissionEnum(Enum):
class AccountPermissions(BasePermissionEnum):
MANAGE_USERS = "account.manage_users"
MANAGE_STAFF = "account.manage_staff"
- MANAGE_SERVICE_ACCOUNTS = "account.manage_service_accounts"
+ # TODO Migrations for account.manage_sa to manage_app
+ MANAGE_SERVICE_ACCOUNTS = "app.manage_apps"
+
+
+class AppPermission(BasePermissionEnum):
+ MANAGE_APPS = "app.manage_apps"
class DiscountPermissions(BasePermissionEnum):
@@ -62,6 +67,7 @@ class WebhookPermissions(BasePermissionEnum):
PERMISSIONS_ENUMS = [
AccountPermissions,
+ AppPermission,
DiscountPermissions,
ExtensionsPermissions,
GiftcardPermissions,
diff --git a/saleor/extensions/plugins/webhook/tasks.py b/saleor/extensions/plugins/webhook/tasks.py
index 6b12f1b95a..d0c55c5d16 100644
--- a/saleor/extensions/plugins/webhook/tasks.py
+++ b/saleor/extensions/plugins/webhook/tasks.py
@@ -19,17 +19,17 @@ def trigger_webhooks_for_event(event_type, data):
required_permission = WebhookEventType.PERMISSIONS[event_type].value
if required_permission:
app_label, codename = required_permission.split(".")
- permissions["service_account__permissions__content_type__app_label"] = app_label
- permissions["service_account__permissions__codename"] = codename
+ permissions["app__permissions__content_type__app_label"] = app_label
+ permissions["app__permissions__codename"] = codename
webhooks = Webhook.objects.filter(
is_active=True,
- service_account__is_active=True,
+ app__is_active=True,
events__event_type__in=[event_type, WebhookEventType.ANY],
**permissions,
)
- webhooks = webhooks.select_related("service_account").prefetch_related(
- "service_account__permissions__content_type"
+ webhooks = webhooks.select_related("app").prefetch_related(
+ "app__permissions__content_type"
)
for webhook in webhooks:
diff --git a/saleor/graphql/account/deprecated/__init__.py b/saleor/graphql/account/deprecated/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/account/deprecated/filters.py b/saleor/graphql/account/deprecated/filters.py
new file mode 100644
index 0000000000..0963f3d435
--- /dev/null
+++ b/saleor/graphql/account/deprecated/filters.py
@@ -0,0 +1,13 @@
+import django_filters
+
+from ....app.models import App
+from ..filters import filter_search
+
+
+class ServiceAccountFilter(django_filters.FilterSet):
+ search = django_filters.CharFilter(method=filter_search)
+ is_active = django_filters.BooleanFilter()
+
+ class Meta:
+ model = App
+ fields = ["search", "is_active"]
diff --git a/saleor/graphql/account/mutations/service_account.py b/saleor/graphql/account/deprecated/mutations_service_account.py
similarity index 85%
rename from saleor/graphql/account/mutations/service_account.py
rename to saleor/graphql/account/deprecated/mutations_service_account.py
index 3214d52ed4..9d8ff1a4c7 100644
--- a/saleor/graphql/account/mutations/service_account.py
+++ b/saleor/graphql/account/deprecated/mutations_service_account.py
@@ -1,11 +1,12 @@
import graphene
-from ....account import models
+from ....app import models
from ....core.permissions import AccountPermissions, get_permissions
from ...core.enums import PermissionEnum
from ...core.mutations import ModelDeleteMutation, ModelMutation
from ...core.types.common import AccountError
from ...meta.deprecated.mutations import ClearMetaBaseMutation, UpdateMetaBaseMutation
+from .types import ServiceAccount, ServiceAccountToken # noqa: F401
class ServiceAccountInput(graphene.InputObjectType):
@@ -35,17 +36,19 @@ class ServiceAccountTokenCreate(ModelMutation):
)
class Meta:
+ return_field_name = "serviceAccountToken"
description = "Creates a new token."
- model = models.ServiceAccountToken
+ model = models.AppToken
permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
error_type_class = AccountError
error_type_field = "account_errors"
@classmethod
def perform_mutation(cls, root, info, **data):
+ input_data = data.get("input", {})
instance = cls.get_instance(info, **data)
- data = data.get("input")
- cleaned_input = cls.clean_input(info, instance, data)
+ cleaned_input = cls.clean_input(info, instance, input_data)
+ cleaned_input["app"] = cleaned_input.pop("service_account", None)
instance = cls.construct_instance(instance, cleaned_input)
cls.clean_instance(info, instance)
cls.save(info, instance, cleaned_input)
@@ -60,8 +63,9 @@ class ServiceAccountTokenDelete(ModelDeleteMutation):
id = graphene.ID(description="ID of an auth token to delete.", required=True)
class Meta:
+ return_field_name = "serviceAccountToken"
description = "Deletes an authentication token assigned to service account."
- model = models.ServiceAccountToken
+ model = models.AppToken
permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
error_type_class = AccountError
error_type_field = "account_errors"
@@ -79,15 +83,16 @@ class ServiceAccountCreate(ModelMutation):
)
class Meta:
+ return_field_name = "serviceAccount"
description = "Creates a new service account."
- model = models.ServiceAccount
+ model = models.App
permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
error_type_class = AccountError
error_type_field = "account_errors"
@classmethod
- def clean_input(cls, info, instance, data):
- cleaned_input = super().clean_input(info, instance, data)
+ def clean_input(cls, info, instance, data, input_cls=None):
+ cleaned_input = super().clean_input(info, instance, data, input_cls)
# clean and prepare permissions
if "permissions" in cleaned_input:
permissions = cleaned_input.pop("permissions")
@@ -117,15 +122,16 @@ class ServiceAccountUpdate(ModelMutation):
)
class Meta:
+ return_field_name = "serviceAccount"
description = "Updates an existing service account."
- model = models.ServiceAccount
+ model = models.App
permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
error_type_class = AccountError
error_type_field = "account_errors"
@classmethod
- def clean_input(cls, info, instance, data):
- cleaned_input = super().clean_input(info, instance, data)
+ def clean_input(cls, info, instance, data, input_cls=None):
+ cleaned_input = super().clean_input(info, instance, data, input_cls)
# clean and prepare permissions
if "permissions" in cleaned_input:
cleaned_input["permissions"] = get_permissions(cleaned_input["permissions"])
@@ -139,8 +145,9 @@ class ServiceAccountDelete(ModelDeleteMutation):
)
class Meta:
+ return_field_name = "serviceAccount"
description = "Deletes a service account."
- model = models.ServiceAccount
+ model = models.App
permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
error_type_class = AccountError
error_type_field = "account_errors"
@@ -148,9 +155,10 @@ class ServiceAccountDelete(ModelDeleteMutation):
class ServiceAccountUpdatePrivateMeta(UpdateMetaBaseMutation):
class Meta:
+ return_field_name = "serviceAccount"
description = "Updates private metadata for a service account."
permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
- model = models.ServiceAccount
+ model = models.App
public = False
error_type_class = AccountError
error_type_field = "account_errors"
@@ -158,8 +166,9 @@ class ServiceAccountUpdatePrivateMeta(UpdateMetaBaseMutation):
class ServiceAccountClearPrivateMeta(ClearMetaBaseMutation):
class Meta:
+ return_field_name = "serviceAccount"
description = "Clear private metadata for a service account."
- model = models.ServiceAccount
+ model = models.App
permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
public = False
error_type_class = AccountError
diff --git a/saleor/graphql/account/deprecated/resolvers.py b/saleor/graphql/account/deprecated/resolvers.py
new file mode 100644
index 0000000000..73007fa39f
--- /dev/null
+++ b/saleor/graphql/account/deprecated/resolvers.py
@@ -0,0 +1,11 @@
+import graphene_django_optimizer as gql_optimizer
+
+from ....app.models import App
+from ...utils import sort_queryset
+from ..deprecated.sorters import ServiceAccountSortField
+
+
+def resolve_service_accounts(info, sort_by=None, **_kwargs):
+ qs = App.objects.all()
+ qs = sort_queryset(qs, sort_by, ServiceAccountSortField)
+ return gql_optimizer.query(qs, info)
diff --git a/saleor/graphql/account/deprecated/sorters.py b/saleor/graphql/account/deprecated/sorters.py
new file mode 100644
index 0000000000..6fc3775a7d
--- /dev/null
+++ b/saleor/graphql/account/deprecated/sorters.py
@@ -0,0 +1,25 @@
+import graphene
+
+from ...core.types import SortInputObjectType
+
+
+class ServiceAccountSortField(graphene.Enum):
+ NAME = "name"
+ CREATION_DATE = "created"
+
+ @property
+ def description(self):
+ # pylint: disable=no-member
+ if self in [
+ ServiceAccountSortField.NAME,
+ ServiceAccountSortField.CREATION_DATE,
+ ]:
+ sort_name = self.name.lower().replace("_", " ")
+ return f"Sort service accounts by {sort_name}."
+ raise ValueError("Unsupported enum value: %s" % self.value)
+
+
+class ServiceAccountSortingInput(SortInputObjectType):
+ class Meta:
+ sort_enum = ServiceAccountSortField
+ type_name = "service accounts"
diff --git a/saleor/graphql/account/deprecated/types.py b/saleor/graphql/account/deprecated/types.py
new file mode 100644
index 0000000000..7b064bda29
--- /dev/null
+++ b/saleor/graphql/account/deprecated/types.py
@@ -0,0 +1,84 @@
+import graphene
+import graphene_django_optimizer as gql_optimizer
+from graphene_federation import key
+
+from ....app.models import App, AppToken
+from ....core.permissions import AccountPermissions
+from ...core.connection import CountableDjangoObjectType
+from ...core.types import PermissionDisplay
+from ...meta.deprecated.resolvers import resolve_meta, resolve_private_meta
+from ...meta.types import ObjectWithMetadata
+from ...utils import format_permissions_for_display
+
+
+class ServiceAccountToken(CountableDjangoObjectType):
+ name = graphene.String(description="Name of the authenticated token.")
+ auth_token = graphene.String(description="Last 4 characters of the token.")
+
+ class Meta:
+ description = "Represents token data."
+ model = AppToken
+ interfaces = [graphene.relay.Node]
+ permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
+ only_fields = ["name", "auth_token"]
+
+ @staticmethod
+ def resolve_auth_token(root: AppToken, _info, **_kwargs):
+ return root.auth_token[-4:]
+
+
+@key(fields="id")
+class ServiceAccount(CountableDjangoObjectType):
+ permissions = graphene.List(
+ PermissionDisplay, description="List of the service's permissions."
+ )
+ created = graphene.DateTime(
+ description="The date and time when the service account was created."
+ )
+ is_active = graphene.Boolean(
+ description="Determine if service account will be set active or not."
+ )
+ name = graphene.String(description="Name of the service account.")
+
+ tokens = graphene.List(
+ ServiceAccountToken, description="Last 4 characters of the tokens."
+ )
+
+ class Meta:
+ description = "Represents service account data."
+ interfaces = [graphene.relay.Node, ObjectWithMetadata]
+ model = App
+ permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
+ only_fields = [
+ "name",
+ "permissions",
+ "created",
+ "is_active",
+ "tokens",
+ "id",
+ "tokens",
+ ]
+
+ @staticmethod
+ def resolve_permissions(root: App, _info, **_kwargs):
+ permissions = root.permissions.prefetch_related("content_type").order_by(
+ "codename"
+ )
+ return format_permissions_for_display(permissions)
+
+ @staticmethod
+ @gql_optimizer.resolver_hints(prefetch_related="tokens")
+ def resolve_tokens(root: App, _info, **_kwargs):
+ return root.tokens.all()
+
+ @staticmethod
+ def resolve_meta(root: App, info):
+ return resolve_meta(root, info)
+
+ @staticmethod
+ def resolve_private_meta(root: App, _info):
+ return resolve_private_meta(root, _info)
+
+ @staticmethod
+ def __resolve_reference(root, _info, **_kwargs):
+ return graphene.Node.get_node_from_global_id(_info, root.id)
diff --git a/saleor/graphql/account/filters.py b/saleor/graphql/account/filters.py
index e6c219e304..5d468a6a0c 100644
--- a/saleor/graphql/account/filters.py
+++ b/saleor/graphql/account/filters.py
@@ -1,7 +1,7 @@
import django_filters
from django.db.models import Count, Sum
-from ...account.models import ServiceAccount, User
+from ...account.models import User
from ..core.filters import EnumFilter, ObjectTypeFilter
from ..core.types.common import DateRangeInput, IntRangeInput, PriceRangeInput
from ..utils import filter_by_query_param, filter_range_field
@@ -86,15 +86,6 @@ class PermissionGroupFilter(django_filters.FilterSet):
search = django_filters.CharFilter(method=filter_search)
-class ServiceAccountFilter(django_filters.FilterSet):
- search = django_filters.CharFilter(method=filter_search)
- is_active = django_filters.BooleanFilter()
-
- class Meta:
- model = ServiceAccount
- fields = ["search", "is_active"]
-
-
class StaffUserFilter(django_filters.FilterSet):
status = EnumFilter(input_class=StaffMemberStatus, method=filter_status)
search = django_filters.CharFilter(method=filter_staff_search)
diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.py
index c187b32c3e..e672ad6c27 100644
--- a/saleor/graphql/account/resolvers.py
+++ b/saleor/graphql/account/resolvers.py
@@ -12,17 +12,8 @@ from ...account import models
from ...core.permissions import AccountPermissions
from ...payment import gateway
from ...payment.utils import fetch_customer_id
-from ..utils import (
- filter_by_query_param,
- get_user_or_service_account_from_context,
- sort_queryset,
-)
-from .sorters import (
- PermissionGroupSortingInput,
- ServiceAccountSortField,
- UserSortField,
- UserSortingInput,
-)
+from ..utils import filter_by_query_param, get_user_or_app_from_context, sort_queryset
+from .sorters import PermissionGroupSortingInput, UserSortField, UserSortingInput
from .types import AddressValidationData, ChoiceValue
from .utils import get_allowed_fields_camel_case, get_required_fields_camel_case
@@ -70,7 +61,7 @@ def resolve_staff_users(info, query, sort_by=None, **_kwargs):
def resolve_user(info, id):
- requester = get_user_or_service_account_from_context(info.context)
+ requester = get_user_or_app_from_context(info.context)
if requester:
_model, user_pk = graphene.Node.from_global_id(id)
if requester.has_perms(
@@ -84,12 +75,6 @@ def resolve_user(info, id):
return PermissionDenied()
-def resolve_service_accounts(info, sort_by=None, **_kwargs):
- qs = models.ServiceAccount.objects.all()
- qs = sort_queryset(qs, sort_by, ServiceAccountSortField)
- return gql_optimizer.query(qs, info)
-
-
def resolve_address_validation_rules(
info,
country_code: str,
@@ -170,9 +155,9 @@ def prepare_graphql_payment_sources_type(payment_sources):
def resolve_address(info, id):
user = info.context.user
- service_account = info.context.service_account
+ app = info.context.app
_model, address_pk = graphene.Node.from_global_id(id)
- if service_account and service_account.has_perm(AccountPermissions.MANAGE_USERS):
+ if app and app.has_perm(AccountPermissions.MANAGE_USERS):
return models.Address.objects.filter(pk=address_pk).first()
if user and not user.is_anonymous:
return user.addresses.filter(id=address_pk).first()
diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.py
index 43142dbf60..10edac2886 100644
--- a/saleor/graphql/account/schema.py
+++ b/saleor/graphql/account/schema.py
@@ -5,13 +5,21 @@ from ..core.fields import FilterInputConnectionField
from ..core.types import FilterInputObjectType
from ..decorators import one_of_permissions_required, permission_required
from .bulk_mutations import CustomerBulkDelete, StaffBulkDelete, UserBulkSetActive
-from .enums import CountryCodeEnum
-from .filters import (
- CustomerFilter,
- PermissionGroupFilter,
- ServiceAccountFilter,
- StaffUserFilter,
+from .deprecated.filters import ServiceAccountFilter
+from .deprecated.mutations_service_account import (
+ ServiceAccountClearPrivateMeta,
+ ServiceAccountCreate,
+ ServiceAccountDelete,
+ ServiceAccountTokenCreate,
+ ServiceAccountTokenDelete,
+ ServiceAccountUpdate,
+ ServiceAccountUpdatePrivateMeta,
)
+from .deprecated.resolvers import resolve_service_accounts
+from .deprecated.sorters import ServiceAccountSortingInput
+from .deprecated.types import ServiceAccount
+from .enums import CountryCodeEnum
+from .filters import CustomerFilter, PermissionGroupFilter, StaffUserFilter
from .mutations.account import (
AccountAddressCreate,
AccountAddressDelete,
@@ -40,15 +48,6 @@ from .mutations.permission_group import (
PermissionGroupUnassignUsers,
PermissionGroupUpdate,
)
-from .mutations.service_account import (
- ServiceAccountClearPrivateMeta,
- ServiceAccountCreate,
- ServiceAccountDelete,
- ServiceAccountTokenCreate,
- ServiceAccountTokenDelete,
- ServiceAccountUpdate,
- ServiceAccountUpdatePrivateMeta,
-)
from .mutations.staff import (
AddressCreate,
AddressDelete,
@@ -70,16 +69,11 @@ from .resolvers import (
resolve_address_validation_rules,
resolve_customers,
resolve_permission_groups,
- resolve_service_accounts,
resolve_staff_users,
resolve_user,
)
-from .sorters import (
- PermissionGroupSortingInput,
- ServiceAccountSortingInput,
- UserSortingInput,
-)
-from .types import Address, AddressValidationData, Group, ServiceAccount, User
+from .sorters import PermissionGroupSortingInput, UserSortingInput
+from .types import Address, AddressValidationData, Group, User
class CustomerFilterInput(FilterInputObjectType):
diff --git a/saleor/graphql/account/sorters.py b/saleor/graphql/account/sorters.py
index 382e41ad82..aa54e0db22 100644
--- a/saleor/graphql/account/sorters.py
+++ b/saleor/graphql/account/sorters.py
@@ -4,28 +4,6 @@ from django.db.models import Count, QuerySet
from ..core.types import SortInputObjectType
-class ServiceAccountSortField(graphene.Enum):
- NAME = "name"
- CREATION_DATE = "created"
-
- @property
- def description(self):
- # pylint: disable=no-member
- if self in [
- ServiceAccountSortField.NAME,
- ServiceAccountSortField.CREATION_DATE,
- ]:
- sort_name = self.name.lower().replace("_", " ")
- return f"Sort service accounts by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
-
-
-class ServiceAccountSortingInput(SortInputObjectType):
- class Meta:
- sort_enum = ServiceAccountSortField
- type_name = "service accounts"
-
-
class UserSortField(graphene.Enum):
FIRST_NAME = "first_name"
LAST_NAME = "last_name"
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 0ed0e7c73a..1c2964e979 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -169,79 +169,6 @@ class CustomerEvent(CountableDjangoObjectType):
return None
-class ServiceAccountToken(CountableDjangoObjectType):
- name = graphene.String(description="Name of the authenticated token.")
- auth_token = graphene.String(description="Last 4 characters of the token.")
-
- class Meta:
- description = "Represents token data."
- model = models.ServiceAccountToken
- interfaces = [relay.Node]
- permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
- only_fields = ["name", "auth_token"]
-
- @staticmethod
- def resolve_auth_token(root: models.ServiceAccountToken, _info, **_kwargs):
- return root.auth_token[-4:]
-
-
-@key(fields="id")
-class ServiceAccount(CountableDjangoObjectType):
- permissions = graphene.List(
- PermissionDisplay, description="List of the service's permissions."
- )
- created = graphene.DateTime(
- description="The date and time when the service account was created."
- )
- is_active = graphene.Boolean(
- description="Determine if service account will be set active or not."
- )
- name = graphene.String(description="Name of the service account.")
-
- tokens = graphene.List(
- ServiceAccountToken, description="Last 4 characters of the tokens."
- )
-
- class Meta:
- description = "Represents service account data."
- interfaces = [relay.Node, ObjectWithMetadata]
- model = models.ServiceAccount
- permissions = (AccountPermissions.MANAGE_SERVICE_ACCOUNTS,)
- only_fields = [
- "name",
- "permissions",
- "created",
- "is_active",
- "tokens",
- "id",
- "tokens",
- ]
-
- @staticmethod
- def resolve_permissions(root: models.ServiceAccount, _info, **_kwargs):
- permissions = root.permissions.prefetch_related("content_type").order_by(
- "codename"
- )
- return format_permissions_for_display(permissions)
-
- @staticmethod
- @gql_optimizer.resolver_hints(prefetch_related="tokens")
- def resolve_tokens(root: models.ServiceAccount, _info, **_kwargs):
- return root.tokens.all()
-
- @staticmethod
- def resolve_meta(root: models.ServiceAccount, info):
- return resolve_meta(root, info)
-
- @staticmethod
- def resolve_private_meta(root: models.ServiceAccount, _info):
- return resolve_private_meta(root, _info)
-
- @staticmethod
- def __resolve_reference(root, _info, **_kwargs):
- return graphene.Node.get_node_from_global_id(_info, root.id)
-
-
@key("id")
@key("email")
class User(CountableDjangoObjectType):
diff --git a/saleor/graphql/app/__init__.py b/saleor/graphql/app/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/checkout/resolvers.py b/saleor/graphql/checkout/resolvers.py
index 8526034da8..e8a3ccb0d9 100644
--- a/saleor/graphql/checkout/resolvers.py
+++ b/saleor/graphql/checkout/resolvers.py
@@ -1,6 +1,6 @@
from ...checkout import models
from ...core.permissions import CheckoutPermissions
-from ..utils import get_user_or_service_account_from_context
+from ..utils import get_user_or_app_from_context
def resolve_checkout_lines():
@@ -28,7 +28,7 @@ def resolve_checkout(info, token):
return checkout
# resolve checkout for staff user
- requester = get_user_or_service_account_from_context(info.context)
+ requester = get_user_or_app_from_context(info.context)
if requester.has_perm(CheckoutPermissions.MANAGE_CHECKOUTS):
return checkout
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 7905e91cb6..f906eb6604 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -269,8 +269,8 @@ class BaseMutation(graphene.Mutation):
return True
if context.user.has_perms(permissions):
return True
- service_account = getattr(context, "service_account", None)
- if service_account and service_account.has_perms(permissions):
+ app = getattr(context, "app", None)
+ if app and app.has_perms(permissions):
return True
return False
diff --git a/saleor/graphql/decorators.py b/saleor/graphql/decorators.py
index 9cff5ab226..f06e5fcff5 100644
--- a/saleor/graphql/decorators.py
+++ b/saleor/graphql/decorators.py
@@ -7,7 +7,7 @@ from graphql_jwt.decorators import context
def account_passes_test(test_func):
- """Determine if user/service_account has permission to access to content."""
+ """Determine if user/app has permission to access to content."""
def decorator(f):
@wraps(f)
@@ -25,8 +25,8 @@ def account_passes_test(test_func):
def _permission_required(perms: Iterable[Enum], context):
if context.user.has_perms(perms):
return True
- service_account = getattr(context, "service_account", None)
- if service_account and service_account.has_perms(perms):
+ app = getattr(context, "app", None)
+ if app and app.has_perms(perms):
return True
return False
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.py
index 00ab90ca16..134cfa8171 100644
--- a/saleor/graphql/meta/permissions.py
+++ b/saleor/graphql/meta/permissions.py
@@ -5,6 +5,7 @@ from graphql_jwt.exceptions import PermissionDenied
from ...account import models as account_models
from ...core.permissions import (
AccountPermissions,
+ AppPermission,
BasePermissionEnum,
CheckoutPermissions,
OrderPermissions,
@@ -51,7 +52,7 @@ def order_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:
def service_account_permissions(_info, _object_pk: int) -> List[BasePermissionEnum]:
- return [AccountPermissions.MANAGE_SERVICE_ACCOUNTS]
+ return [AppPermission.MANAGE_APPS]
def checkout_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:
diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.py
index 74df84e481..ed1973859f 100644
--- a/saleor/graphql/meta/resolvers.py
+++ b/saleor/graphql/meta/resolvers.py
@@ -3,17 +3,19 @@ from operator import itemgetter
from graphql_jwt.exceptions import PermissionDenied
from ...account import models as account_models
+from ...app import models as app_models
from ...checkout import models as checkout_models
from ...core.models import ModelWithMetadata
from ...order import models as order_models
from ...product import models as product_models
-from ..utils import get_user_or_service_account_from_context
+from ..utils import get_user_or_app_from_context
from .permissions import PRIVATE_META_PERMISSION_MAP
def resolve_object_with_metadata_type(instance: ModelWithMetadata):
# Imports inside resolvers to avoid circular imports.
from ..account import types as account_types
+ from ..account.deprecated.types import ServiceAccount
from ..checkout import types as checkout_types
from ..order import types as order_types
from ..product import types as product_types
@@ -29,7 +31,7 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):
product_models.Product: product_types.Product,
product_models.ProductType: product_types.ProductType,
product_models.ProductVariant: product_types.ProductVariant,
- account_models.ServiceAccount: account_types.ServiceAccount,
+ app_models.App: ServiceAccount, # FIXME
account_models.User: account_types.User,
}
return MODEL_TO_TYPE_MAP.get(type(instance), None)
@@ -57,7 +59,7 @@ def resolve_private_metadata(root: ModelWithMetadata, info):
if not required_permission:
raise PermissionDenied()
- requester = get_user_or_service_account_from_context(info.context)
+ requester = get_user_or_app_from_context(info.context)
if not requester.has_perms(required_permission):
raise PermissionDenied()
diff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.py
index 8d386a22af..ea261b28eb 100644
--- a/saleor/graphql/middleware.py
+++ b/saleor/graphql/middleware.py
@@ -8,7 +8,7 @@ from django.utils.functional import SimpleLazyObject
from graphql import ResolveInfo
from graphql_jwt.middleware import JSONWebTokenMiddleware
-from ..account.models import ServiceAccount
+from ..app.models import App
from ..core.tracing import should_trace
from .views import API_PATH, GraphQLView
@@ -36,27 +36,25 @@ class OpentracingGrapheneMiddleware:
return next_(root, info, **kwargs)
-def get_service_account(auth_token) -> Optional[ServiceAccount]:
- qs = ServiceAccount.objects.filter(tokens__auth_token=auth_token, is_active=True)
+def get_app(auth_token) -> Optional[App]:
+ qs = App.objects.filter(tokens__auth_token=auth_token, is_active=True)
return qs.first()
-def service_account_middleware(next, root, info, **kwargs):
+def app_middleware(next, root, info, **kwargs):
- service_account_auth_header = "HTTP_AUTHORIZATION"
+ app_auth_header = "HTTP_AUTHORIZATION"
prefix = "bearer"
request = info.context
if request.path == API_PATH:
- if not hasattr(request, "service_account"):
- request.service_account = None
- auth = request.META.get(service_account_auth_header, "").split()
+ if not hasattr(request, "app"):
+ request.app = None
+ auth = request.META.get(app_auth_header, "").split()
if len(auth) == 2:
auth_prefix, auth_token = auth
if auth_prefix.lower() == prefix:
- request.service_account = SimpleLazyObject(
- lambda: get_service_account(auth_token)
- )
+ request.app = SimpleLazyObject(lambda: get_app(auth_token))
return next(root, info, **kwargs)
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index e82145826c..32cb62ec4a 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -14,7 +14,7 @@ from ..utils import (
filter_by_query_param,
get_database_id,
get_nodes,
- get_user_or_service_account_from_context,
+ get_user_or_app_from_context,
sort_queryset,
)
from .filters import (
@@ -145,7 +145,7 @@ def resolve_products(
**_kwargs,
):
- user = get_user_or_service_account_from_context(info.context)
+ user = get_user_or_app_from_context(info.context)
qs = models.Product.objects.visible_to_user(user)
qs = sort_products(qs, sort_by)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index bfadc79c1a..97eb7b8845 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3024,6 +3024,7 @@ enum PermissionEnum {
MANAGE_USERS
MANAGE_STAFF
MANAGE_SERVICE_ACCOUNTS
+ MANAGE_APPS
MANAGE_DISCOUNTS
MANAGE_PLUGINS
MANAGE_GIFT_CARD
@@ -4961,12 +4962,12 @@ input WarehouseUpdateInput {
type Webhook implements Node {
name: String!
- serviceAccount: ServiceAccount!
targetUrl: String!
isActive: Boolean!
secretKey: String
id: ID!
events: [WebhookEvent!]!
+ serviceAccount: ServiceAccount!
}
type WebhookCountableConnection {
@@ -4991,6 +4992,7 @@ input WebhookCreateInput {
targetUrl: String
events: [WebhookEventTypeEnum]
serviceAccount: ID
+ app: ID
isActive: Boolean
secretKey: String
}
@@ -5072,6 +5074,7 @@ input WebhookUpdateInput {
targetUrl: String
events: [WebhookEventTypeEnum]
serviceAccount: ID
+ app: ID
isActive: Boolean
secretKey: String
}
@@ -5092,7 +5095,7 @@ enum WeightUnitsEnum {
scalar _Any
-union _Entity = Address | ServiceAccount | User | Group | ProductVariant | Product | ProductType | Collection | Category | ProductImage
+union _Entity = Address | User | Group | ServiceAccount | ProductVariant | Product | ProductType | Collection | Category | ProductImage
type _Service {
sdl: String
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
index a558c640c9..1ac8f0ba14 100644
--- a/saleor/graphql/utils.py
+++ b/saleor/graphql/utils.py
@@ -185,10 +185,10 @@ def create_jwt_payload(user, context=None):
return payload
-def get_user_or_service_account_from_context(context):
+def get_user_or_app_from_context(context):
# order is important
- # service_account can be None but user if None then is passed as anonymous
- return context.service_account or context.user
+ # app can be None but user if None then is passed as anonymous
+ return context.app or context.user
def filter_range_field(qs, field, value):
diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.py
index 927aa4ffc3..f79881e145 100644
--- a/saleor/graphql/webhook/mutations.py
+++ b/saleor/graphql/webhook/mutations.py
@@ -20,6 +20,9 @@ class WebhookCreateInput(graphene.InputObjectType):
required=False,
description="ID of the service account to which webhook belongs.",
)
+ app = graphene.ID(
+ required=False, description="ID of the app to which webhook belongs.",
+ )
is_active = graphene.Boolean(
description="Determine if webhook will be set active or not.", required=False
)
@@ -46,40 +49,39 @@ class WebhookCreate(ModelMutation):
def clean_input(cls, info, instance, data):
cleaned_data = super().clean_input(info, instance, data)
- service_account = cleaned_data.get("service_account")
+ # This should be removed after we drop service_account
+ service_account = cleaned_data.pop("service_account", None)
+ app = cleaned_data["app"] = cleaned_data.get("app") or 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", code=WebhookErrorCode.INVALID
- )
-
- 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:
+ # We need to confirm that cleaned_data has app_id or
+ # context has assigned app instance
+ if not instance.app_id and not app:
+ raise ValidationError("Missing token or app", code=WebhookErrorCode.INVALID)
+
+ if instance.app_id:
+ # Let's skip app id in case when context has
+ # app instance
+ app = instance.app
+ cleaned_data.pop("app", None)
+
+ if not app or not app.is_active:
raise ValidationError(
- "Service account doesn't exist or is disabled",
- code=WebhookErrorCode.NOT_FOUND,
+ "App doesn't exist or is disabled", code=WebhookErrorCode.NOT_FOUND,
)
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
+ app = info.context.app
+ instance.app = app
return instance
@classmethod
def check_permissions(cls, context):
has_perm = super().check_permissions(context)
- has_perm = bool(context.service_account) or has_perm
+ has_perm = bool(context.app) or has_perm
return has_perm
@classmethod
@@ -108,6 +110,9 @@ class WebhookUpdateInput(graphene.InputObjectType):
required=False,
description="ID of the service account to which webhook belongs.",
)
+ app = graphene.ID(
+ required=False, description="ID of the app to which webhook belongs.",
+ )
is_active = graphene.Boolean(
description="Determine if webhook will be set active or not.", required=False
)
@@ -132,6 +137,16 @@ class WebhookUpdate(ModelMutation):
error_type_class = WebhookError
error_type_field = "webhook_errors"
+ @classmethod
+ def clean_input(cls, info, instance, data, input_cls=None):
+ cleaned_input = super().clean_input(info, instance, data, input_cls)
+ # This should be removed after we drop service_account
+ service_account = cleaned_input.pop("service_account", None)
+ app = cleaned_input.get("app", service_account)
+ if app:
+ cleaned_input["app"] = app
+ return cleaned_input
+
@classmethod
def save(cls, info, instance, cleaned_input):
instance.save()
@@ -162,7 +177,7 @@ class WebhookDelete(ModelDeleteMutation):
@classmethod
def check_permissions(cls, context):
has_perm = super().check_permissions(context)
- has_perm = bool(context.service_account) or has_perm
+ has_perm = bool(context.app) or has_perm
return has_perm
@classmethod
@@ -170,15 +185,15 @@ class WebhookDelete(ModelDeleteMutation):
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:
+ app = info.context.app
+ if app:
+ if not app.is_active:
raise ValidationError(
"Service account needs to be active to delete webhook",
code=WebhookErrorCode.INVALID,
)
try:
- service_account.webhooks.get(id=object_id)
+ app.webhooks.get(id=object_id)
except models.Webhook.DoesNotExist:
raise ValidationError(
"Couldn't resolve to a node: %s" % node_id,
diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.py
index 1a32b88261..fbff72d9e5 100644
--- a/saleor/graphql/webhook/resolvers.py
+++ b/saleor/graphql/webhook/resolvers.py
@@ -10,9 +10,9 @@ from .types import Webhook, WebhookEvent
def resolve_webhooks(info, sort_by=None, **_kwargs):
- service_account = info.context.service_account
- if service_account:
- qs = models.Webhook.objects.filter(service_account=service_account)
+ app = info.context.app
+ if app:
+ qs = models.Webhook.objects.filter(app=app)
else:
user = info.context.user
if not user.has_perm(WebhookPermissions.MANAGE_WEBHOOKS):
@@ -22,10 +22,10 @@ def resolve_webhooks(info, sort_by=None, **_kwargs):
def resolve_webhook(info, webhook_id):
- service_account = info.context.service_account
- if service_account:
+ app = info.context.app
+ if app:
_, webhook_id = graphene.Node.from_global_id(webhook_id)
- return service_account.webhooks.filter(id=webhook_id).first()
+ return app.webhooks.filter(id=webhook_id).first()
user = info.context.user
if user.has_perm(WebhookPermissions.MANAGE_WEBHOOKS):
return graphene.Node.get_node_from_global_id(info, webhook_id, Webhook)
@@ -40,10 +40,10 @@ def resolve_webhook_events():
def resolve_sample_payload(info, event_name):
- service_account = info.context.service_account
+ app = info.context.app
required_permission = WebhookEventType.PERMISSIONS.get(event_name)
if required_permission:
- if service_account and service_account.has_perm(required_permission):
+ if app and app.has_perm(required_permission):
return payloads.generate_sample_payload(event_name)
if info.context.user.has_perm(required_permission):
return payloads.generate_sample_payload(event_name)
diff --git a/saleor/graphql/webhook/sorters.py b/saleor/graphql/webhook/sorters.py
index c660d16c91..3bb63c6815 100644
--- a/saleor/graphql/webhook/sorters.py
+++ b/saleor/graphql/webhook/sorters.py
@@ -5,7 +5,7 @@ from ..core.types import SortInputObjectType
class WebhookSortField(graphene.Enum):
NAME = "name"
- SERVICE_ACCOUNT = "service_account__name"
+ SERVICE_ACCOUNT = "app__name"
TARGET_URL = "target_url"
@property
diff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.py
index b469ab999d..6d1a3a95fc 100644
--- a/saleor/graphql/webhook/types.py
+++ b/saleor/graphql/webhook/types.py
@@ -3,6 +3,7 @@ import graphene_django_optimizer as gql_optimizer
from ...webhook import models
from ...webhook.event_types import WebhookEventType
+from ..account.deprecated.types import ServiceAccount
from ..core.connection import CountableDjangoObjectType
from .enums import WebhookEventTypeEnum
@@ -33,19 +34,23 @@ class Webhook(CountableDjangoObjectType):
),
model_field="events",
)
+ service_account = graphene.Field(ServiceAccount, required=True)
class Meta:
description = "Webhook."
model = models.Webhook
interfaces = [graphene.relay.Node]
only_fields = [
- "service_account",
"target_url",
"is_active",
"secret_key",
"name",
]
+ @staticmethod
+ def resolve_service_account(root: models.Webhook, *_args, **_kwargs):
+ return root.app
+
@staticmethod
@gql_optimizer.resolver_hints(prefetch_related=("events",))
def resolve_events(root: models.Webhook, *_args, **_kwargs):
diff --git a/saleor/settings.py b/saleor/settings.py
index 4889116baf..6a3f40fc90 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -237,6 +237,7 @@ INSTALLED_APPS = [
"saleor.warehouse",
"saleor.webhook",
"saleor.wishlist",
+ "saleor.app",
# External apps
"versatileimagefield",
"django_measurement",
@@ -506,7 +507,7 @@ GRAPHENE = {
"MIDDLEWARE": [
"saleor.graphql.middleware.OpentracingGrapheneMiddleware",
"saleor.graphql.middleware.JWTMiddleware",
- "saleor.graphql.middleware.service_account_middleware",
+ "saleor.graphql.middleware.app_middleware",
],
}
diff --git a/saleor/webhook/migrations/0003_unmount_service_account.py b/saleor/webhook/migrations/0003_unmount_service_account.py
new file mode 100644
index 0000000000..e047204135
--- /dev/null
+++ b/saleor/webhook/migrations/0003_unmount_service_account.py
@@ -0,0 +1,22 @@
+# Generated by Django 3.0.5 on 2020-04-16 06:01
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("webhook", "0002_webhook_name"),
+ ("account", "0040_auto_20200416_0100"),
+ ]
+
+ state_operations = [
+ migrations.RemoveField(model_name="webhook", name="app",),
+ ]
+
+ operations = [
+ migrations.RenameField(
+ model_name="webhook", old_name="service_account", new_name="app"
+ ),
+ migrations.SeparateDatabaseAndState(state_operations=state_operations),
+ ]
diff --git a/saleor/webhook/migrations/0004_mount_app.py b/saleor/webhook/migrations/0004_mount_app.py
new file mode 100644
index 0000000000..9f2bee01cf
--- /dev/null
+++ b/saleor/webhook/migrations/0004_mount_app.py
@@ -0,0 +1,24 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("app", "0001_initial"),
+ ("webhook", "0003_unmount_service_account"),
+ ]
+ state_operations = [
+ migrations.AddField(
+ model_name="webhook",
+ name="app",
+ field=models.ForeignKey(
+ default="",
+ on_delete=models.deletion.CASCADE,
+ related_name="webhooks",
+ to="app.App",
+ ),
+ preserve_default=False,
+ ),
+ ]
+ operations = [
+ migrations.SeparateDatabaseAndState(state_operations=state_operations)
+ ]
diff --git a/saleor/webhook/models.py b/saleor/webhook/models.py
index e9fa4b8e05..e83ff49887 100644
--- a/saleor/webhook/models.py
+++ b/saleor/webhook/models.py
@@ -1,14 +1,12 @@
from django.db import models
-from ..account.models import ServiceAccount
+from ..app.models import App
from ..core.permissions import WebhookPermissions
class Webhook(models.Model):
name = models.CharField(max_length=255, null=True, blank=True)
- service_account = models.ForeignKey(
- ServiceAccount, related_name="webhooks", on_delete=models.CASCADE
- )
+ app = models.ForeignKey(App, related_name="webhooks", on_delete=models.CASCADE)
target_url = models.URLField(max_length=255)
is_active = models.BooleanField(default=True)
secret_key = models.CharField(max_length=255, null=True, blank=True)
diff --git a/tests/api/conftest.py b/tests/api/conftest.py
index 1a87119345..f9646cafdd 100644
--- a/tests/api/conftest.py
+++ b/tests/api/conftest.py
@@ -8,7 +8,8 @@ from django.shortcuts import reverse
from django.test.client import MULTIPART_CONTENT, Client
from graphql_jwt.shortcuts import get_token
-from saleor.account.models import ServiceAccount, User
+from saleor.account.models import User
+from saleor.app.models import App
from ..utils import flush_post_commit_hooks
from .utils import assert_no_permission
@@ -21,25 +22,25 @@ class ApiClient(Client):
def __init__(self, *args, **kwargs):
user = kwargs.pop("user", AnonymousUser())
- service_account = kwargs.pop("service_account", None)
+ app = kwargs.pop("app", None)
self._user = None
self.token = None
self.user = user
- self.service_token = None
- self.service_account = service_account
+ self.app_token = None
+ self.app = app
if not user.is_anonymous:
self.token = get_token(user)
- elif service_account:
- token = service_account.tokens.first()
- self.service_token = token.auth_token if token else None
+ elif app:
+ token = app.tokens.first()
+ self.app_token = token.auth_token if token else None
super().__init__(*args, **kwargs)
def _base_environ(self, **request):
environ = super()._base_environ(**request)
if not self.user.is_anonymous:
environ["HTTP_AUTHORIZATION"] = f"JWT {self.token}"
- elif self.service_token:
- environ["HTTP_AUTHORIZATION"] = f"Bearer {self.service_token}"
+ elif self.app_token:
+ environ["HTTP_AUTHORIZATION"] = f"Bearer {self.app_token}"
return environ
@property
@@ -88,8 +89,8 @@ class ApiClient(Client):
if check_no_permissions:
response = super().post(API_PATH, data, **kwargs)
assert_no_permission(response)
- if self.service_account:
- self.service_account.permissions.add(*permissions)
+ if self.app:
+ self.app.permissions.add(*permissions)
else:
self.user.user_permissions.add(*permissions)
result = super().post(API_PATH, data, **kwargs)
@@ -112,8 +113,8 @@ class ApiClient(Client):
@pytest.fixture
-def service_account_api_client(service_account):
- return ApiClient(service_account=service_account)
+def app_api_client(app):
+ return ApiClient(app=app)
@pytest.fixture
@@ -164,9 +165,7 @@ def user_list_not_active(user_list):
@pytest.fixture
-def service_account(db):
- service_account = ServiceAccount.objects.create(
- name="Sample service account", is_active=True
- )
- service_account.tokens.create(name="Default")
- return service_account
+def app(db):
+ app = App.objects.create(name="Sample app object", is_active=True)
+ app.tokens.create(name="Default")
+ return app
diff --git a/tests/api/pagination/test_webhook.py b/tests/api/pagination/test_webhook.py
index 1b18f7e3ba..3d418ca5fa 100644
--- a/tests/api/pagination/test_webhook.py
+++ b/tests/api/pagination/test_webhook.py
@@ -1,6 +1,6 @@
import pytest
-from saleor.account.models import ServiceAccount
+from saleor.app.models import App
from saleor.webhook.models import Webhook
from ..utils import get_graphql_content
@@ -8,41 +8,36 @@ from ..utils import get_graphql_content
@pytest.fixture
def webhooks_for_pagination(db):
- service_accounts = ServiceAccount.objects.bulk_create(
- [
- ServiceAccount(name="ServiceAccount1", is_active=True),
- ServiceAccount(name="ServiceAccount2", is_active=True),
- ]
+ apps = App.objects.bulk_create(
+ [App(name="App1", is_active=True), App(name="App2", is_active=True)]
)
return Webhook.objects.bulk_create(
[
Webhook(
name="Webhook1",
- service_account=service_accounts[1],
+ app=apps[1],
target_url="http://www.example.com/test4",
is_active=False,
),
Webhook(
name="WebhookWebhook1",
- service_account=service_accounts[0],
+ app=apps[0],
target_url="http://www.example.com/test2",
),
Webhook(
name="WebhookWebhook2",
- service_account=service_accounts[1],
+ app=apps[1],
target_url="http://www.example.com/test1",
),
Webhook(
name="Webhook2",
- service_account=service_accounts[1],
+ app=apps[1],
target_url="http://www.example.com/test3",
is_active=False,
),
Webhook(
- name="Webhook3",
- service_account=service_accounts[0],
- target_url="http://www.example.com/test",
+ name="Webhook3", app=apps[0], target_url="http://www.example.com/test",
),
]
)
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index f4d418caa0..99b4c18af8 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -305,12 +305,10 @@ def test_user_query_permission_manage_users_get_customer(
assert customer_user.email == data["email"]
-def test_user_query_as_service_account(
- service_account_api_client, customer_user, permission_manage_users
-):
+def test_user_query_as_app(app_api_client, customer_user, permission_manage_users):
customer_id = graphene.Node.to_global_id("User", customer_user.pk)
variables = {"id": customer_id}
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
USER_QUERY, variables, permissions=[permission_manage_users]
)
content = get_graphql_content(response)
@@ -3168,11 +3166,11 @@ def test_address_query_as_not_owner(
assert not data
-def test_address_query_as_service_account_with_permission(
- service_account_api_client, address_other_country, permission_manage_users,
+def test_address_query_as_app_with_permission(
+ app_api_client, address_other_country, permission_manage_users,
):
variables = {"id": graphene.Node.to_global_id("Address", address_other_country.pk)}
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
ADDRESS_QUERY, variables, permissions=[permission_manage_users]
)
content = get_graphql_content(response)
@@ -3180,12 +3178,12 @@ def test_address_query_as_service_account_with_permission(
assert data["country"]["code"] == address_other_country.country.code
-def test_address_query_as_service_account_without_permission(
- service_account_api_client, service_account, address_other_country
+def test_address_query_as_app_without_permission(
+ app_api_client, app, address_other_country
):
variables = {"id": graphene.Node.to_global_id("Address", address_other_country.pk)}
- response = service_account_api_client.post_graphql(ADDRESS_QUERY, variables)
+ response = app_api_client.post_graphql(ADDRESS_QUERY, variables)
assert_no_permission(response)
diff --git a/tests/api/test_account_permission_group.py b/tests/api/test_account_permission_group.py
index c960245c04..f0eb8a16e3 100644
--- a/tests/api/test_account_permission_group.py
+++ b/tests/api/test_account_permission_group.py
@@ -3,7 +3,7 @@ import pytest
from django.contrib.auth.models import Group
from saleor.account.models import User
-from saleor.core.permissions import AccountPermissions
+from saleor.core.permissions import AccountPermissions, AppPermission
from .utils import assert_no_permission, get_graphql_content
@@ -41,7 +41,7 @@ def test_permission_group_create_mutation(
"name": "New permission group",
"permissions": [
AccountPermissions.MANAGE_USERS.name,
- AccountPermissions.MANAGE_SERVICE_ACCOUNTS.name,
+ AppPermission.MANAGE_APPS.name,
],
}
}
@@ -77,7 +77,7 @@ def test_permission_group_create_mutation_no_permission_to_perform_mutation(
"name": "New permission group",
"permissions": [
AccountPermissions.MANAGE_USERS.name,
- AccountPermissions.MANAGE_SERVICE_ACCOUNTS.name,
+ AppPermission.MANAGE_APPS.name,
],
}
}
@@ -96,7 +96,7 @@ def test_permission_group_create_mutation_group_exists(
"name": permission_group_manage_users.name,
"permissions": [
AccountPermissions.MANAGE_USERS.name,
- AccountPermissions.MANAGE_SERVICE_ACCOUNTS.name,
+ AppPermission.MANAGE_APPS.name,
],
}
}
@@ -141,7 +141,7 @@ def test_permission_group_create_mutation_no_name(
"name": None,
"permissions": [
AccountPermissions.MANAGE_USERS.name,
- AccountPermissions.MANAGE_SERVICE_ACCOUNTS.name,
+ AppPermission.MANAGE_APPS.name,
],
}
}
@@ -184,7 +184,7 @@ def test_permission_group_update_mutation(
"id": graphene.Node.to_global_id("Group", group.id),
"input": {
"name": "New permission group",
- "permissions": [AccountPermissions.MANAGE_SERVICE_ACCOUNTS.name],
+ "permissions": [AppPermission.MANAGE_APPS.name],
},
}
response = staff_api_client.post_graphql(query, variables)
@@ -263,7 +263,7 @@ def test_permission_group_update_mutation_only_permissions(
variables = {
"id": graphene.Node.to_global_id("Group", group.id),
- "input": {"permissions": [AccountPermissions.MANAGE_SERVICE_ACCOUNTS.name]},
+ "input": {"permissions": [AppPermission.MANAGE_APPS.name]},
}
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
@@ -290,7 +290,7 @@ def test_permission_group_update_mutation_no_permission_to_perform_mutation(
"id": graphene.Node.to_global_id("Group", group.id),
"input": {
"name": "New permission group",
- "permissions": [AccountPermissions.MANAGE_SERVICE_ACCOUNTS.name],
+ "permissions": [AppPermission.MANAGE_APPS.name],
},
}
response = staff_api_client.post_graphql(query, variables)
diff --git a/tests/api/test_account_service_account.py b/tests/api/test_account_service_account.py
index 1c845c3fba..1850d6d9ea 100644
--- a/tests/api/test_account_service_account.py
+++ b/tests/api/test_account_service_account.py
@@ -2,7 +2,7 @@ import graphene
import pytest
from freezegun import freeze_time
-from saleor.account.models import ServiceAccount, ServiceAccountToken
+from saleor.app.models import App, AppToken
from saleor.graphql.core.enums import PermissionEnum
from .utils import assert_no_permission, get_graphql_content
@@ -53,7 +53,7 @@ def test_service_account_create_mutation(
content = get_graphql_content(response)
service_account_data = content["data"]["serviceAccountCreate"]["serviceAccount"]
default_token = content["data"]["serviceAccountCreate"]["authToken"]
- service_account = ServiceAccount.objects.get()
+ service_account = App.objects.get()
assert service_account_data["isActive"] == service_account.is_active
assert service_account_data["name"] == service_account.name
assert list(service_account.permissions.all()) == [permission_manage_products]
@@ -103,7 +103,7 @@ mutation ServiceAccountUpdate($id: ID!, $is_active: Boolean,
def test_service_account_update_mutation(
- service_account,
+ app,
permission_manage_service_accounts,
permission_manage_products,
permission_manage_users,
@@ -112,7 +112,7 @@ def test_service_account_update_mutation(
):
query = SERVICE_ACCOUNT_UPDATE_MUTATION
staff_user.user_permissions.add(permission_manage_service_accounts)
- id = graphene.Node.to_global_id("ServiceAccount", service_account.id)
+ id = graphene.Node.to_global_id("ServiceAccount", app.id)
variables = {
"id": id,
@@ -127,24 +127,22 @@ def test_service_account_update_mutation(
service_account_data = content["data"]["serviceAccountUpdate"]["serviceAccount"]
tokens_data = service_account_data["tokens"]
- service_account.refresh_from_db()
- tokens = service_account.tokens.all()
+ app.refresh_from_db()
+ tokens = app.tokens.all()
- assert service_account_data["isActive"] == service_account.is_active
- assert service_account.is_active is False
+ assert service_account_data["isActive"] == app.is_active
+ assert app.is_active is False
assert len(tokens_data) == 1
assert tokens_data[0]["authToken"] == tokens.get().auth_token[-4:]
- assert set(service_account.permissions.all()) == {
+ assert set(app.permissions.all()) == {
permission_manage_products,
permission_manage_users,
}
-def test_service_account_update_no_permission(
- service_account, staff_api_client, staff_user
-):
+def test_service_account_update_no_permission(app, staff_api_client, staff_user):
query = SERVICE_ACCOUNT_UPDATE_MUTATION
- id = graphene.Node.to_global_id("ServiceAccount", service_account.id)
+ id = graphene.Node.to_global_id("ServiceAccount", app.id)
variables = {
"id": id,
"is_active": False,
@@ -183,11 +181,11 @@ QUERY_SERVICE_ACCOUNTS_WITH_FILTER = """
def test_service_accounts_query(
staff_api_client,
permission_manage_service_accounts,
- service_account,
+ app,
service_account_filter,
count,
):
- second_service_account = ServiceAccount.objects.create(name="Simple service")
+ second_service_account = App.objects.create(name="Simple service")
second_service_account.is_active = False
second_service_account.tokens.create(name="default")
second_service_account.save()
@@ -237,9 +235,9 @@ def test_query_service_accounts_with_sort(
permission_manage_service_accounts,
):
with freeze_time("2018-05-31 12:00:01"):
- ServiceAccount.objects.create(name="google", is_active=True)
+ App.objects.create(name="google", is_active=True)
with freeze_time("2019-05-31 12:00:01"):
- ServiceAccount.objects.create(name="facebook", is_active=True)
+ App.objects.create(name="facebook", is_active=True)
variables = {"sort_by": service_accounts_sort}
staff_api_client.user.user_permissions.add(permission_manage_service_accounts)
response = staff_api_client.post_graphql(
@@ -253,7 +251,7 @@ def test_query_service_accounts_with_sort(
def test_service_accounts_query_no_permission(
- staff_api_client, permission_manage_users, permission_manage_staff, service_account
+ staff_api_client, permission_manage_users, permission_manage_staff, app
):
variables = {"filter": {}}
response = staff_api_client.post_graphql(
@@ -289,14 +287,11 @@ QUERY_SERVICE_ACCOUNT = """
def test_service_account_query(
- staff_api_client,
- permission_manage_service_accounts,
- permission_manage_staff,
- service_account,
+ staff_api_client, permission_manage_service_accounts, permission_manage_staff, app,
):
- service_account.permissions.add(permission_manage_staff)
+ app.permissions.add(permission_manage_staff)
- id = graphene.Node.to_global_id("ServiceAccount", service_account.id)
+ id = graphene.Node.to_global_id("ServiceAccount", app.id)
variables = {"id": id}
response = staff_api_client.post_graphql(
QUERY_SERVICE_ACCOUNT,
@@ -305,24 +300,24 @@ def test_service_account_query(
)
content = get_graphql_content(response)
- tokens = service_account.tokens.all()
+ tokens = app.tokens.all()
service_account_data = content["data"]["serviceAccount"]
tokens_data = service_account_data["tokens"]
assert tokens.count() == 1
assert tokens_data[0]["authToken"] == tokens.first().auth_token[-4:]
- assert service_account_data["isActive"] == service_account.is_active
+ assert service_account_data["isActive"] == app.is_active
assert service_account_data["permissions"] == [
{"code": "MANAGE_STAFF", "name": "Manage staff."}
]
def test_service_account_query_no_permission(
- staff_api_client, permission_manage_staff, permission_manage_users, service_account
+ staff_api_client, permission_manage_staff, permission_manage_users, app
):
- service_account.permissions.add(permission_manage_staff)
+ app.permissions.add(permission_manage_staff)
- id = graphene.Node.to_global_id("ServiceAccount", service_account.id)
+ id = graphene.Node.to_global_id("ServiceAccount", app.id)
variables = {"id": id}
response = staff_api_client.post_graphql(
QUERY_SERVICE_ACCOUNT, variables, permissions=[]
@@ -338,10 +333,7 @@ def test_service_account_query_no_permission(
def test_service_account_with_access_to_resources(
- service_account_api_client,
- service_account,
- permission_manage_orders,
- order_with_lines,
+ app_api_client, app, permission_manage_orders, order_with_lines,
):
query = """
query {
@@ -354,9 +346,9 @@ def test_service_account_with_access_to_resources(
}
}
"""
- response = service_account_api_client.post_graphql(query)
+ response = app_api_client.post_graphql(query)
assert_no_permission(response)
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
query, permissions=[permission_manage_orders]
)
get_graphql_content(response)
@@ -384,7 +376,7 @@ def test_service_account_token_create(
permission_manage_service_accounts, staff_api_client, staff_user
):
- service_account = ServiceAccount.objects.create(name="New_sa")
+ service_account = App.objects.create(name="New_sa")
query = SERVICE_ACCOUNT_TOKEN_CREATE_MUTATION
staff_user.user_permissions.add(permission_manage_service_accounts)
@@ -402,7 +394,7 @@ def test_service_account_token_create(
def test_service_account_token_create_no_permissions(staff_api_client, staff_user):
- service_account = ServiceAccount.objects.create(name="New_sa")
+ service_account = App.objects.create(name="New_sa")
query = SERVICE_ACCOUNT_TOKEN_CREATE_MUTATION
id = graphene.Node.to_global_id("ServiceAccount", service_account.id)
variables = {"name": "Default token", "serviceAccount": id}
@@ -427,26 +419,24 @@ SERVICE_ACCOUNT_TOKEN_DELETE_MUTATION = """
def test_service_account_token_delete(
- permission_manage_service_accounts, staff_api_client, staff_user, service_account
+ permission_manage_service_accounts, staff_api_client, staff_user, app
):
query = SERVICE_ACCOUNT_TOKEN_DELETE_MUTATION
- token = service_account.tokens.get()
+ token = app.tokens.get()
id = graphene.Node.to_global_id("ServiceAccountToken", token.id)
staff_user.user_permissions.add(permission_manage_service_accounts)
variables = {"id": id}
response = staff_api_client.post_graphql(query, variables=variables)
get_graphql_content(response)
- assert not ServiceAccountToken.objects.filter(id=token.id).first()
+ assert not AppToken.objects.filter(id=token.id).first()
-def test_service_account_token_delete_no_permissions(
- staff_api_client, staff_user, service_account
-):
+def test_service_account_token_delete_no_permissions(staff_api_client, staff_user, app):
query = SERVICE_ACCOUNT_TOKEN_DELETE_MUTATION
- token = service_account.tokens.get()
+ token = app.tokens.get()
id = graphene.Node.to_global_id("ServiceAccountToken", token.id)
variables = {"id": id}
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 1f4245d13f..f982012fc1 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -1807,10 +1807,10 @@ def test_query_anonymous_customer_checkout_as_staff_user(
def test_query_anonymous_customer_checkout_as_service_account(
- service_account_api_client, checkout, permission_manage_checkouts
+ app_api_client, checkout, permission_manage_checkouts
):
variables = {"token": str(checkout.token)}
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_CHECKOUT,
variables,
permissions=[permission_manage_checkouts],
@@ -1852,12 +1852,12 @@ def test_query_other_customer_checkout_as_customer(
def test_query_customer_checkout_as_staff_user(
- service_account_api_client, checkout, customer_user, permission_manage_checkouts
+ app_api_client, checkout, customer_user, permission_manage_checkouts
):
checkout.user = customer_user
checkout.save(update_fields=["user"])
variables = {"token": str(checkout.token)}
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_CHECKOUT,
variables,
permissions=[permission_manage_checkouts],
diff --git a/tests/api/test_meta_mutations.py b/tests/api/test_meta_mutations.py
index daefc93655..8f36bd693e 100644
--- a/tests/api/test_meta_mutations.py
+++ b/tests/api/test_meta_mutations.py
@@ -128,14 +128,14 @@ def test_add_public_metadata_for_customer_as_staff(
def test_add_public_metadata_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_id = graphene.Node.to_global_id("User", customer_user.pk)
# when
response = execute_update_public_metadata_for_item(
- service_account_api_client, permission_manage_users, customer_id, "User"
+ app_api_client, permission_manage_users, customer_id, "User"
)
# then
@@ -145,14 +145,14 @@ def test_add_public_metadata_for_customer_as_service_account(
def test_add_multiple_public_metadata_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_id = graphene.Node.to_global_id("User", customer_user.pk)
# when
response = execute_update_public_metadata_for_multiple_items(
- service_account_api_client, permission_manage_users, customer_id, "User"
+ app_api_client, permission_manage_users, customer_id, "User"
)
# then
@@ -180,14 +180,14 @@ def test_add_public_metadata_for_other_staff_as_staff(
def test_add_public_metadata_for_staff_as_service_account(
- service_account_api_client, permission_manage_staff, admin_user
+ app_api_client, permission_manage_staff, admin_user
):
# given
admin_id = graphene.Node.to_global_id("User", admin_user.pk)
# when
response = execute_update_public_metadata_for_item(
- service_account_api_client, permission_manage_staff, admin_id, "User"
+ app_api_client, permission_manage_staff, admin_id, "User"
)
# then
@@ -415,12 +415,10 @@ def test_add_public_metadata_for_product_variant(
def test_add_public_metadata_for_service_account(
- staff_api_client, permission_manage_service_accounts, service_account
+ staff_api_client, permission_manage_service_accounts, app
):
# given
- service_account_id = graphene.Node.to_global_id(
- "ServiceAccount", service_account.pk
- )
+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)
# when
response = execute_update_public_metadata_for_item(
@@ -432,7 +430,7 @@ def test_add_public_metadata_for_service_account(
# then
assert item_contains_proper_public_metadata(
- response["data"]["updateMetadata"]["item"], service_account, service_account_id
+ response["data"]["updateMetadata"]["item"], app, service_account_id
)
@@ -597,7 +595,7 @@ def test_delete_public_metadata_for_customer_as_staff(
def test_delete_public_metadata_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_user.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -606,7 +604,7 @@ def test_delete_public_metadata_for_customer_as_service_account(
# when
response = execute_clear_public_metadata_for_item(
- service_account_api_client, permission_manage_users, customer_id, "User"
+ app_api_client, permission_manage_users, customer_id, "User"
)
# then
@@ -616,7 +614,7 @@ def test_delete_public_metadata_for_customer_as_service_account(
def test_delete_multiple_public_metadata_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_user.store_value_in_metadata(
@@ -627,7 +625,7 @@ def test_delete_multiple_public_metadata_for_customer_as_service_account(
# when
response = execute_clear_public_metadata_for_multiple_items(
- service_account_api_client, permission_manage_users, customer_id, "User"
+ app_api_client, permission_manage_users, customer_id, "User"
)
# then
@@ -657,7 +655,7 @@ def test_delete_public_metadata_for_other_staff_as_staff(
def test_delete_public_metadata_for_staff_as_service_account(
- service_account_api_client, permission_manage_staff, admin_user
+ app_api_client, permission_manage_staff, admin_user
):
# given
admin_user.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -666,7 +664,7 @@ def test_delete_public_metadata_for_staff_as_service_account(
# when
response = execute_clear_public_metadata_for_item(
- service_account_api_client, permission_manage_staff, admin_id, "User"
+ app_api_client, permission_manage_staff, admin_id, "User"
)
# then
@@ -920,12 +918,10 @@ def test_delete_public_metadata_for_product_variant(
def test_delete_public_metadata_for_service_account(
- staff_api_client, permission_manage_service_accounts, service_account
+ staff_api_client, permission_manage_service_accounts, app
):
# given
- service_account_id = graphene.Node.to_global_id(
- "ServiceAccount", service_account.pk
- )
+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)
# when
response = execute_clear_public_metadata_for_item(
@@ -937,7 +933,7 @@ def test_delete_public_metadata_for_service_account(
# then
assert item_without_public_metadata(
- response["data"]["deleteMetadata"]["item"], service_account, service_account_id
+ response["data"]["deleteMetadata"]["item"], app, service_account_id
)
@@ -1129,14 +1125,14 @@ def test_add_private_metadata_for_customer_as_staff(
def test_add_private_metadata_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_id = graphene.Node.to_global_id("User", customer_user.pk)
# when
response = execute_update_private_metadata_for_item(
- service_account_api_client, permission_manage_users, customer_id, "User"
+ app_api_client, permission_manage_users, customer_id, "User"
)
# then
@@ -1146,14 +1142,14 @@ def test_add_private_metadata_for_customer_as_service_account(
def test_add_multiple_private_metadata_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_id = graphene.Node.to_global_id("User", customer_user.pk)
# when
response = execute_update_private_metadata_for_multiple_items(
- service_account_api_client, permission_manage_users, customer_id, "User"
+ app_api_client, permission_manage_users, customer_id, "User"
)
# then
@@ -1181,14 +1177,14 @@ def test_add_private_metadata_for_other_staff_as_staff(
def test_add_private_metadata_for_staff_as_service_account(
- service_account_api_client, permission_manage_staff, admin_user
+ app_api_client, permission_manage_staff, admin_user
):
# given
admin_id = graphene.Node.to_global_id("User", admin_user.pk)
# when
response = execute_update_private_metadata_for_item(
- service_account_api_client, permission_manage_staff, admin_id, "User"
+ app_api_client, permission_manage_staff, admin_id, "User"
)
# then
@@ -1426,12 +1422,10 @@ def test_add_private_metadata_for_product_variant(
def test_add_private_metadata_for_service_account(
- staff_api_client, permission_manage_service_accounts, service_account
+ staff_api_client, permission_manage_service_accounts, app
):
# given
- service_account_id = graphene.Node.to_global_id(
- "ServiceAccount", service_account.pk
- )
+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)
# when
response = execute_update_private_metadata_for_item(
@@ -1443,9 +1437,7 @@ def test_add_private_metadata_for_service_account(
# then
assert item_contains_proper_private_metadata(
- response["data"]["updatePrivateMetadata"]["item"],
- service_account,
- service_account_id,
+ response["data"]["updatePrivateMetadata"]["item"], app, service_account_id,
)
@@ -1618,7 +1610,7 @@ def test_delete_private_metadata_for_customer_as_staff(
def test_delete_private_metadata_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_user.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -1627,7 +1619,7 @@ def test_delete_private_metadata_for_customer_as_service_account(
# when
response = execute_clear_private_metadata_for_item(
- service_account_api_client, permission_manage_users, customer_id, "User"
+ app_api_client, permission_manage_users, customer_id, "User"
)
# then
@@ -1637,7 +1629,7 @@ def test_delete_private_metadata_for_customer_as_service_account(
def test_delete_multiple_private_metadata_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_user.store_value_in_metadata(
@@ -1648,7 +1640,7 @@ def test_delete_multiple_private_metadata_for_customer_as_service_account(
# when
response = execute_clear_private_metadata_for_multiple_items(
- service_account_api_client, permission_manage_users, customer_id, "User"
+ app_api_client, permission_manage_users, customer_id, "User"
)
# then
@@ -1678,7 +1670,7 @@ def test_delete_private_metadata_for_other_staff_as_staff(
def test_delete_private_metadata_for_staff_as_service_account(
- service_account_api_client, permission_manage_staff, admin_user
+ app_api_client, permission_manage_staff, admin_user
):
# given
admin_user.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -1687,7 +1679,7 @@ def test_delete_private_metadata_for_staff_as_service_account(
# when
response = execute_clear_private_metadata_for_item(
- service_account_api_client, permission_manage_staff, admin_id, "User"
+ app_api_client, permission_manage_staff, admin_id, "User"
)
# then
@@ -1955,12 +1947,10 @@ def test_delete_private_metadata_for_product_variant(
def test_delete_private_metadata_for_service_account(
- staff_api_client, permission_manage_service_accounts, service_account
+ staff_api_client, permission_manage_service_accounts, app
):
# given
- service_account_id = graphene.Node.to_global_id(
- "ServiceAccount", service_account.pk
- )
+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)
# when
response = execute_clear_private_metadata_for_item(
@@ -1972,9 +1962,7 @@ def test_delete_private_metadata_for_service_account(
# then
assert item_without_private_metadata(
- response["data"]["deletePrivateMetadata"]["item"],
- service_account,
- service_account_id,
+ response["data"]["deletePrivateMetadata"]["item"], app, service_account_id,
)
diff --git a/tests/api/test_meta_queries.py b/tests/api/test_meta_queries.py
index 810c9506a7..c9695ede46 100644
--- a/tests/api/test_meta_queries.py
+++ b/tests/api/test_meta_queries.py
@@ -86,7 +86,7 @@ def test_query_public_meta_for_customer_as_staff(
def test_query_public_meta_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_user.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -94,7 +94,7 @@ def test_query_public_meta_for_customer_as_service_account(
variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_USER_PUBLIC_META, variables, [permission_manage_users]
)
content = get_graphql_content(response)
@@ -126,7 +126,7 @@ def test_query_public_meta_for_staff_as_other_staff(
def test_query_public_meta_for_staff_as_service_account(
- service_account_api_client, permission_manage_staff, admin_user
+ app_api_client, permission_manage_staff, admin_user
):
# given
admin_user.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -134,7 +134,7 @@ def test_query_public_meta_for_staff_as_service_account(
variables = {"id": graphene.Node.to_global_id("User", admin_user.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_USER_PUBLIC_META, variables, [permission_manage_staff]
)
content = get_graphql_content(response)
@@ -232,7 +232,7 @@ def test_query_public_meta_for_checkout_as_staff(
def test_query_public_meta_for_checkout_as_service_account(
- service_account_api_client, checkout, customer_user, permission_manage_checkouts
+ app_api_client, checkout, customer_user, permission_manage_checkouts
):
# given
checkout.user = customer_user
@@ -241,7 +241,7 @@ def test_query_public_meta_for_checkout_as_service_account(
variables = {"token": checkout.pk}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_CHECKOUT_PUBLIC_META,
variables,
[permission_manage_checkouts],
@@ -325,7 +325,7 @@ def test_query_public_meta_for_order_by_token_as_staff(
def test_query_public_meta_for_order_by_token_as_service_account(
- service_account_api_client, order, customer_user, permission_manage_orders
+ app_api_client, order, customer_user, permission_manage_orders
):
# given
order.user = customer_user
@@ -334,7 +334,7 @@ def test_query_public_meta_for_order_by_token_as_service_account(
variables = {"token": order.token}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_ORDER_BY_TOKEN_PUBLIC_META,
variables,
[permission_manage_orders],
@@ -410,7 +410,7 @@ def test_query_public_meta_for_order_as_staff(
def test_query_public_meta_for_order_as_service_account(
- service_account_api_client, order, customer_user, permission_manage_orders
+ app_api_client, order, customer_user, permission_manage_orders
):
# given
order.user = customer_user
@@ -419,7 +419,7 @@ def test_query_public_meta_for_order_as_service_account(
variables = {"id": graphene.Node.to_global_id("Order", order.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_ORDER_PUBLIC_META,
variables,
[permission_manage_orders],
@@ -495,7 +495,7 @@ def test_query_public_meta_for_draft_order_as_staff(
def test_query_public_meta_for_draft_order_as_service_account(
- service_account_api_client, draft_order, customer_user, permission_manage_orders
+ app_api_client, draft_order, customer_user, permission_manage_orders
):
# given
draft_order.user = customer_user
@@ -504,7 +504,7 @@ def test_query_public_meta_for_draft_order_as_service_account(
variables = {"id": graphene.Node.to_global_id("Order", draft_order.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_ORDER_PUBLIC_META,
variables,
[permission_manage_orders],
@@ -599,7 +599,7 @@ def test_query_public_meta_for_fulfillment_as_staff(
def test_query_public_meta_for_fulfillment_as_service_account(
- service_account_api_client, fulfilled_order, customer_user, permission_manage_orders
+ app_api_client, fulfilled_order, customer_user, permission_manage_orders
):
# given
fulfillment = fulfilled_order.fulfillments.first()
@@ -610,7 +610,7 @@ def test_query_public_meta_for_fulfillment_as_service_account(
variables = {"token": fulfilled_order.token}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_FULFILLMENT_PUBLIC_META,
variables,
[permission_manage_orders],
@@ -692,7 +692,7 @@ def test_query_public_meta_for_attribute_as_staff(
def test_query_public_meta_for_attribute_as_service_account(
- service_account_api_client, color_attribute, permission_manage_products
+ app_api_client, color_attribute, permission_manage_products
):
# given
color_attribute.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -700,7 +700,7 @@ def test_query_public_meta_for_attribute_as_service_account(
variables = {"id": graphene.Node.to_global_id("Attribute", color_attribute.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_ATTRIBUTE_PUBLIC_META,
variables,
[permission_manage_products],
@@ -782,7 +782,7 @@ def test_query_public_meta_for_category_as_staff(
def test_query_public_meta_for_category_as_service_account(
- service_account_api_client, category, permission_manage_products
+ app_api_client, category, permission_manage_products
):
# given
category.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -790,7 +790,7 @@ def test_query_public_meta_for_category_as_service_account(
variables = {"id": graphene.Node.to_global_id("Category", category.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_CATEGORY_PUBLIC_META,
variables,
[permission_manage_products],
@@ -872,7 +872,7 @@ def test_query_public_meta_for_collection_as_staff(
def test_query_public_meta_for_collection_as_service_account(
- service_account_api_client, collection, permission_manage_products
+ app_api_client, collection, permission_manage_products
):
# given
collection.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -880,7 +880,7 @@ def test_query_public_meta_for_collection_as_service_account(
variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_COLLECTION_PUBLIC_META,
variables,
[permission_manage_products],
@@ -960,7 +960,7 @@ def test_query_public_meta_for_digital_content_as_staff(
def test_query_public_meta_for_digital_content_as_service_account(
- service_account_api_client, digital_content, permission_manage_products
+ app_api_client, digital_content, permission_manage_products
):
# given
digital_content.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -968,7 +968,7 @@ def test_query_public_meta_for_digital_content_as_service_account(
variables = {"id": graphene.Node.to_global_id("DigitalContent", digital_content.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_DIGITAL_CONTENT_PUBLIC_META,
variables,
[permission_manage_products],
@@ -1050,7 +1050,7 @@ def test_query_public_meta_for_product_as_staff(
def test_query_public_meta_for_product_as_service_account(
- service_account_api_client, product, permission_manage_products
+ app_api_client, product, permission_manage_products
):
# given
product.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -1058,7 +1058,7 @@ def test_query_public_meta_for_product_as_service_account(
variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_PRODUCT_PUBLIC_META,
variables,
[permission_manage_products],
@@ -1140,7 +1140,7 @@ def test_query_public_meta_for_product_type_as_staff(
def test_query_public_meta_for_product_type_as_service_account(
- service_account_api_client, product_type, permission_manage_products
+ app_api_client, product_type, permission_manage_products
):
# given
product_type.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -1148,7 +1148,7 @@ def test_query_public_meta_for_product_type_as_service_account(
variables = {"id": graphene.Node.to_global_id("ProductType", product_type.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_PRODUCT_TYPE_PUBLIC_META,
variables,
[permission_manage_products],
@@ -1232,7 +1232,7 @@ def test_query_public_meta_for_product_variant_as_staff(
def test_query_public_meta_for_product_variant_as_service_account(
- service_account_api_client, variant, permission_manage_products
+ app_api_client, variant, permission_manage_products
):
# given
variant.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
@@ -1240,7 +1240,7 @@ def test_query_public_meta_for_product_variant_as_service_account(
variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_PRODUCT_VARIANT_PUBLIC_META,
variables,
[permission_manage_products],
@@ -1266,11 +1266,9 @@ QUERY_SERVICE_ACCOUNT_PUBLIC_META = """
"""
-def test_query_public_meta_for_service_account_as_anonymous_user(
- api_client, service_account
-):
+def test_query_public_meta_for_service_account_as_anonymous_user(api_client, app):
# given
- variables = {"id": graphene.Node.to_global_id("ServiceAccount", service_account.pk)}
+ variables = {"id": graphene.Node.to_global_id("ServiceAccount", app.pk)}
# when
response = api_client.post_graphql(QUERY_SERVICE_ACCOUNT_PUBLIC_META, variables)
@@ -1279,11 +1277,9 @@ def test_query_public_meta_for_service_account_as_anonymous_user(
assert_no_permission(response)
-def test_query_public_meta_for_service_account_as_customer(
- user_api_client, service_account
-):
+def test_query_public_meta_for_service_account_as_customer(user_api_client, app):
# given
- variables = {"id": graphene.Node.to_global_id("ServiceAccount", service_account.pk)}
+ variables = {"id": graphene.Node.to_global_id("ServiceAccount", app.pk)}
# when
response = user_api_client.post_graphql(
@@ -1295,12 +1291,12 @@ def test_query_public_meta_for_service_account_as_customer(
def test_query_public_meta_for_service_account_as_staff(
- staff_api_client, service_account, permission_manage_service_accounts
+ staff_api_client, app, permission_manage_service_accounts
):
# given
- service_account.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
- service_account.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("ServiceAccount", service_account.pk)}
+ app.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ app.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("ServiceAccount", app.pk)}
# when
response = staff_api_client.post_graphql(
@@ -1318,15 +1314,15 @@ def test_query_public_meta_for_service_account_as_staff(
def test_query_public_meta_for_service_account_as_service_account(
- service_account_api_client, service_account, permission_manage_service_accounts
+ app_api_client, app, permission_manage_service_accounts
):
# given
- service_account.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
- service_account.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("ServiceAccount", service_account.pk)}
+ app.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ app.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("ServiceAccount", app.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_SERVICE_ACCOUNT_PUBLIC_META,
variables,
[permission_manage_service_accounts],
@@ -1429,7 +1425,7 @@ def test_query_private_meta_for_customer_as_staff(
def test_query_private_meta_for_customer_as_service_account(
- service_account_api_client, permission_manage_users, customer_user
+ app_api_client, permission_manage_users, customer_user
):
# given
customer_user.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -1437,7 +1433,7 @@ def test_query_private_meta_for_customer_as_service_account(
variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_USER_PRIVATE_META, variables, [permission_manage_users]
)
content = get_graphql_content(response)
@@ -1469,7 +1465,7 @@ def test_query_private_meta_for_staff_as_other_staff(
def test_query_private_meta_for_staff_as_service_account(
- service_account_api_client, permission_manage_staff, admin_user
+ app_api_client, permission_manage_staff, admin_user
):
# given
admin_user.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -1477,7 +1473,7 @@ def test_query_private_meta_for_staff_as_service_account(
variables = {"id": graphene.Node.to_global_id("User", admin_user.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_USER_PRIVATE_META, variables, [permission_manage_staff]
)
content = get_graphql_content(response)
@@ -1565,7 +1561,7 @@ def test_query_private_meta_for_checkout_as_staff(
def test_query_private_meta_for_checkout_as_service_account(
- service_account_api_client, checkout, customer_user, permission_manage_checkouts
+ app_api_client, checkout, customer_user, permission_manage_checkouts
):
# given
checkout.user = customer_user
@@ -1574,7 +1570,7 @@ def test_query_private_meta_for_checkout_as_service_account(
variables = {"token": checkout.pk}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_CHECKOUT_PRIVATE_META,
variables,
[permission_manage_checkouts],
@@ -1651,7 +1647,7 @@ def test_query_private_meta_for_order_by_token_as_staff(
def test_query_private_meta_for_order_by_token_as_service_account(
- service_account_api_client, order, customer_user, permission_manage_orders
+ app_api_client, order, customer_user, permission_manage_orders
):
# given
order.user = customer_user
@@ -1660,7 +1656,7 @@ def test_query_private_meta_for_order_by_token_as_service_account(
variables = {"token": order.token}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_ORDER_BY_TOKEN_PRIVATE_META,
variables,
[permission_manage_orders],
@@ -1735,7 +1731,7 @@ def test_query_private_meta_for_order_as_staff(
def test_query_private_meta_for_order_as_service_account(
- service_account_api_client, order, customer_user, permission_manage_orders
+ app_api_client, order, customer_user, permission_manage_orders
):
# given
order.user = customer_user
@@ -1744,7 +1740,7 @@ def test_query_private_meta_for_order_as_service_account(
variables = {"id": graphene.Node.to_global_id("Order", order.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_ORDER_PRIVATE_META,
variables,
[permission_manage_orders],
@@ -1820,7 +1816,7 @@ def test_query_private_meta_for_draft_order_as_staff(
def test_query_private_meta_for_draft_order_as_service_account(
- service_account_api_client, draft_order, customer_user, permission_manage_orders
+ app_api_client, draft_order, customer_user, permission_manage_orders
):
# given
draft_order.user = customer_user
@@ -1829,7 +1825,7 @@ def test_query_private_meta_for_draft_order_as_service_account(
variables = {"id": graphene.Node.to_global_id("Order", draft_order.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_ORDER_PRIVATE_META,
variables,
[permission_manage_orders],
@@ -1912,7 +1908,7 @@ def test_query_private_meta_for_fulfillment_as_staff(
def test_query_private_meta_for_fulfillment_as_service_account(
- service_account_api_client, fulfilled_order, customer_user, permission_manage_orders
+ app_api_client, fulfilled_order, customer_user, permission_manage_orders
):
# given
fulfillment = fulfilled_order.fulfillments.first()
@@ -1923,7 +1919,7 @@ def test_query_private_meta_for_fulfillment_as_service_account(
variables = {"token": fulfilled_order.token}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_FULFILLMENT_PRIVATE_META,
variables,
[permission_manage_orders],
@@ -1997,7 +1993,7 @@ def test_query_private_meta_for_attribute_as_staff(
def test_query_private_meta_for_attribute_as_service_account(
- service_account_api_client, color_attribute, permission_manage_products
+ app_api_client, color_attribute, permission_manage_products
):
# given
color_attribute.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -2005,7 +2001,7 @@ def test_query_private_meta_for_attribute_as_service_account(
variables = {"id": graphene.Node.to_global_id("Attribute", color_attribute.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_ATTRIBUTE_PRIVATE_META,
variables,
[permission_manage_products],
@@ -2077,7 +2073,7 @@ def test_query_private_meta_for_category_as_staff(
def test_query_private_meta_for_category_as_service_account(
- service_account_api_client, category, permission_manage_products
+ app_api_client, category, permission_manage_products
):
# given
category.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -2085,7 +2081,7 @@ def test_query_private_meta_for_category_as_service_account(
variables = {"id": graphene.Node.to_global_id("Category", category.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_CATEGORY_PRIVATE_META,
variables,
[permission_manage_products],
@@ -2157,7 +2153,7 @@ def test_query_private_meta_for_collection_as_staff(
def test_query_private_meta_for_collection_as_service_account(
- service_account_api_client, collection, permission_manage_products
+ app_api_client, collection, permission_manage_products
):
# given
collection.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -2165,7 +2161,7 @@ def test_query_private_meta_for_collection_as_service_account(
variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_COLLECTION_PRIVATE_META,
variables,
[permission_manage_products],
@@ -2245,7 +2241,7 @@ def test_query_private_meta_for_digital_content_as_staff(
def test_query_private_meta_for_digital_content_as_service_account(
- service_account_api_client, digital_content, permission_manage_products
+ app_api_client, digital_content, permission_manage_products
):
# given
digital_content.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -2253,7 +2249,7 @@ def test_query_private_meta_for_digital_content_as_service_account(
variables = {"id": graphene.Node.to_global_id("DigitalContent", digital_content.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_DIGITAL_CONTENT_PRIVATE_META,
variables,
[permission_manage_products],
@@ -2325,7 +2321,7 @@ def test_query_private_meta_for_product_as_staff(
def test_query_private_meta_for_product_as_service_account(
- service_account_api_client, product, permission_manage_products
+ app_api_client, product, permission_manage_products
):
# given
product.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -2333,7 +2329,7 @@ def test_query_private_meta_for_product_as_service_account(
variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_PRODUCT_PRIVATE_META,
variables,
[permission_manage_products],
@@ -2407,7 +2403,7 @@ def test_query_private_meta_for_product_type_as_staff(
def test_query_private_meta_for_product_type_as_service_account(
- service_account_api_client, product_type, permission_manage_products
+ app_api_client, product_type, permission_manage_products
):
# given
product_type.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -2415,7 +2411,7 @@ def test_query_private_meta_for_product_type_as_service_account(
variables = {"id": graphene.Node.to_global_id("ProductType", product_type.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_PRODUCT_TYPE_PRIVATE_META,
variables,
[permission_manage_products],
@@ -2493,7 +2489,7 @@ def test_query_private_meta_for_product_variant_as_staff(
def test_query_private_meta_for_product_variant_as_service_account(
- service_account_api_client, variant, permission_manage_products
+ app_api_client, variant, permission_manage_products
):
# given
variant.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
@@ -2501,7 +2497,7 @@ def test_query_private_meta_for_product_variant_as_service_account(
variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_PRODUCT_VARIANT_PRIVATE_META,
variables,
[permission_manage_products],
@@ -2527,11 +2523,9 @@ QUERY_SERVICE_ACCOUNT_PRIVATE_META = """
"""
-def test_query_private_meta_for_service_account_as_anonymous_user(
- api_client, service_account
-):
+def test_query_private_meta_for_service_account_as_anonymous_user(api_client, app):
# given
- variables = {"id": graphene.Node.to_global_id("ServiceAccount", service_account.pk)}
+ variables = {"id": graphene.Node.to_global_id("ServiceAccount", app.pk)}
# when
response = api_client.post_graphql(QUERY_SERVICE_ACCOUNT_PRIVATE_META, variables)
@@ -2540,11 +2534,9 @@ def test_query_private_meta_for_service_account_as_anonymous_user(
assert_no_permission(response)
-def test_query_private_meta_for_service_account_as_customer(
- user_api_client, service_account
-):
+def test_query_private_meta_for_service_account_as_customer(user_api_client, app):
# given
- variables = {"id": graphene.Node.to_global_id("ServiceAccount", service_account.pk)}
+ variables = {"id": graphene.Node.to_global_id("ServiceAccount", app.pk)}
# when
response = user_api_client.post_graphql(
@@ -2556,12 +2548,12 @@ def test_query_private_meta_for_service_account_as_customer(
def test_query_private_meta_for_service_account_as_staff(
- staff_api_client, service_account, permission_manage_service_accounts
+ staff_api_client, app, permission_manage_service_accounts
):
# given
- service_account.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
- service_account.save(update_fields=["private_metadata"])
- variables = {"id": graphene.Node.to_global_id("ServiceAccount", service_account.pk)}
+ app.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ app.save(update_fields=["private_metadata"])
+ variables = {"id": graphene.Node.to_global_id("ServiceAccount", app.pk)}
# when
response = staff_api_client.post_graphql(
@@ -2579,15 +2571,15 @@ def test_query_private_meta_for_service_account_as_staff(
def test_query_private_meta_for_service_account_as_service_account(
- service_account_api_client, service_account, permission_manage_service_accounts
+ app_api_client, app, permission_manage_service_accounts
):
# given
- service_account.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
- service_account.save(update_fields=["private_metadata"])
- variables = {"id": graphene.Node.to_global_id("ServiceAccount", service_account.pk)}
+ app.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ app.save(update_fields=["private_metadata"])
+ variables = {"id": graphene.Node.to_global_id("ServiceAccount", app.pk)}
# when
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_SERVICE_ACCOUNT_PRIVATE_META,
variables,
[permission_manage_service_accounts],
diff --git a/tests/api/test_middleware.py b/tests/api/test_middleware.py
index 29f37e6db1..e494315006 100644
--- a/tests/api/test_middleware.py
+++ b/tests/api/test_middleware.py
@@ -2,18 +2,16 @@ from unittest.mock import Mock
from django.urls import reverse
-from saleor.graphql.middleware import service_account_middleware
+from saleor.graphql.middleware import app_middleware
-def test_service_account_middleware_accepts_api_requests(service_account, rf):
+def test_service_account_middleware_accepts_api_requests(app, rf):
# Retrieve sample request object
request = rf.get(reverse("api"))
- token = service_account.tokens.first().auth_token
+ token = app.tokens.first().auth_token
request.META = {"HTTP_AUTHORIZATION": f"Bearer {token}"}
- service_account_middleware(
- lambda root, info: info.context, Mock(), Mock(context=request)
- )
+ app_middleware(lambda root, info: info.context, Mock(), Mock(context=request))
- assert request.service_account == service_account
+ assert request.app == app
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index 67b1a866e1..5405ea06cb 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -504,7 +504,7 @@ def test_non_staff_user_cannot_only_see_his_order(user_api_client, order):
def test_query_order_as_service_account(
- service_account_api_client, permission_manage_orders, order
+ app_api_client, permission_manage_orders, order
):
query = """
query OrderQuery($id: ID!) {
@@ -515,7 +515,7 @@ def test_query_order_as_service_account(
"""
ID = graphene.Node.to_global_id("Order", order.id)
variables = {"id": ID}
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index a2a238e206..f452a9132f 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -112,9 +112,9 @@ def test_fetch_all_products(user_api_client, product):
def test_fetch_all_products_service_account(
- service_account_api_client, unavailable_product, permission_manage_products,
+ app_api_client, unavailable_product, permission_manage_products,
):
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
QUERY_FETCH_ALL_PRODUCTS,
permissions=[permission_manage_products],
check_no_permissions=False,
diff --git a/tests/api/test_shop.py b/tests/api/test_shop.py
index c42e386341..0f6e599e86 100644
--- a/tests/api/test_shop.py
+++ b/tests/api/test_shop.py
@@ -179,7 +179,7 @@ def test_query_permissions(staff_api_client):
}
}
"""
- permissions_codenames = get_permissions_codename()
+ permissions_codenames = set(get_permissions_codename())
response = staff_api_client.post_graphql(query)
content = get_graphql_content(response)
data = content["data"]["shop"]
diff --git a/tests/api/test_webhook.py b/tests/api/test_webhook.py
index 27c012eaa9..4e8b7805bd 100644
--- a/tests/api/test_webhook.py
+++ b/tests/api/test_webhook.py
@@ -3,7 +3,7 @@ from unittest.mock import patch
import graphene
import pytest
-from saleor.account.models import ServiceAccount
+from saleor.app.models import App
from saleor.graphql.webhook.enums import (
WebhookEventTypeEnum,
WebhookSampleEventTypeEnum,
@@ -29,9 +29,7 @@ WEBHOOK_CREATE_BY_SERVICE_ACCOUNT = """
"""
-def test_webhook_create_by_service_account(
- service_account_api_client, permission_manage_orders
-):
+def test_webhook_create_by_service_account(app_api_client, permission_manage_orders):
query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT
variables = {
"name": "New integration",
@@ -41,7 +39,7 @@ def test_webhook_create_by_service_account(
WebhookEventTypeEnum.ORDER_CREATED.name,
],
}
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
query,
variables=variables,
permissions=[permission_manage_orders],
@@ -57,10 +55,10 @@ def test_webhook_create_by_service_account(
def test_webhook_create_inactive_service_account(
- service_account_api_client, service_account, permission_manage_orders
+ app_api_client, app, permission_manage_orders
):
- service_account.is_active = False
- service_account.save()
+ app.is_active = False
+ app.save()
query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT
variables = {
"target_url": "https://www.example.com",
@@ -68,31 +66,27 @@ def test_webhook_create_inactive_service_account(
"name": "",
}
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
query, variables=variables, permissions=[permission_manage_orders]
)
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
+def test_webhook_create_without_service_account(app_api_client, app):
+ app_api_client.app = None
+ app_api_client.app_token = None
query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT
variables = {
"target_url": "https://www.example.com",
"events": [WebhookEventTypeEnum.ORDER_CREATED.name],
"name": "",
}
- response = service_account_api_client.post_graphql(query, variables=variables)
+ response = app_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()
+def test_webhook_create_service_account_doesnt_exist(app_api_client, app):
+ app.delete()
query = WEBHOOK_CREATE_BY_SERVICE_ACCOUNT
variables = {
@@ -100,7 +94,7 @@ def test_webhook_create_service_account_doesnt_exist(
"events": [WebhookEventTypeEnum.ORDER_CREATED.name],
"name": "",
}
- response = service_account_api_client.post_graphql(query, variables=variables)
+ response = app_api_client.post_graphql(query, variables=variables)
assert_no_permission(response)
@@ -122,16 +116,11 @@ WEBHOOK_CREATE_BY_STAFF = """
def test_webhook_create_by_staff(
- staff_api_client,
- service_account,
- permission_manage_webhooks,
- permission_manage_orders,
+ staff_api_client, app, permission_manage_webhooks, permission_manage_orders,
):
query = WEBHOOK_CREATE_BY_STAFF
- service_account.permissions.add(permission_manage_orders)
- service_account_id = graphene.Node.to_global_id(
- "ServiceAccount", service_account.pk
- )
+ app.permissions.add(permission_manage_orders)
+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)
variables = {
"target_url": "https://www.example.com",
"events": [WebhookEventTypeEnum.ORDER_CREATED.name],
@@ -142,20 +131,16 @@ def test_webhook_create_by_staff(
get_graphql_content(response)
new_webhook = Webhook.objects.get()
assert new_webhook.target_url == "https://www.example.com"
- assert new_webhook.service_account == service_account
+ assert new_webhook.app == app
events = new_webhook.events.all()
assert len(events) == 1
assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.value
-def test_webhook_create_by_staff_with_inactive_service_account(
- staff_api_client, service_account
-):
- service_account.is_active = False
+def test_webhook_create_by_staff_with_inactive_service_account(staff_api_client, app):
+ app.is_active = False
query = WEBHOOK_CREATE_BY_STAFF
- service_account_id = graphene.Node.to_global_id(
- "ServiceAccount", service_account.pk
- )
+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)
variables = {
"target_url": "https://www.example.com",
"events": [WebhookEventTypeEnum.ORDER_CREATED.name],
@@ -166,11 +151,9 @@ def test_webhook_create_by_staff_with_inactive_service_account(
assert Webhook.objects.count() == 0
-def test_webhook_create_by_staff_without_permission(staff_api_client, service_account):
+def test_webhook_create_by_staff_without_permission(staff_api_client, app):
query = WEBHOOK_CREATE_BY_STAFF
- service_account_id = graphene.Node.to_global_id(
- "ServiceAccount", service_account.pk
- )
+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)
variables = {
"target_url": "https://www.example.com",
"events": [WebhookEventTypeEnum.ORDER_CREATED.name],
@@ -194,68 +177,60 @@ WEBHOOK_DELETE_BY_SERVICE_ACCOUNT = """
"""
-def test_webhook_delete_by_service_account(service_account_api_client, webhook):
+def test_webhook_delete_by_service_account(app_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)
+ response = app_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
+def test_webhook_delete_by_service_account_with_wrong_webhook(app_api_client, webhook):
+ second_app = App.objects.create(name="second")
+ webhook.app = second_app
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)
+ response = app_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
-):
+def test_webhook_delete_by_service_account_wrong_webhook(app_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)
+ response = app_api_client.post_graphql(query, variables=variables)
content = get_graphql_content(response)
errors = content["data"]["webhookDelete"]["webhookErrors"]
assert errors[0]["code"] == "GRAPHQL_ERROR"
-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()
+def test_webhook_delete_by_inactive_service_account(app_api_client, webhook):
+ app = webhook.app
+ app.is_active = False
+ app.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)
+ response = app_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()
+def test_webhook_delete_service_account_doesnt_exist(app_api_client, app):
+ app.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)
+ response = app_api_client.post_graphql(query, variables=variables)
assert_no_permission(response)
@@ -278,9 +253,7 @@ WEBHOOK_UPDATE = """
"""
-def test_webhook_update_not_allowed_by_service_account(
- service_account_api_client, service_account, webhook
-):
+def test_webhook_update_not_allowed_by_service_account(app_api_client, app, webhook):
query = WEBHOOK_UPDATE
webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
variables = {
@@ -288,12 +261,12 @@ def test_webhook_update_not_allowed_by_service_account(
"events": [WebhookEventTypeEnum.ORDER_CREATED.name],
"is_active": False,
}
- response = service_account_api_client.post_graphql(query, variables=variables)
+ response = app_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
+ staff_api_client, app, webhook, permission_manage_webhooks
):
query = WEBHOOK_UPDATE
webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
@@ -315,9 +288,7 @@ def test_webhook_update_by_staff(
assert events[0].event_type == WebhookEventTypeEnum.CUSTOMER_CREATED.value
-def test_webhook_update_by_staff_without_permission(
- staff_api_client, service_account, webhook
-):
+def test_webhook_update_by_staff_without_permission(staff_api_client, app, webhook):
query = WEBHOOK_UPDATE
webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
variables = {
@@ -371,18 +342,16 @@ def test_query_webhooks_by_staff_without_permission(staff_api_client, webhook):
assert_no_permission(response)
-def test_query_webhooks_by_service_account(service_account_api_client, webhook):
- second_sa = ServiceAccount.objects.create(
- name="Sample service account", is_active=True
- )
+def test_query_webhooks_by_service_account(app_api_client, webhook):
+ second_app = App.objects.create(name="Sample app", is_active=True)
second_webhook = Webhook.objects.create(
- service_account=second_sa, target_url="http://www.example.com/test"
+ app=second_app, target_url="http://www.example.com/test"
)
second_webhook.events.create(event_type="order_created")
query = QUERY_WEBHOOKS
variables = {"filter": {}}
- response = service_account_api_client.post_graphql(query, variables=variables)
+ response = app_api_client.post_graphql(query, variables=variables)
content = get_graphql_content(response)
webhooks = content["data"]["webhooks"]["edges"]
assert len(webhooks) == 1
@@ -403,11 +372,9 @@ def test_query_webhooks_by_service_account(service_account_api_client, webhook):
def test_query_webhooks_with_filters(
webhook_filter, staff_api_client, webhook, permission_manage_webhooks
):
- second_sa = ServiceAccount.objects.create(
- name="Second sample service account", is_active=False
- )
+ second_app = App.objects.create(name="Second sample app account", is_active=False)
second_webhook = Webhook.objects.create(
- service_account=second_sa,
+ app=second_app,
target_url="http://www.example.com/test",
is_active=False,
name="Sample webhook",
@@ -460,24 +427,16 @@ QUERY_WEBHOOKS_WITH_SORT = """
def test_query_webhooks_with_sort(
webhooks_sort, result_order, staff_api_client, permission_manage_webhooks
):
- backupAccount = ServiceAccount.objects.create(name="backupAccount", is_active=True)
- account = ServiceAccount.objects.create(name="account", is_active=True)
+ backupApp = App.objects.create(name="backupApp", is_active=True)
+ app = App.objects.create(name="app", is_active=True)
Webhook.objects.bulk_create(
[
Webhook(
- name="hook1",
- service_account=backupAccount,
- target_url="http://example.com/activate2",
+ name="hook1", app=backupApp, target_url="http://example.com/activate2",
),
+ Webhook(name="hook2", app=app, target_url="http://example.com/activate",),
Webhook(
- name="hook2",
- service_account=account,
- target_url="http://example.com/activate",
- ),
- Webhook(
- name="backup",
- service_account=backupAccount,
- target_url="http://example.com/backup",
+ name="backup", app=backupApp, target_url="http://example.com/backup",
),
]
)
@@ -491,20 +450,16 @@ def test_query_webhooks_with_sort(
assert webhooks[order]["node"]["name"] == webhook_name
-def test_query_webhooks_by_service_account_without_permissions(
- service_account_api_client,
-):
- second_sa = ServiceAccount.objects.create(
- name="Sample service account", is_active=True
- )
+def test_query_webhooks_by_service_account_without_permissions(app_api_client,):
+ second_app = App.objects.create(name="Sample app account", is_active=True)
second_webhook = Webhook.objects.create(
- service_account=second_sa, target_url="http://www.example.com/test"
+ app=second_app, target_url="http://www.example.com/test"
)
second_webhook.events.create(event_type="order_created")
query = QUERY_WEBHOOKS
variables = {"filter": {}}
- response = service_account_api_client.post_graphql(query, variables=variables)
+ response = app_api_client.post_graphql(query, variables=variables)
content = get_graphql_content(response)
webhooks = content["data"]["webhooks"]["edges"]
assert len(webhooks) == 0
@@ -548,12 +503,12 @@ def test_query_webhook_by_staff_without_permission(staff_api_client, webhook):
assert_no_permission(response)
-def test_query_webhook_by_service_account(service_account_api_client, webhook):
+def test_query_webhook_by_service_account(app_api_client, webhook):
query = QUERY_WEBHOOK
webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
variables = {"id": webhook_id}
- response = service_account_api_client.post_graphql(query, variables=variables)
+ response = app_api_client.post_graphql(query, variables=variables)
content = get_graphql_content(response)
webhook_response = content["data"]["webhook"]
@@ -564,21 +519,17 @@ def test_query_webhook_by_service_account(service_account_api_client, webhook):
assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.value
-def test_query_webhook_by_service_account_without_permission(
- service_account_api_client,
-):
- second_sa = ServiceAccount.objects.create(
- name="Sample service account", is_active=True
- )
+def test_query_webhook_by_service_account_without_permission(app_api_client,):
+ second_app = App.objects.create(name="Sample app account", is_active=True)
webhook = Webhook.objects.create(
- service_account=second_sa, target_url="http://www.example.com/test"
+ app=second_app, target_url="http://www.example.com/test"
)
webhook.events.create(event_type="order_created")
query = QUERY_WEBHOOK
webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
variables = {"id": webhook_id}
- response = service_account_api_client.post_graphql(query, variables=variables)
+ response = app_api_client.post_graphql(query, variables=variables)
content = get_graphql_content(response)
webhook_response = content["data"]["webhook"]
assert webhook_response is None
@@ -638,14 +589,14 @@ def test_sample_payload_query_by_service_account(
mock_generate_sample_payload,
event_type,
has_access,
- service_account_api_client,
+ app_api_client,
permission_manage_orders,
):
mock_generate_sample_payload.return_value = {"mocked_response": ""}
query = SAMPLE_PAYLOAD_QUERY
variables = {"event_type": event_type.name}
- response = service_account_api_client.post_graphql(
+ response = app_api_client.post_graphql(
query, variables=variables, permissions=[permission_manage_orders]
)
if not has_access:
diff --git a/tests/conftest.py b/tests/conftest.py
index 8a89e9ba0a..d67f81d490 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -20,12 +20,8 @@ from django_countries import countries
from PIL import Image
from prices import Money, TaxedMoney
-from saleor.account.models import (
- Address,
- ServiceAccount,
- StaffNotificationRecipient,
- User,
-)
+from saleor.account.models import Address, StaffNotificationRecipient, User
+from saleor.app.models import App
from saleor.checkout import utils
from saleor.checkout.models import Checkout
from saleor.checkout.utils import add_variant_to_checkout
@@ -584,7 +580,7 @@ def permission_manage_plugins():
@pytest.fixture
def permission_manage_service_accounts():
- return Permission.objects.get(codename="manage_service_accounts")
+ return Permission.objects.get(codename="manage_apps")
@pytest.fixture
@@ -1798,15 +1794,13 @@ def other_description_json():
@pytest.fixture
-def service_account(db):
- return ServiceAccount.objects.create(name="Sample service account", is_active=True)
+def app(db):
+ return App.objects.create(name="Sample app objects", is_active=True)
@pytest.fixture
-def webhook(service_account):
- webhook = Webhook.objects.create(
- service_account=service_account, target_url="http://www.example.com/test"
- )
+def webhook(app):
+ webhook = Webhook.objects.create(app=app, target_url="http://www.example.com/test")
webhook.events.create(event_type=WebhookEventType.ORDER_CREATED)
return webhook
diff --git a/tests/extensions/plugins/test_webhook.py b/tests/extensions/plugins/test_webhook.py
index 8940e177d4..a8cdd4fd21 100644
--- a/tests/extensions/plugins/test_webhook.py
+++ b/tests/extensions/plugins/test_webhook.py
@@ -4,7 +4,7 @@ import pytest
import requests
from django.core.serializers import serialize
-from saleor.account.models import ServiceAccount
+from saleor.app.models import App
from saleor.extensions.manager import get_extensions_manager
from saleor.extensions.plugins.webhook import create_hmac_signature
from saleor.extensions.plugins.webhook.tasks import trigger_webhooks_for_event
@@ -29,7 +29,7 @@ def test_trigger_webhooks_for_event(
permission_manage_users,
permission_manage_products,
):
- webhook.service_account.permissions.add(permission_manage_orders)
+ webhook.app.permissions.add(permission_manage_orders)
webhook.target_url = "https://webhook.site/f0fc9979-cbd4-47b7-8705-1acb03fff1d0"
webhook.save()
@@ -69,7 +69,7 @@ def test_trigger_webhooks_for_event_calls_expected_events(
event_name,
total_webhook_calls,
expected_target_urls,
- service_account,
+ app,
order_with_lines,
permission_manage_orders,
permission_manage_users,
@@ -77,27 +77,25 @@ def test_trigger_webhooks_for_event_calls_expected_events(
):
"""Confirm that Saleor executes only valid and allowed webhook events."""
- service_account.permissions.add(permission_manage_orders)
- service_account.permissions.add(permission_manage_products)
- webhook = service_account.webhooks.create(
- target_url="http://www.example.com/first/"
- )
+ app.permissions.add(permission_manage_orders)
+ app.permissions.add(permission_manage_products)
+ webhook = app.webhooks.create(target_url="http://www.example.com/first/")
webhook.events.create(event_type=WebhookEventType.CUSTOMER_CREATED)
webhook.events.create(event_type=WebhookEventType.PRODUCT_CREATED)
webhook.events.create(event_type=WebhookEventType.ORDER_FULLY_PAID)
- sa_without_permissions = ServiceAccount.objects.create()
+ app_without_permissions = App.objects.create()
- second_webhook = sa_without_permissions.webhooks.create(
+ second_webhook = app_without_permissions.webhooks.create(
target_url="http://www.example.com/wrong"
)
second_webhook.events.create(event_type=WebhookEventType.ANY)
second_webhook.events.create(event_type=WebhookEventType.PRODUCT_CREATED)
second_webhook.events.create(event_type=WebhookEventType.CUSTOMER_CREATED)
- sa_with_partial_permissions = ServiceAccount.objects.create()
- sa_with_partial_permissions.permissions.add(permission_manage_orders)
- third_webhook = sa_with_partial_permissions.webhooks.create(
+ app_with_partial_permissions = App.objects.create()
+ app_with_partial_permissions.permissions.add(permission_manage_orders)
+ third_webhook = app_with_partial_permissions.webhooks.create(
target_url="http://www.example.com/third/"
)
third_webhook.events.create(event_type=WebhookEventType.ANY)
@@ -116,7 +114,7 @@ def test_trigger_webhooks_for_event_calls_expected_events(
def test_trigger_webhooks_for_event_with_secret_key(
mock_request, webhook, order_with_lines, permission_manage_orders
):
- webhook.service_account.permissions.add(permission_manage_orders)
+ webhook.app.permissions.add(permission_manage_orders)
webhook.target_url = "https://webhook.site/f0fc9979-cbd4-47b7-8705-1acb03fff1d0"
webhook.secret_key = "secret_key"
webhook.save()
diff --git a/tests/test_account_service_account.py b/tests/test_account_service_account.py
deleted file mode 100644
index e19b14bd0c..0000000000
--- a/tests/test_account_service_account.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from unittest.mock import ANY, Mock
-
-import requests
-from django.core.management import call_command
-
-from saleor.account.models import ServiceAccount
-from saleor.core.permissions import get_permissions
-
-
-def test_createaccount_command_creates_service_account():
- name = "SA name"
- permissions = ["account.manage_users", "order.manage_orders"]
- call_command("createserviceaccount", name, permission=permissions)
-
- sa_accounts = ServiceAccount.objects.filter(name=name)
- assert len(sa_accounts) == 1
-
- sa_account = sa_accounts[0]
- tokens = sa_account.tokens.all()
- assert len(tokens) == 1
-
-
-def test_createaccount_command_service_account_has_all_required_permissions():
- name = "SA name"
- permission_list = ["account.manage_users", "order.manage_orders"]
- expected_permission = get_permissions(permission_list)
- call_command("createserviceaccount", name, permission=permission_list)
-
- sa_accounts = ServiceAccount.objects.filter(name=name)
- assert len(sa_accounts) == 1
- sa_account = sa_accounts[0]
- assert set(sa_account.permissions.all()) == set(expected_permission)
-
-
-def test_createaccount_command_sends_data_to_target_url(monkeypatch):
- mocked_response = Mock()
- mocked_response.status_code = 200
- mocked_post = Mock(return_value=mocked_response)
-
- monkeypatch.setattr(requests, "post", mocked_post)
-
- name = "SA name"
- target_url = "https://ss.shop.com/register"
- permissions = [
- "account.manage_users",
- ]
-
- call_command(
- "createserviceaccount", name, permission=permissions, target_url=target_url
- )
-
- service_account = ServiceAccount.objects.filter(name=name)[0]
- token = service_account.tokens.all()[0].auth_token
- mocked_post.assert_called_once_with(
- target_url,
- headers={"x-saleor-domain": "mirumee.com"},
- json={"auth_token": token},
- timeout=ANY,
- )
diff --git a/tests/test_app_create_app_command.py b/tests/test_app_create_app_command.py
new file mode 100644
index 0000000000..028f9e5138
--- /dev/null
+++ b/tests/test_app_create_app_command.py
@@ -0,0 +1,57 @@
+from unittest.mock import ANY, Mock
+
+import requests
+from django.core.management import call_command
+
+from saleor.app.models import App
+from saleor.core.permissions import get_permissions
+
+
+def test_creates_app_object():
+ name = "Single App"
+ permissions = ["account.manage_users", "order.manage_orders"]
+ call_command("create_app", name, permission=permissions)
+
+ apps = App.objects.filter(name=name)
+ assert len(apps) == 1
+
+ app = apps[0]
+ tokens = app.tokens.all()
+ assert len(tokens) == 1
+
+
+def test_app_has_all_required_permissions():
+ name = "SA name"
+ permission_list = ["account.manage_users", "order.manage_orders"]
+ expected_permission = get_permissions(permission_list)
+ call_command("create_app", name, permission=permission_list)
+
+ apps = App.objects.filter(name=name)
+ assert len(apps) == 1
+ app = apps[0]
+ assert set(app.permissions.all()) == set(expected_permission)
+
+
+def test_sends_data_to_target_url(monkeypatch):
+ mocked_response = Mock()
+ mocked_response.status_code = 200
+ mocked_post = Mock(return_value=mocked_response)
+
+ monkeypatch.setattr(requests, "post", mocked_post)
+
+ name = "Single App"
+ target_url = "https://ss.shop.com/register"
+ permissions = [
+ "account.manage_users",
+ ]
+
+ call_command("create_app", name, permission=permissions, target_url=target_url)
+
+ app = App.objects.filter(name=name)[0]
+ token = app.tokens.all()[0].auth_token
+ mocked_post.assert_called_once_with(
+ target_url,
+ headers={"x-saleor-domain": "mirumee.com"},
+ json={"auth_token": token},
+ timeout=ANY,
+ )
diff --git a/tests/test_core.py b/tests/test_core.py
index 13b4f2fbe3..4296ea291f 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -320,10 +320,10 @@ def test_cleardb_delete_staff_parameter(staff_user):
@override_settings(DEBUG=True)
-def test_cleardb_preserves_data(admin_user, service_account, site_settings, staff_user):
+def test_cleardb_preserves_data(admin_user, app, site_settings, staff_user):
call_command("cleardb")
# These shouldn't be deleted when running `cleardb`.
admin_user.refresh_from_db()
- service_account.refresh_from_db()
+ app.refresh_from_db()
site_settings.refresh_from_db()
staff_user.refresh_from_db()