Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Include permissions in schema descriptions of protected fields (#9428)
Marcin Gębalaf0a988e798dd
diff --git a/saleor/core/permissions/__init__.py b/saleor/core/permissions/__init__.pynew file mode 100644index 0000000000..b6295bfd77--- /dev/null+++ b/saleor/core/permissions/__init__.py@@ -0,0 +1,109 @@+# flake8: noqa++from django.contrib.auth import get_user_model++from .auth_filters import (+ AuthorizationFilters,+ is_app,+ is_staff_user,+ is_user,+ resolve_authorization_filter_fn,+)+from .enums import (+ PERMISSIONS_ENUMS,+ AccountPermissions,+ AppPermission,+ BasePermissionEnum,+ ChannelPermissions,+ CheckoutPermissions,+ DiscountPermissions,+ GiftcardPermissions,+ MenuPermissions,+ OrderPermissions,+ PagePermissions,+ PageTypePermissions,+ PaymentPermissions,+ PluginsPermissions,+ ProductPermissions,+ ProductTypePermissions,+ ShippingPermissions,+ SitePermissions,+ get_permission_names,+ get_permissions,+ get_permissions_codename,+ get_permissions_enum_dict,+ get_permissions_enum_list,+ get_permissions_from_codenames,+ get_permissions_from_names,+ split_permission_codename,+)+++def one_of_permissions_or_auth_filter_required(context, permissions):+ """Determine whether user or app has rights to perform an action.++ The `context` parameter is the Context instance associated with the request.+ """+ if not permissions:+ return True++ authorization_filters = [+ p for p in permissions if isinstance(p, AuthorizationFilters)+ ]+ permissions = [p for p in permissions if not isinstance(p, AuthorizationFilters)]++ granted_by_permissions = False+ granted_by_authorization_filters = False++ # TODO: move this function from graphql to core+ from saleor.graphql.utils import get_user_or_app_from_context++ is_app = bool(getattr(context, "app", None))+ requestor = get_user_or_app_from_context(context)++ if permissions:+ perm_checks_results = []+ for permission in permissions:+ if is_app and permission == AccountPermissions.MANAGE_STAFF:+ # `MANAGE_STAFF` permission for apps is not supported, as apps using it+ # could create a staff user with full access.+ perm_checks_results.append(False)+ else:+ perm_checks_results.append(requestor.has_perm(permission))+ granted_by_permissions = any(perm_checks_results)++ if authorization_filters:+ auth_filters_results = []+ for p in authorization_filters:+ perm_fn = resolve_authorization_filter_fn(p)+ if perm_fn:+ res = perm_fn(context)+ auth_filters_results.append(bool(res))+ granted_by_authorization_filters = any(auth_filters_results)++ return granted_by_permissions or granted_by_authorization_filters+++def permission_required(requestor, perms):+ User = get_user_model()+ if isinstance(requestor, User):+ return requestor.has_perms(perms)+ else:+ # for now MANAGE_STAFF permission for app is not supported+ if AccountPermissions.MANAGE_STAFF in perms:+ return False+ return requestor.has_perms(perms)+++def has_one_of_permissions(requestor, permissions=None):+ if not permissions:+ return True+ for perm in permissions:+ if permission_required(requestor, (perm,)):+ return True+ return False+++def message_one_of_permissions_required(permissions):+ permission_msg = ", ".join([p.name for p in permissions])+ return f"Requires one of the following permissions: {permission_msg}."diff --git a/saleor/core/permissions/auth_filters.py b/saleor/core/permissions/auth_filters.pynew file mode 100644index 0000000000..783db9534c--- /dev/null+++ b/saleor/core/permissions/auth_filters.py@@ -0,0 +1,40 @@+from .enums import BasePermissionEnum+++def is_app(context):+ return bool(context.app)+++def is_user(context):+ return context.user.is_active and context.user.is_authenticated+++def is_staff_user(context):+ return is_user(context) and context.user.is_staff+++class AuthorizationFilters(BasePermissionEnum):+ # Grants access to any authenticated app.+ AUTHENTICATED_APP = "authorization_filters.authenticated_app"++ # Grants access to any authenticated staff user.+ AUTHENTICATED_STAFF_USER = "authorization_filters.authenticated_staff_user"++ # Grants access to any authenticated user.+ AUTHENTICATED_USER = "authorization_filters.authenticated_user"++ # Grants access to the owner of the related object. This rule doesn't come with any+ # permission function, as the ownership needs to be defined individually in each+ # case.+ OWNER = "authorization_filters.owner"+++AUTHORIZATION_FILTER_MAP = {+ AuthorizationFilters.AUTHENTICATED_APP: is_app,+ AuthorizationFilters.AUTHENTICATED_USER: is_user,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER: is_staff_user,+}+++def resolve_authorization_filter_fn(perm):+ return AUTHORIZATION_FILTER_MAP.get(perm)diff --git a/saleor/core/permissions.py b/saleor/core/permissions/enums.pysimilarity index 69%rename from saleor/core/permissions.pyrename to saleor/core/permissions/enums.pyindex 0eb6953ad3..dff260d761 100644--- a/saleor/core/permissions.py+++ b/saleor/core/permissions/enums.py@@ -1,7 +1,6 @@from enum import Enumfrom typing import Iterable, List-from django.contrib.auth import get_user_modelfrom django.contrib.auth.models import Permission@@ -99,49 +98,6 @@ PERMISSIONS_ENUMS = []-def is_app(context):- return bool(context.app)---def is_user(context):- return context.user.is_active and context.user.is_authenticated---def is_staff_user(context):- return is_user(context) and context.user.is_staff---class AuthorizationFilters(BasePermissionEnum):- # Grants access to any authenticated app.- AUTHENTICATED_APP = "authorization_filters.authenticated_app"-- # Grants access to any authenticated staff user.- AUTHENTICATED_STAFF_USER = "authorization_filters.authenticated_staff_user"-- # Grants access to any authenticated user.- AUTHENTICATED_USER = "authorization_filters.authenticated_user"-- # Grants access to the owner of the related object. This rule doesn't come with any- # permission function, as the ownership needs to be defined individually in each- # case.- OWNER = "authorization_filters.owner"---AUTHORIZATION_FILTER_MAP = {- AuthorizationFilters.AUTHENTICATED_APP: is_app,- AuthorizationFilters.AUTHENTICATED_USER: is_user,- AuthorizationFilters.AUTHENTICATED_STAFF_USER: is_staff_user,-}---def resolve_authorization_filter_fn(perm):- return AUTHORIZATION_FILTER_MAP.get(perm)---def split_permission_codename(permissions):- return [permission.split(".")[1] for permission in permissions]--def get_permissions_codename():permissions_values = [enum.codename@@ -151,6 +107,15 @@ def get_permissions_codename():return permissions_values+def get_permissions_enum_list():+ permissions_list = [+ (enum.name, enum.value)+ for permission_enum in PERMISSIONS_ENUMS+ for enum in permission_enum+ ]+ return permissions_list++def get_permissions_enum_dict():return {enum.name: enum@@ -176,13 +141,8 @@ def get_permission_names(permissions: Iterable["Permission"]):return names-def get_permissions_enum_list():- permissions_list = [- (enum.name, enum.value)- for permission_enum in PERMISSIONS_ENUMS- for enum in permission_enum- ]- return permissions_list+def split_permission_codename(permissions):+ return [permission.split(".")[1] for permission in permissions]def get_permissions(permissions=None):@@ -199,25 +159,3 @@ def get_permissions_from_codenames(permission_codenames: List[str]):.prefetch_related("content_type").order_by("codename"))---def permission_required(perms, requestor):- User = get_user_model()- if isinstance(requestor, User):- if requestor.has_perms(perms):- return True- else:- # for now MANAGE_STAFF permission for app is not supported- if AccountPermissions.MANAGE_STAFF in perms:- return False- return requestor.has_perms(perms)- return False---def has_one_of_permissions(requestor, permissions=None):- if not permissions:- return True- for perm in permissions:- if permission_required((perm,), requestor):- return True- return Falsediff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.pyindex 0f7f557dea..c95eed2a61 100644--- a/saleor/graphql/account/mutations/staff.py+++ b/saleor/graphql/account/mutations/staff.py@@ -15,7 +15,7 @@ from ....account.utils import (remove_the_oldest_user_address_if_address_limit_is_reached,)from ....checkout import AddressType-from ....core.permissions import AccountPermissions+from ....core.permissions import AccountPermissions, AuthorizationFiltersfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils.url import validate_storefront_urlfrom ....giftcard.utils import assign_user_gift_cards@@ -25,7 +25,6 @@ from ...account.types import Address, AddressInput, Userfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.types import AccountError, NonNullList, StaffError, Uploadfrom ...core.utils import add_hash_to_file_name, validate_image_file-from ...decorators import staff_member_requiredfrom ...utils.validators import check_for_duplicatesfrom ..utils import (CustomerDeleteMixin,@@ -559,9 +558,9 @@ class UserAvatarUpdate(BaseMutation):)error_type_class = AccountErrorerror_type_field = "account_errors"+ permissions = (AuthorizationFilters.AUTHENTICATED_STAFF_USER,)@classmethod- @staff_member_requireddef perform_mutation(cls, _root, info, image):user = info.context.userimage_data = info.context.FILES.get(image)@@ -584,9 +583,9 @@ class UserAvatarDelete(BaseMutation):description = "Deletes a user avatar. Only for staff members."error_type_class = AccountErrorerror_type_field = "account_errors"+ permissions = (AuthorizationFilters.AUTHENTICATED_STAFF_USER,)@classmethod- @staff_member_requireddef perform_mutation(cls, _root, info):user = info.context.useruser.avatar.delete_sized_images()diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.pyindex 5ce9aefece..ccabe82b52 100644--- a/saleor/graphql/account/schema.py+++ b/saleor/graphql/account/schema.py@@ -2,11 +2,10 @@ import graphenefrom ...core.permissions import AccountPermissions, OrderPermissionsfrom ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.fields import FilterConnectionField+from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.types import FilterInputObjectTypefrom ..core.utils import from_global_id_or_errorfrom ..core.validators import validate_one_of_args_is_in_query-from ..decorators import one_of_permissions_required, permission_requiredfrom .bulk_mutations import CustomerBulkDelete, StaffBulkDelete, UserBulkSetActivefrom .enums import CountryCodeEnumfrom .filters import CustomerFilter, PermissionGroupFilter, StaffUserFilter@@ -122,6 +121,7 @@ class AccountQueries(graphene.ObjectType):filter=CustomerFilterInput(description="Filtering options for customers."),sort_by=UserSortingInput(description="Sort customers."),description="List of the shop's customers.",+ permissions=[OrderPermissions.MANAGE_ORDERS, AccountPermissions.MANAGE_USERS],)permission_groups = FilterConnectionField(GroupCountableConnection,@@ -130,13 +130,15 @@ class AccountQueries(graphene.ObjectType):),sort_by=PermissionGroupSortingInput(description="Sort permission groups."),description="List of permission groups.",+ permissions=[AccountPermissions.MANAGE_STAFF],)- permission_group = graphene.Field(+ permission_group = PermissionsField(Group,id=graphene.Argument(graphene.ID, description="ID of the group.", required=True),description="Look up permission group by ID.",+ permissions=[AccountPermissions.MANAGE_STAFF],)me = graphene.Field(User, description="Return the currently authenticated user.")staff_users = FilterConnectionField(@@ -144,13 +146,19 @@ class AccountQueries(graphene.ObjectType):filter=StaffUserInput(description="Filtering options for staff users."),sort_by=UserSortingInput(description="Sort staff users."),description="List of the shop's staff users.",+ permissions=[AccountPermissions.MANAGE_STAFF],)- user = graphene.Field(+ user = PermissionsField(User,id=graphene.Argument(graphene.ID, description="ID of the user."),email=graphene.Argument(graphene.String, description="Email address of the user."),+ permissions=[+ AccountPermissions.MANAGE_STAFF,+ AccountPermissions.MANAGE_USERS,+ OrderPermissions.MANAGE_ORDERS,+ ],description="Look up a user by ID or email address.",)@@ -165,21 +173,16 @@ class AccountQueries(graphene.ObjectType):city_area=city_area,)- @one_of_permissions_required(- [OrderPermissions.MANAGE_ORDERS, AccountPermissions.MANAGE_USERS]- )def resolve_customers(self, info, **kwargs):qs = resolve_customers(info, **kwargs)qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, UserCountableConnection)- @permission_required(AccountPermissions.MANAGE_STAFF)def resolve_permission_groups(self, info, **kwargs):qs = resolve_permission_groups(info, **kwargs)qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, GroupCountableConnection)- @permission_required(AccountPermissions.MANAGE_STAFF)def resolve_permission_group(self, info, id):_, id = from_global_id_or_error(id, Group)return resolve_permission_group(id)@@ -188,19 +191,11 @@ class AccountQueries(graphene.ObjectType):user = info.context.userreturn user if user.is_authenticated else None- @permission_required(AccountPermissions.MANAGE_STAFF)def resolve_staff_users(self, info, **kwargs):qs = resolve_staff_users(info, **kwargs)qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, UserCountableConnection)- @one_of_permissions_required(- [- AccountPermissions.MANAGE_STAFF,- AccountPermissions.MANAGE_USERS,- OrderPermissions.MANAGE_ORDERS,- ]- )def resolve_user(self, info, id=None, email=None):validate_one_of_args_is_in_query("id", id, "email", email)return resolve_user(info, id, email)diff --git a/saleor/graphql/account/tests/test_account_utils.py b/saleor/graphql/account/tests/test_account_utils.pyindex 710460c9c1..248b669185 100644--- a/saleor/graphql/account/tests/test_account_utils.py+++ b/saleor/graphql/account/tests/test_account_utils.py@@ -21,8 +21,8 @@ from ..utils import (get_out_of_scope_users,get_user_permissions,get_users_and_look_for_permissions_in_groups_with_manage_staff,+ is_owner_or_has_one_of_perms,look_for_permission_in_users_with_manage_staff,- requestor_has_access,)@@ -855,7 +855,7 @@ def test_can_manage_app_for_app(def test_requestor_has_access_no_access_by_customer(staff_user, customer_user):# when- result = requestor_has_access(+ result = is_owner_or_has_one_of_perms(customer_user, staff_user, OrderPermissions.MANAGE_ORDERS)@@ -865,7 +865,7 @@ def test_requestor_has_access_no_access_by_customer(staff_user, customer_user):def test_requestor_has_access_access_by_customer(customer_user):# when- result = requestor_has_access(+ result = is_owner_or_has_one_of_perms(customer_user, customer_user, OrderPermissions.MANAGE_ORDERS)@@ -881,7 +881,7 @@ def test_requestor_has_access_access_by_staff(staff_user.save()# when- result = requestor_has_access(+ result = is_owner_or_has_one_of_perms(staff_user, customer_user, OrderPermissions.MANAGE_ORDERS)@@ -897,7 +897,7 @@ def test_requestor_has_access_no_access_by_staff(staff_user.save()# when- result = requestor_has_access(+ result = is_owner_or_has_one_of_perms(staff_user, customer_user, OrderPermissions.MANAGE_ORDERS)diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.pyindex ec79ef8986..5b2bb653e0 100644--- a/saleor/graphql/account/types.py+++ b/saleor/graphql/account/types.py@@ -16,7 +16,7 @@ from ...core.permissions import ()from ...core.tracing import traced_resolverfrom ...order import OrderStatus-from ..account.utils import check_requestor_access+from ..account.utils import check_is_owner_or_has_one_of_permsfrom ..app.dataloaders import AppByIdLoaderfrom ..app.types import Appfrom ..checkout.dataloaders import CheckoutByUserAndChannelLoader, CheckoutByUserLoader@@ -25,11 +25,10 @@ from ..core.connection import CountableConnection, create_connection_slicefrom ..core.descriptions import DEPRECATED_IN_3X_FIELDfrom ..core.enums import LanguageCodeEnumfrom ..core.federation import federated_entity, resolve_federation_references-from ..core.fields import ConnectionField+from ..core.fields import ConnectionField, PermissionsFieldfrom ..core.scalars import UUIDfrom ..core.types import CountryDisplay, Image, ModelObjectType, NonNullList, Permissionfrom ..core.utils import from_global_id_or_error, str_to_enum-from ..decorators import one_of_permissions_required, permission_requiredfrom ..giftcard.dataloaders import GiftCardsByUserLoaderfrom ..meta.types import ObjectWithMetadatafrom ..order.dataloaders import OrderLineByIdLoader, OrdersByUserLoader@@ -181,7 +180,9 @@ class CustomerEvent(ModelObjectType):@staticmethoddef resolve_app(root: models.CustomerEvent, info):requestor = get_user_or_app_from_context(info.context)- check_requestor_access(requestor, root.user, AppPermission.MANAGE_APPS)+ check_is_owner_or_has_one_of_perms(+ requestor, root.user, AppPermission.MANAGE_APPS+ )return AppByIdLoader(info.context).load(root.app_id) if root.app_id else None@staticmethod@@ -252,10 +253,17 @@ class User(ModelObjectType):"saleor.graphql.giftcard.types.GiftCardCountableConnection",description="List of the user gift cards.",)- note = graphene.String(description="A note about the customer.")+ note = PermissionsField(+ graphene.String,+ description="A note about the customer.",+ permissions=[AccountPermissions.MANAGE_USERS, AccountPermissions.MANAGE_STAFF],+ )orders = ConnectionField("saleor.graphql.order.types.OrderCountableConnection",- description="List of user's orders.",+ description=(+ "List of user's orders. Requires one of the following permissions: "+ f"{AccountPermissions.MANAGE_STAFF}, {AuthorizationFilters.OWNER}"+ ),)user_permissions = NonNullList(UserPermission, description="List of user's permissions."@@ -269,8 +277,10 @@ class User(ModelObjectType):description="List of user's permission groups which user can manage.",)avatar = graphene.Field(Image, size=graphene.Int(description="Size of the avatar."))- events = NonNullList(- CustomerEvent, description="List of events associated with the user."+ events = PermissionsField(+ NonNullList(CustomerEvent),+ description="List of events associated with the user.",+ permissions=[AccountPermissions.MANAGE_USERS, AccountPermissions.MANAGE_STAFF],)stored_payment_sources = NonNullList("saleor.graphql.payment.types.PaymentSource",@@ -353,16 +363,10 @@ class User(ModelObjectType):return get_groups_which_user_can_manage(root)@staticmethod- @one_of_permissions_required(- [AccountPermissions.MANAGE_USERS, AccountPermissions.MANAGE_STAFF]- )def resolve_note(root: models.User, info):return root.note@staticmethod- @one_of_permissions_required(- [AccountPermissions.MANAGE_USERS, AccountPermissions.MANAGE_STAFF]- )def resolve_events(root: models.User, info):return CustomerEventsByUserLoader(info.context).load(root.id)@@ -520,7 +524,13 @@ class StaffNotificationRecipient(graphene.ObjectType):class Group(ModelObjectType):id = graphene.GlobalID(required=True)name = graphene.String(required=True)- users = NonNullList(User, description="List of group users")+ users = PermissionsField(+ NonNullList(User),+ description="List of group users",+ permissions=[+ AccountPermissions.MANAGE_STAFF,+ ],+ )permissions = NonNullList(Permission, description="List of group permissions")user_can_manage = graphene.Boolean(required=True,@@ -535,7 +545,6 @@ class Group(ModelObjectType):model = auth_models.Group@staticmethod- @permission_required(AccountPermissions.MANAGE_STAFF)def resolve_users(root: auth_models.Group, _info):return root.user_set.all()diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.pyindex 56746129e8..f9623ccb92 100644--- a/saleor/graphql/account/utils.py+++ b/saleor/graphql/account/utils.py@@ -12,7 +12,11 @@ from graphene.utils.str_converters import to_camel_casefrom ...account import events as account_eventsfrom ...account.error_codes import AccountErrorCodefrom ...core.exceptions import PermissionDenied-from ...core.permissions import AccountPermissions, has_one_of_permissions+from ...core.permissions import (+ AccountPermissions,+ AuthorizationFilters,+ has_one_of_permissions,+)if TYPE_CHECKING:from django.db.models import QuerySet@@ -463,7 +467,7 @@ def look_for_permission_in_users_with_manage_staff(permissions_to_find.difference_update(common_permissions)-def requestor_has_access(+def is_owner_or_has_one_of_perms(requestor: Union["User", "App"], owner: Optional[Union["User", "App"]], *perms) -> bool:"""Check if requestor can access data.@@ -478,7 +482,7 @@ def requestor_has_access(return requestor == owner or has_one_of_permissions(requestor, perms)-def check_requestor_access(+def check_is_owner_or_has_one_of_perms(requestor: Union["User", "App"], owner: Optional["User"], *perms) -> None:"""Confirm that requestor can access data, raise `PermissionDenied` otherwise.@@ -492,5 +496,5 @@ def check_requestor_access(:raises PermissionDenied: if requestor cannot access data"""- if not requestor_has_access(requestor, owner, *perms):- raise PermissionDenied(permissions=perms)+ if not is_owner_or_has_one_of_perms(requestor, owner, *perms):+ raise PermissionDenied(permissions=list(perms) + [AuthorizationFilters.OWNER])diff --git a/saleor/graphql/app/schema.py b/saleor/graphql/app/schema.pyindex f64941b08a..315a5d0362 100644--- a/saleor/graphql/app/schema.py+++ b/saleor/graphql/app/schema.py@@ -1,12 +1,11 @@import graphene-from ...core.permissions import AppPermission+from ...core.permissions import AppPermission, AuthorizationFiltersfrom ..core.connection import create_connection_slice, filter_connection_querysetfrom ..core.descriptions import ADDED_IN_31, PREVIEW_FEATURE-from ..core.fields import FilterConnectionField+from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.types import FilterInputObjectType, NonNullListfrom ..core.utils import from_global_id_or_error-from ..decorators import permission_required, staff_member_or_app_requiredfrom .dataloaders import AppByIdLoader, AppExtensionByIdLoaderfrom .filters import AppExtensionFilter, AppFilterfrom .mutations import (@@ -50,46 +49,58 @@ class AppExtensionFilterInput(FilterInputObjectType):class AppQueries(graphene.ObjectType):- apps_installations = NonNullList(- AppInstallation,+ apps_installations = PermissionsField(+ NonNullList(AppInstallation),description="List of all apps installations",required=True,+ permissions=[+ AppPermission.MANAGE_APPS,+ ],)apps = FilterConnectionField(AppCountableConnection,filter=AppFilterInput(description="Filtering options for apps."),sort_by=AppSortingInput(description="Sort apps."),description="List of the apps.",+ permissions=[+ AppPermission.MANAGE_APPS,+ ],)app = graphene.Field(App,id=graphene.Argument(graphene.ID, description="ID of the app.", required=False),description=(- "Look up an app by ID. "- "If ID is not provided, return the currently authenticated app."+ "Look up an app by ID. If ID is not provided, return the currently "+ "authenticated app. Requires one of the following permissions: "+ f"{AuthorizationFilters.OWNER}, {AppPermission.MANAGE_APPS}."),)-app_extensions = FilterConnectionField(AppExtensionCountableConnection,filter=AppExtensionFilterInput(description="Filtering options for apps extensions."),description=f"{ADDED_IN_31} List of all extensions. {PREVIEW_FEATURE}",+ permissions=[+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ ],)- app_extension = graphene.Field(+ app_extension = PermissionsField(AppExtension,id=graphene.Argument(graphene.ID, description="ID of the app extension.", required=True),description=f"{ADDED_IN_31} Look up an app extension by ID. {PREVIEW_FEATURE}",+ permissions=[+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ ],)- @permission_required(AppPermission.MANAGE_APPS)def resolve_apps_installations(self, info, **kwargs):return resolve_apps_installations(info, **kwargs)- @permission_required(AppPermission.MANAGE_APPS)def resolve_apps(self, info, **kwargs):qs = resolve_apps(info, **kwargs)qs = filter_connection_queryset(qs, kwargs)@@ -101,7 +112,6 @@ class AppQueries(graphene.ObjectType):return appreturn resolve_app(info, id)- @staff_member_or_app_requireddef resolve_app_extensions(self, info, **kwargs):qs = resolve_app_extensions(info)qs = filter_connection_queryset(qs, kwargs)@@ -109,7 +119,6 @@ class AppQueries(graphene.ObjectType):qs, info, kwargs, AppExtensionCountableConnection)- @staff_member_or_app_requireddef resolve_app_extension(self, info, id):def app_is_active(app_extension):def is_active(app):diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.pyindex 5b37a1ddae..9d11ff7aeb 100644--- a/saleor/graphql/app/types.py+++ b/saleor/graphql/app/types.py@@ -6,7 +6,7 @@ from ...app import modelsfrom ...app.types import AppExtensionTargetfrom ...core.exceptions import PermissionDeniedfrom ...core.permissions import AppPermission, AuthorizationFilters-from ..account.utils import requestor_has_access+from ..account.utils import is_owner_or_has_one_of_permsfrom ..core.connection import CountableConnectionfrom ..core.descriptions import ADDED_IN_31, PREVIEW_FEATUREfrom ..core.federation import federated_entity, resolve_federation_references@@ -25,7 +25,7 @@ from .resolvers import (def has_required_permission(app: models.App, context):requester = get_user_or_app_from_context(context)- if not requestor_has_access(requester, app, AppPermission.MANAGE_APPS):+ if not is_owner_or_has_one_of_perms(requester, app, AppPermission.MANAGE_APPS):raise PermissionDenied(permissions=[AppPermission.MANAGE_APPS, AuthorizationFilters.OWNER])diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex e532a2ad24..023a387858 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -1,10 +1,15 @@-import refrom typing import castimport graphenefrom django.db.models import QuerySetfrom ...attribute import AttributeEntityType, AttributeInputType, models+from ...core.permissions import (+ PagePermissions,+ PageTypePermissions,+ ProductPermissions,+ ProductTypePermissions,+)from ...core.tracing import traced_resolverfrom ..core.connection import (CountableConnection,@@ -32,9 +37,6 @@ from .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypfrom .filters import AttributeValueFilterInputfrom .sorters import AttributeChoicesSortingInput-COLOR_PATTERN = r"^(#[0-9a-fA-F]{3}|#(?:[0-9a-fA-F]{2}){2,4}|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))$" # noqa-color_pattern = re.compile(COLOR_PATTERN)-class AttributeValue(ModelObjectType):id = graphene.GlobalID(required=True)@@ -155,30 +157,69 @@ class Attribute(ModelObjectType):)value_required = graphene.Boolean(- description=AttributeDescriptions.VALUE_REQUIRED, required=True+ description=(+ f"{AttributeDescriptions.VALUE_REQUIRED} Requires one of the following "+ f"permissions: {PagePermissions.MANAGE_PAGES}, "+ f"{PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES}, "+ f"{ProductPermissions.MANAGE_PRODUCTS}, "+ f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES}."+ ),+ required=True,)visible_in_storefront = graphene.Boolean(- description=AttributeDescriptions.VISIBLE_IN_STOREFRONT, required=True+ description=(+ f"{AttributeDescriptions.VISIBLE_IN_STOREFRONT} Requires one of the "+ f"following permissions: {PagePermissions.MANAGE_PAGES}, "+ f"{PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES}, "+ f"{ProductPermissions.MANAGE_PRODUCTS}, "+ f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES}."+ ),+ required=True,)filterable_in_storefront = graphene.Boolean(- description=AttributeDescriptions.FILTERABLE_IN_STOREFRONT, required=True+ description=(+ f"{AttributeDescriptions.FILTERABLE_IN_STOREFRONT} Requires one of the "+ f"following permissions: {PagePermissions.MANAGE_PAGES}, "+ f"{PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES}, "+ f"{ProductPermissions.MANAGE_PRODUCTS}, "+ f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES}."+ ),+ required=True,)filterable_in_dashboard = graphene.Boolean(- description=AttributeDescriptions.FILTERABLE_IN_DASHBOARD, required=True+ description=(+ f"{AttributeDescriptions.FILTERABLE_IN_DASHBOARD} Requires one of the "+ f"following permissions: {PagePermissions.MANAGE_PAGES}, "+ f"{PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES}, "+ f"{ProductPermissions.MANAGE_PRODUCTS}, "+ f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES}."+ ),+ required=True,)available_in_grid = graphene.Boolean(- description=AttributeDescriptions.AVAILABLE_IN_GRID, required=True+ description=(+ f"{AttributeDescriptions.AVAILABLE_IN_GRID} Requires one of the following "+ f"permissions: {PagePermissions.MANAGE_PAGES}, "+ f"{PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES}, "+ f"{ProductPermissions.MANAGE_PRODUCTS}, "+ f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES}."+ ),+ required=True,)-- translation = TranslationField(AttributeTranslation, type_name="attribute")-storefront_search_position = graphene.Int(- description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION, required=True+ description=(+ f"{AttributeDescriptions.STOREFRONT_SEARCH_POSITION} Requires one of the "+ f"following permissions: {PagePermissions.MANAGE_PAGES}, "+ f"{PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES}, "+ f"{ProductPermissions.MANAGE_PRODUCTS}, "+ f"{ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES}."+ ),+ required=True,)+ translation = TranslationField(AttributeTranslation, type_name="attribute")with_choices = graphene.Boolean(description=AttributeDescriptions.WITH_CHOICES, required=True)-product_types = ConnectionField("saleor.graphql.product.types.ProductTypeCountableConnection",required=True,diff --git a/saleor/graphql/channel/schema.py b/saleor/graphql/channel/schema.pyindex 941bfca849..7fa0e67f63 100644--- a/saleor/graphql/channel/schema.py+++ b/saleor/graphql/channel/schema.py@@ -1,8 +1,9 @@import graphene+from ...core.permissions import AuthorizationFilters+from ..core.fields import PermissionsFieldfrom ..core.types import NonNullListfrom ..core.utils import from_global_id_or_error-from ..decorators import staff_member_or_app_requiredfrom .mutations import (ChannelActivate,ChannelCreate,@@ -15,19 +16,28 @@ from .types import Channelclass ChannelQueries(graphene.ObjectType):- channel = graphene.Field(+ channel = PermissionsField(Channel,id=graphene.Argument(graphene.ID, description="ID of the channel."),description="Look up a channel by ID.",+ permissions=[+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ )+ channels = PermissionsField(+ NonNullList(Channel),+ description="List of all channels.",+ permissions=[+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],)- channels = NonNullList(Channel, description="List of all channels.")- @staff_member_or_app_requireddef resolve_channel(self, info, id=None, **kwargs):_, id = from_global_id_or_error(id, Channel)return resolve_channel(id)- @staff_member_or_app_requireddef resolve_channels(self, _info, **kwargs):return resolve_channels()diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex 8d1fec0d2f..ad65f1ace8 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -7,8 +7,8 @@ from graphene.types.resolver import get_default_resolverfrom ...channel import modelsfrom ...core.permissions import ChannelPermissionsfrom ..core.descriptions import ADDED_IN_31+from ..core.fields import PermissionsFieldfrom ..core.types import CountryDisplay, ModelObjectType-from ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadatafrom ..translations.resolvers import resolve_translationfrom . import ChannelContext@@ -102,8 +102,13 @@ class Channel(ModelObjectType):slug = graphene.String(required=True)currency_code = graphene.String(required=True)slug = graphene.String(required=True)- has_orders = graphene.Boolean(- required=True, description="Whether a channel has associated orders."+ has_orders = PermissionsField(+ graphene.Boolean,+ description="Whether a channel has associated orders.",+ permissions=[+ ChannelPermissions.MANAGE_CHANNELS,+ ],+ required=True,)default_country = graphene.Field(CountryDisplay,@@ -121,7 +126,6 @@ class Channel(ModelObjectType):interfaces = [graphene.relay.Node]@staticmethod- @permission_required(ChannelPermissions.MANAGE_CHANNELS)def resolve_has_orders(root: models.Channel, info):return (ChannelWithHasOrdersByIdLoader(info.context)diff --git a/saleor/graphql/checkout/schema.py b/saleor/graphql/checkout/schema.pyindex 4778ef255c..50e8724bf6 100644--- a/saleor/graphql/checkout/schema.py+++ b/saleor/graphql/checkout/schema.py@@ -5,7 +5,6 @@ from ..core.connection import create_connection_slice, filter_connection_querysefrom ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELDfrom ..core.fields import ConnectionField, FilterConnectionFieldfrom ..core.scalars import UUID-from ..decorators import permission_requiredfrom ..payment.mutations import CheckoutPaymentCreatefrom .filters import CheckoutFilterInputfrom .mutations import (@@ -52,22 +51,27 @@ class CheckoutQueries(graphene.ObjectType):channel=graphene.String(description="Slug of a channel for which the data should be returned."),+ permissions=[+ CheckoutPermissions.MANAGE_CHECKOUTS,+ ],description="List of checkouts.",)checkout_lines = ConnectionField(- CheckoutLineCountableConnection, description="List of checkout lines."+ CheckoutLineCountableConnection,+ description="List of checkout lines.",+ permissions=[+ CheckoutPermissions.MANAGE_CHECKOUTS,+ ],)def resolve_checkout(self, info, token):return resolve_checkout(info, token)- @permission_required(CheckoutPermissions.MANAGE_CHECKOUTS)def resolve_checkouts(self, info, *_args, channel=None, **kwargs):qs = resolve_checkouts(channel)qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, CheckoutCountableConnection)- @permission_required(CheckoutPermissions.MANAGE_CHECKOUTS)def resolve_checkout_lines(self, info, *_args, **kwargs):qs = resolve_checkout_lines()return create_connection_slice(diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex b6ba85f80f..e7123981a3 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -10,7 +10,7 @@ from ...shipping.interface import ShippingMethodDatafrom ...warehouse import models as warehouse_modelsfrom ...warehouse.reservations import is_reservation_enabledfrom ..account.dataloaders import AddressByIdLoader-from ..account.utils import check_requestor_access+from ..account.utils import check_is_owner_or_has_one_of_permsfrom ..channel import ChannelContextfrom ..channel.dataloaders import ChannelByCheckoutLineIDLoader, ChannelByIdLoaderfrom ..channel.types import Channel@@ -305,7 +305,9 @@ class Checkout(ModelObjectType):if not root.user_id:return Nonerequestor = get_user_or_app_from_context(info.context)- check_requestor_access(requestor, root.user, AccountPermissions.MANAGE_USERS)+ check_is_owner_or_has_one_of_perms(+ requestor, root.user, AccountPermissions.MANAGE_USERS+ )return root.user@staticmethoddiff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.pyindex 1766452d40..6c28069e17 100644--- a/saleor/graphql/core/fields.py+++ b/saleor/graphql/core/fields.py@@ -5,10 +5,34 @@ import graphenefrom graphene.relay import Connection, is_nodefrom graphql import GraphQLError+from ...core.permissions import message_one_of_permissions_required+from ..decorators import one_of_permissions_requiredfrom .connection import FILTERS_NAME, FILTERSET_CLASS-class ConnectionField(graphene.Field):+class PermissionsField(graphene.Field):+ def __init__(self, *args, **kwargs):+ self.permissions = kwargs.pop("permissions", [])+ assert isinstance(self.permissions, list), (+ "FieldWithPermissions `permissions` argument must be a list: "+ f"{self.permissions}"+ )++ super(PermissionsField, self).__init__(*args, **kwargs)++ if self.permissions:+ permissions_msg = message_one_of_permissions_required(self.permissions)+ description = self.description or ""+ self.description = f"{description} {permissions_msg}"++ def get_resolver(self, parent_resolver):+ resolver = self.resolver or parent_resolver+ if self.permissions:+ resolver = one_of_permissions_required(self.permissions)(resolver)+ return resolver+++class ConnectionField(PermissionsField):def __init__(self, type_, *args, **kwargs):kwargs.setdefault("before",diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex cae5b3f4be..a314054c4a 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -21,16 +21,11 @@ from graphql.error import GraphQLErrorfrom ...core.db.utils import set_mutation_flag_in_contextfrom ...core.exceptions import PermissionDeniedfrom ...core.permissions import (- AccountPermissions,AuthorizationFilters,- resolve_authorization_filter_fn,-)-from ..decorators import staff_member_or_app_required-from ..utils import (- get_nodes,- get_user_or_app_from_context,- resolve_global_ids_to_primary_keys,+ message_one_of_permissions_required,+ one_of_permissions_or_auth_filter_required,)+from ..utils import get_nodes, resolve_global_ids_to_primary_keysfrom .descriptions import DEPRECATED_IN_3X_FIELDfrom .types import File, NonNullList, Upload, UploadErrorfrom .utils import from_global_id_or_error, snake_to_camel_case@@ -150,11 +145,8 @@ class BaseMutation(graphene.Mutation):_meta.errors_mapping = errors_mappingif permissions and auto_permission_message:- permission_msg = ", ".join([p.name for p in permissions])- description = (- f"{description} Requires one of the following "- f"permissions: {permission_msg}."- )+ permissions_msg = message_one_of_permissions_required(permissions)+ description = f"{description} {permissions_msg}"super().__init_subclass_with_meta__(description=description, _meta=_meta, **options@@ -363,37 +355,7 @@ class BaseMutation(graphene.Mutation):if not all_permissions:return True- authorization_filters = [- p for p in all_permissions if isinstance(p, AuthorizationFilters)- ]- permissions = [- p for p in all_permissions if not isinstance(p, AuthorizationFilters)- ]-- granted_by_permissions = False- granted_by_authorization_filters = False-- app = getattr(context, "app", None)- if app and permissions and AccountPermissions.MANAGE_STAFF in permissions:- # `MANAGE_STAFF` permission for apps is not supported. If apps could use it- # they could create a staff user with full access which would be a- # permission leak issue.- return False-- requestor = get_user_or_app_from_context(context)- if permissions:- granted_by_permissions = requestor.has_perms(permissions)-- if authorization_filters:- internal_perm_checks = []- for p in authorization_filters:- perm_fn = resolve_authorization_filter_fn(p)- if perm_fn:- res = perm_fn(context)- internal_perm_checks.append(bool(res))- granted_by_authorization_filters = any(internal_perm_checks)-- return granted_by_permissions or granted_by_authorization_filters+ return one_of_permissions_or_auth_filter_required(context, all_permissions)@classmethoddef mutate(cls, root, info, **data):@@ -782,9 +744,12 @@ class FileUpload(BaseMutation):)error_type_class = UploadErrorerror_type_field = "upload_errors"+ permissions = (+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ )@classmethod- @staff_member_or_app_requireddef perform_mutation(cls, _root, info, **data):file_data = info.context.FILES.get(data["file"])diff --git a/saleor/graphql/csv/schema.py b/saleor/graphql/csv/schema.pyindex 8e552898e7..cad5a4d769 100644--- a/saleor/graphql/csv/schema.py+++ b/saleor/graphql/csv/schema.py@@ -2,9 +2,8 @@ import graphenefrom ...core.permissions import ProductPermissionsfrom ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.fields import FilterConnectionField+from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.utils import from_global_id_or_error-from ..decorators import permission_requiredfrom .filters import ExportFileFilterInputfrom .mutations import ExportGiftCards, ExportProductsfrom .resolvers import resolve_export_file, resolve_export_files@@ -13,26 +12,26 @@ from .types import ExportFile, ExportFileCountableConnectionclass CsvQueries(graphene.ObjectType):- export_file = graphene.Field(+ export_file = PermissionsField(ExportFile,id=graphene.Argument(graphene.ID, description="ID of the export file job.", required=True),description="Look up a export file by ID.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)export_files = FilterConnectionField(ExportFileCountableConnection,filter=ExportFileFilterInput(description="Filtering options for export files."),sort_by=ExportFileSortingInput(description="Sort export files."),description="List of export files.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)- @permission_required(ProductPermissions.MANAGE_PRODUCTS)- def resolve_export_file(self, info, id):+ def resolve_export_file(self, _info, id):_, id = from_global_id_or_error(id, ExportFile)return resolve_export_file(id)- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_export_files(self, info, **kwargs):qs = resolve_export_files()qs = filter_connection_queryset(qs, kwargs)diff --git a/saleor/graphql/csv/types.py b/saleor/graphql/csv/types.pyindex c4699ea706..155558f19b 100644--- a/saleor/graphql/csv/types.py+++ b/saleor/graphql/csv/types.py@@ -1,9 +1,9 @@import graphene-from ...core.permissions import AccountPermissions, AppPermission+from ...core.permissions import AccountPermissions, AppPermission, AuthorizationFiltersfrom ...csv import modelsfrom ..account.types import User-from ..account.utils import check_requestor_access+from ..account.utils import check_is_owner_or_has_one_of_permsfrom ..app.dataloaders import AppByIdLoaderfrom ..app.types import Appfrom ..core.connection import CountableConnection@@ -19,10 +19,21 @@ class ExportEvent(ModelObjectType):)type = ExportEventEnum(description="Export event type.", required=True)user = graphene.Field(- User, description="User who performed the action.", required=False+ User,+ description=(+ "User who performed the action. Requires one of the following "+ f"permissions: {AuthorizationFilters.OWNER}, "+ f"{AccountPermissions.MANAGE_STAFF}."+ ),+ required=False,)app = graphene.Field(- App, description="App which performed the action.", required=False+ App,+ description=(+ "App which performed the action. Requires one of the following "+ f"permissions: {AuthorizationFilters.OWNER}, {AppPermission.MANAGE_APPS}."+ ),+ required=False,)message = graphene.String(description="Content of the event.",@@ -37,13 +48,17 @@ class ExportEvent(ModelObjectType):@staticmethoddef resolve_user(root: models.ExportEvent, info):requestor = get_user_or_app_from_context(info.context)- check_requestor_access(requestor, root.user, AccountPermissions.MANAGE_STAFF)+ check_is_owner_or_has_one_of_perms(+ requestor, root.user, AccountPermissions.MANAGE_STAFF+ )return root.user@staticmethoddef resolve_app(root: models.ExportEvent, info):requestor = get_user_or_app_from_context(info.context)- check_requestor_access(requestor, root.user, AppPermission.MANAGE_APPS)+ check_is_owner_or_has_one_of_perms(+ requestor, root.user, AppPermission.MANAGE_APPS+ )return root.app@staticmethod@@ -76,13 +91,17 @@ class ExportFile(ModelObjectType):@staticmethoddef resolve_user(root: models.ExportFile, info):requestor = get_user_or_app_from_context(info.context)- check_requestor_access(requestor, root.user, AccountPermissions.MANAGE_STAFF)+ check_is_owner_or_has_one_of_perms(+ requestor, root.user, AccountPermissions.MANAGE_STAFF+ )return root.user@staticmethoddef resolve_app(root: models.ExportFile, info):requestor = get_user_or_app_from_context(info.context)- check_requestor_access(requestor, root.user, AppPermission.MANAGE_APPS)+ check_is_owner_or_has_one_of_perms(+ requestor, root.user, AppPermission.MANAGE_APPS+ )return AppByIdLoader(info.context).load(root.app_id) if root.app_id else None@staticmethoddiff --git a/saleor/graphql/decorators.py b/saleor/graphql/decorators.pyindex 353e392161..bb60a21857 100644--- a/saleor/graphql/decorators.py+++ b/saleor/graphql/decorators.py@@ -14,6 +14,7 @@ from ..core.permissions import (has_one_of_permissions,is_app,is_staff_user,+ one_of_permissions_or_auth_filter_required,)from ..core.permissions import permission_required as core_permission_requiredfrom .utils import get_user_or_app_from_context@@ -69,7 +70,7 @@ def permission_required(perm: Union[Enum, Iterable[Enum]]):perms = permrequestor = get_user_or_app_from_context(context)- if not core_permission_required(perms, requestor):+ if not core_permission_required(requestor, perms):raise PermissionDenied(permissions=perms)return account_passes_test(check_perms)@@ -77,8 +78,7 @@ def permission_required(perm: Union[Enum, Iterable[Enum]]):def one_of_permissions_required(perms: Iterable[Enum]):def check_perms(context):- requestor = get_user_or_app_from_context(context)- if not has_one_of_permissions(requestor, perms):+ if not one_of_permissions_or_auth_filter_required(context, perms):raise PermissionDenied(permissions=perms)return account_passes_test(check_perms)diff --git a/saleor/graphql/discount/schema.py b/saleor/graphql/discount/schema.pyindex f81644e270..7da2964851 100644--- a/saleor/graphql/discount/schema.py+++ b/saleor/graphql/discount/schema.py@@ -3,10 +3,9 @@ import graphenefrom ...core.permissions import DiscountPermissionsfrom ..core.connection import create_connection_slice, filter_connection_querysetfrom ..core.descriptions import DEPRECATED_IN_3X_INPUT-from ..core.fields import FilterConnectionField+from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.types import FilterInputObjectTypefrom ..core.utils import from_global_id_or_error-from ..decorators import permission_requiredfrom ..translations.mutations import SaleTranslate, VoucherTranslatefrom .bulk_mutations import SaleBulkDelete, VoucherBulkDeletefrom .filters import SaleFilter, VoucherFilter@@ -40,13 +39,16 @@ class SaleFilterInput(FilterInputObjectType):class DiscountQueries(graphene.ObjectType):- sale = graphene.Field(+ sale = PermissionsField(Sale,id=graphene.Argument(graphene.ID, description="ID of the sale.", required=True),channel=graphene.String(description="Slug of a channel for which the data should be returned."),description="Look up a sale by ID.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)sales = FilterConnectionField(SaleCountableConnection,@@ -62,8 +64,11 @@ class DiscountQueries(graphene.ObjectType):description="Slug of a channel for which the data should be returned."),description="List of the shop's sales.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)- voucher = graphene.Field(+ voucher = PermissionsField(Voucher,id=graphene.Argument(graphene.ID, description="ID of the voucher.", required=True@@ -72,6 +77,9 @@ class DiscountQueries(graphene.ObjectType):description="Slug of a channel for which the data should be returned."),description="Look up a voucher by ID.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)vouchers = FilterConnectionField(VoucherCountableConnection,@@ -87,26 +95,25 @@ class DiscountQueries(graphene.ObjectType):description="Slug of a channel for which the data should be returned."),description="List of the shop's vouchers.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_sale(self, info, id, channel=None):_, id = from_global_id_or_error(id, Sale)return resolve_sale(id, channel)- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_sales(self, info, channel=None, **kwargs):qs = resolve_sales(info, channel_slug=channel, **kwargs)kwargs["channel"] = channelqs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, SaleCountableConnection)- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_voucher(self, info, id, channel=None):_, id = from_global_id_or_error(id, Voucher)return resolve_voucher(id, channel)- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_vouchers(self, info, channel=None, **kwargs):qs = resolve_vouchers(info, channel_slug=channel, **kwargs)kwargs["channel"] = channeldiff --git a/saleor/graphql/discount/types.py b/saleor/graphql/discount/types.pyindex c07ee122be..c03a93115a 100644--- a/saleor/graphql/discount/types.py+++ b/saleor/graphql/discount/types.py@@ -14,10 +14,9 @@ from ..channel.types import (from ..core import typesfrom ..core.connection import CountableConnection, create_connection_slicefrom ..core.descriptions import ADDED_IN_31-from ..core.fields import ConnectionField+from ..core.fields import ConnectionField, PermissionsFieldfrom ..core.scalars import PositiveDecimalfrom ..core.types import ModelObjectType, Money, NonNullList-from ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadatafrom ..product.types import (CategoryCountableConnection,@@ -72,22 +71,35 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType):collections = ConnectionField(CollectionCountableConnection,description="List of collections this sale applies to.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)products = ConnectionField(- ProductCountableConnection, description="List of products this sale applies to."+ ProductCountableConnection,+ description="List of products this sale applies to.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)variants = ConnectionField(ProductVariantCountableConnection,description=f"{ADDED_IN_31} List of product variants this sale applies to.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)translation = TranslationField(SaleTranslation,type_name="sale",resolver=ChannelContextType.resolve_translation,)- channel_listings = NonNullList(- SaleChannelListing,+ channel_listings = PermissionsField(+ NonNullList(SaleChannelListing),description="List of channels available for the sale.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)discount_value = graphene.Float(description="Sale value.")currency = graphene.String(description="Currency code for sale.")@@ -111,26 +123,22 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType):return create_connection_slice(qs, info, kwargs, CategoryCountableConnection)@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_channel_listings(root: ChannelContext[models.Sale], info, **_kwargs):return SaleChannelListingBySaleIdLoader(info.context).load(root.node.id)@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_collections(root: ChannelContext[models.Sale], info, *_args, **kwargs):qs = root.node.collections.all()qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)return create_connection_slice(qs, info, kwargs, CollectionCountableConnection)@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_products(root: ChannelContext[models.Sale], info, **kwargs):qs = root.node.products.all()qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)return create_connection_slice(qs, info, kwargs, ProductCountableConnection)@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_variants(root: ChannelContext[models.Sale], info, **kwargs):qs = root.node.variants.all()qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)@@ -210,14 +218,23 @@ class Voucher(ChannelContextTypeWithMetadata, ModelObjectType):collections = ConnectionField(CollectionCountableConnection,description="List of collections this voucher applies to.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)products = ConnectionField(ProductCountableConnection,description="List of products this voucher applies to.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)variants = ConnectionField(ProductVariantCountableConnection,description=f"{ADDED_IN_31} List of product variants this voucher applies to.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)countries = NonNullList(types.CountryDisplay,@@ -238,9 +255,12 @@ class Voucher(ChannelContextTypeWithMetadata, ModelObjectType):Money, description="Minimum order value to apply voucher.")type = VoucherTypeEnum(description="Determines a type of voucher.", required=True)- channel_listings = NonNullList(- VoucherChannelListing,+ channel_listings = PermissionsField(+ NonNullList(VoucherChannelListing),description="List of availability in channels for the voucher.",+ permissions=[+ DiscountPermissions.MANAGE_DISCOUNTS,+ ],)class Meta:@@ -261,7 +281,6 @@ class Voucher(ChannelContextTypeWithMetadata, ModelObjectType):return create_connection_slice(qs, info, kwargs, CategoryCountableConnection)@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_collections(root: ChannelContext[models.Voucher], info, *_args, **kwargs):@@ -270,14 +289,12 @@ class Voucher(ChannelContextTypeWithMetadata, ModelObjectType):return create_connection_slice(qs, info, kwargs, CollectionCountableConnection)@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_products(root: ChannelContext[models.Voucher], info, **kwargs):qs = root.node.products.all()qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)return create_connection_slice(qs, info, kwargs, ProductCountableConnection)@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_variants(root: ChannelContext[models.Voucher], info, **kwargs):qs = root.node.variants.all()qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)@@ -338,7 +355,6 @@ class Voucher(ChannelContextTypeWithMetadata, ModelObjectType):)@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_channel_listings(root: ChannelContext[models.Voucher], info, **_kwargs):return VoucherChannelListingByVoucherIdLoader(info.context).load(root.node.id)@@ -362,8 +378,13 @@ class OrderDiscount(ModelObjectType):required=True,description="Value of the discount. Can store fixed value or percent value",)- reason = graphene.String(- required=False, description="Explanation for the applied discount."+ reason = PermissionsField(+ graphene.String,+ required=False,+ description="Explanation for the applied discount.",+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)amount = graphene.Field(Money, description="Returns amount of discount.", required=True@@ -377,6 +398,5 @@ class OrderDiscount(ModelObjectType):model = models.OrderDiscount@staticmethod- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_reason(root: models.OrderDiscount, _info):return root.reasondiff --git a/saleor/graphql/giftcard/schema.py b/saleor/graphql/giftcard/schema.pyindex c55a45ed1a..18317d2c8e 100644--- a/saleor/graphql/giftcard/schema.py+++ b/saleor/graphql/giftcard/schema.py@@ -5,10 +5,9 @@ from ...core.permissions import GiftcardPermissionsfrom ...giftcard import modelsfrom ..core.connection import create_connection_slice, filter_connection_querysetfrom ..core.descriptions import ADDED_IN_31, PREVIEW_FEATURE-from ..core.fields import FilterConnectionField+from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.types import NonNullListfrom ..core.utils import from_global_id_or_error-from ..decorators import permission_requiredfrom .bulk_mutations import (GiftCardBulkActivate,GiftCardBulkCreate,@@ -31,12 +30,15 @@ from .types import GiftCard, GiftCardCountableConnection, GiftCardTagCountableCoclass GiftCardQueries(graphene.ObjectType):- gift_card = graphene.Field(+ gift_card = PermissionsField(GiftCard,id=graphene.Argument(graphene.ID, description="ID of the gift card.", required=True),description="Look up a gift card by ID.",+ permissions=[+ GiftcardPermissions.MANAGE_GIFT_CARD,+ ],)gift_cards = FilterConnectionField(GiftCardCountableConnection,@@ -49,11 +51,17 @@ class GiftCardQueries(graphene.ObjectType):)),description="List of gift cards.",+ permissions=[+ GiftcardPermissions.MANAGE_GIFT_CARD,+ ],)- gift_card_currencies = NonNullList(- graphene.String,+ gift_card_currencies = PermissionsField(+ NonNullList(graphene.String),description=f"{ADDED_IN_31} List of gift card currencies. {PREVIEW_FEATURE}",required=True,+ permissions=[+ GiftcardPermissions.MANAGE_GIFT_CARD,+ ],)gift_card_tags = FilterConnectionField(GiftCardTagCountableConnection,@@ -61,14 +69,15 @@ class GiftCardQueries(graphene.ObjectType):description="Filtering options for gift card tags."),description=f"{ADDED_IN_31} List of gift card tags. {PREVIEW_FEATURE}",+ permissions=[+ GiftcardPermissions.MANAGE_GIFT_CARD,+ ],)- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)def resolve_gift_card(self, info, **data):_, id = from_global_id_or_error(data.get("id"), GiftCard)return resolve_gift_card(id)- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)def resolve_gift_cards(self, info, **data):sorting_by_balance = "sort_by" in data and "current_balance_amount" in data["sort_by"@@ -80,11 +89,9 @@ class GiftCardQueries(graphene.ObjectType):qs = filter_connection_queryset(qs, data)return create_connection_slice(qs, info, data, GiftCardCountableConnection)- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)def resolve_gift_card_currencies(self, info, **data):return set(models.GiftCard.objects.values_list("currency", flat=True))- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)def resolve_gift_card_tags(self, info, **data):qs = resolve_gift_card_tags()qs = filter_connection_queryset(qs, data)diff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.pyindex 066b431d94..22022e66fd 100644--- a/saleor/graphql/giftcard/types.py+++ b/saleor/graphql/giftcard/types.py@@ -15,15 +15,18 @@ from ...core.permissions import (from ...core.tracing import traced_resolverfrom ...giftcard import GiftCardEvents, modelsfrom ..account.dataloaders import UserByUserIdLoader-from ..account.utils import check_requestor_access, requestor_has_access+from ..account.utils import (+ check_is_owner_or_has_one_of_perms,+ is_owner_or_has_one_of_perms,+)from ..app.dataloaders import AppByIdLoaderfrom ..app.types import Appfrom ..channel import ChannelContextfrom ..channel.dataloaders import ChannelByIdLoaderfrom ..core.connection import CountableConnectionfrom ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE+from ..core.fields import PermissionsFieldfrom ..core.types import ModelObjectType, Money, NonNullList-from ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadatafrom ..order.dataloaders import OrderByIdLoaderfrom ..product.dataloaders.products import ProductByIdLoader@@ -68,9 +71,19 @@ class GiftCardEvent(ModelObjectType):type = GiftCardEventsEnum(description="Gift card event type.")user = graphene.Field("saleor.graphql.account.types.User",- description="User who performed the action.",+ description=(+ "User who performed the action. Requires one of the following "+ f"permissions: {AccountPermissions.MANAGE_USERS}, "+ f"{AccountPermissions.MANAGE_STAFF}, {AuthorizationFilters.OWNER}."+ ),+ )+ app = graphene.Field(+ App,+ description=(+ "App that performed the action. Requires one of the following permissions: "+ f"{AppPermission.MANAGE_APPS}, {AuthorizationFilters.OWNER}."+ ),)- app = graphene.Field(App, description="App that performed the action.")message = graphene.String(description="Content of the event.")email = graphene.String(description="Email of the customer.")order_id = graphene.ID(@@ -104,19 +117,13 @@ class GiftCardEvent(ModelObjectType):def resolve_user(root: models.GiftCardEvent, info):def _resolve_user(event_user):requester = get_user_or_app_from_context(info.context)- if (- requester == event_user- or requester.has_perm(AccountPermissions.MANAGE_USERS)- or requester.has_perm(AccountPermissions.MANAGE_STAFF)- ):- return event_user- return PermissionDenied(- permissions=[- AccountPermissions.MANAGE_STAFF,- AccountPermissions.MANAGE_USERS,- AuthorizationFilters.OWNER,- ]+ check_is_owner_or_has_one_of_perms(+ requester,+ event_user,+ AccountPermissions.MANAGE_USERS,+ AccountPermissions.MANAGE_STAFF,)+ return event_userif root.user_id is None:return _resolve_user(None)@@ -127,11 +134,10 @@ class GiftCardEvent(ModelObjectType):def resolve_app(root: models.GiftCardEvent, info):def _resolve_app(app):requester = get_user_or_app_from_context(info.context)- if requester == app or requester.has_perm(AppPermission.MANAGE_APPS):- return app- return PermissionDenied(- permissions=[AppPermission.MANAGE_APPS, AuthorizationFilters.OWNER]+ check_is_owner_or_has_one_of_perms(+ requester, app, AppPermission.MANAGE_APPS)+ return appif root.app_id is None:return _resolve_app(None)@@ -230,9 +236,9 @@ class GiftCard(ModelObjectType):)code = graphene.String(description=(- "Gift card code. "- "Can be fetched by staff member with manage gift card permission when "- "gift card wasn't used yet and by the gift card owner."+ "Gift card code. Can be fetched by a staff member with "+ f"{GiftcardPermissions.MANAGE_GIFT_CARD} when gift card wasn't yet used "+ "and by the gift card owner."),required=True,)@@ -254,6 +260,8 @@ class GiftCard(ModelObjectType):required=False,description=(f"{ADDED_IN_31} Email address of the user who bought or issued gift card. "+ "Requires one of the following permissions: "+ f"{AccountPermissions.MANAGE_USERS}, {AuthorizationFilters.OWNER}. "f"{PREVIEW_FEATURE}"),)@@ -268,14 +276,18 @@ class GiftCard(ModelObjectType):expiry_date = graphene.Date()app = graphene.Field(App,- description=f"{ADDED_IN_31} App which created the gift card. {PREVIEW_FEATURE}",+ description=(+ f"{ADDED_IN_31} App which created the gift card. Requires one of the "+ f"following permissions: {AppPermission.MANAGE_APPS}, "+ f"{AuthorizationFilters.OWNER}. {PREVIEW_FEATURE}"+ ),)product = graphene.Field("saleor.graphql.product.types.products.Product",description=f"{ADDED_IN_31} Related gift card product. {PREVIEW_FEATURE}",)- events = NonNullList(- GiftCardEvent,+ events = PermissionsField(+ NonNullList(GiftCardEvent),filter=GiftCardEventFilterInput(description="Filtering options for gift card events."),@@ -284,11 +296,17 @@ class GiftCard(ModelObjectType):f"{PREVIEW_FEATURE}"),required=True,+ permissions=[+ GiftcardPermissions.MANAGE_GIFT_CARD,+ ],)- tags = NonNullList(- GiftCardTag,+ tags = PermissionsField(+ NonNullList(GiftCardTag),description=f"{ADDED_IN_31} The gift card tag. {PREVIEW_FEATURE}",required=True,+ permissions=[+ GiftcardPermissions.MANAGE_GIFT_CARD,+ ],)bought_in_channel = graphene.String(description=(@@ -362,7 +380,9 @@ class GiftCard(ModelObjectType):def resolve_created_by(root: models.GiftCard, info):def _resolve_created_by(user):requestor = get_user_or_app_from_context(info.context)- check_requestor_access(requestor, user, AccountPermissions.MANAGE_USERS)+ check_is_owner_or_has_one_of_perms(+ requestor, user, AccountPermissions.MANAGE_USERS+ )return userif root.created_by_id is None:@@ -374,7 +394,9 @@ class GiftCard(ModelObjectType):def resolve_used_by(root: models.GiftCard, info):def _resolve_used_by(user):requestor = get_user_or_app_from_context(info.context)- if requestor_has_access(requestor, user, AccountPermissions.MANAGE_USERS):+ if is_owner_or_has_one_of_perms(+ requestor, user, AccountPermissions.MANAGE_USERS+ ):return userif not root.used_by_id:@@ -390,7 +412,7 @@ class GiftCard(ModelObjectType):def resolve_created_by_email(root: models.GiftCard, info):def _resolve_created_by_email(user):requester = get_user_or_app_from_context(info.context)- if requestor_has_access(+ if is_owner_or_has_one_of_perms(requester, user, GiftcardPermissions.MANAGE_GIFT_CARD):return user.email if user else root.created_by_email@@ -409,7 +431,7 @@ class GiftCard(ModelObjectType):def resolve_used_by_email(root: models.GiftCard, info):def _resolve_used_by_email(user):requester = get_user_or_app_from_context(info.context)- if requestor_has_access(+ if is_owner_or_has_one_of_perms(requester, user, GiftcardPermissions.MANAGE_GIFT_CARD):return user.email if user else root.used_by_email@@ -428,11 +450,10 @@ class GiftCard(ModelObjectType):def resolve_app(root: models.GiftCard, info):def _resolve_app(app):requester = get_user_or_app_from_context(info.context)- if requester == app or requester.has_perm(AppPermission.MANAGE_APPS):- return app- return PermissionDenied(- permissions=[AppPermission.MANAGE_APPS, AuthorizationFilters.OWNER]+ check_is_owner_or_has_one_of_perms(+ requester, app, AppPermission.MANAGE_APPS)+ return appif root.app_id is None:return _resolve_app(None)@@ -449,7 +470,6 @@ class GiftCard(ModelObjectType):)@staticmethod- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)def resolve_events(root: models.GiftCard, info, **kwargs):def filter_events(events):event_filter = kwargs.get("filter", {})@@ -466,7 +486,6 @@ class GiftCard(ModelObjectType):)@staticmethod- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)def resolve_tags(root: models.GiftCard, info):return GiftCardTagsByGiftCardIdLoader(info.context).load(root.id)@@ -513,7 +532,9 @@ class GiftCard(ModelObjectType):def resolve_user(root: models.GiftCard, info):def _resolve_user(user):requestor = get_user_or_app_from_context(info.context)- if requestor_has_access(requestor, user, AccountPermissions.MANAGE_USERS):+ if is_owner_or_has_one_of_perms(+ requestor, user, AccountPermissions.MANAGE_USERS+ ):return userif not root.created_by_id:diff --git a/saleor/graphql/menu/types.py b/saleor/graphql/menu/types.pyindex e43d01e4ec..0f535dc648 100644--- a/saleor/graphql/menu/types.py+++ b/saleor/graphql/menu/types.py@@ -69,8 +69,21 @@ class MenuItem(ChannelContextTypeWithMetadata, ModelObjectType):menu = graphene.Field(Menu, required=True)parent = graphene.Field(lambda: MenuItem)category = graphene.Field(Category)- collection = graphene.Field(Collection)- page = graphene.Field(Page)+ collection = graphene.Field(+ Collection,+ description=(+ "A collection associated with this menu item. Requires one of the "+ "following permissions to include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),+ )+ page = graphene.Field(+ Page,+ description=(+ "A page associated with this menu item. Requires one of the following "+ f"permissions to include unpublished items: {PagePermissions.MANAGE_PAGES}."+ ),+ )level = graphene.Int(required=True)children = NonNullList(lambda: MenuItem)url = graphene.String(description="URL to the menu item.")diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex 976c301ac8..e3a1d17f9f 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -4,11 +4,10 @@ from ...core.permissions import OrderPermissionsfrom ..core.connection import create_connection_slice, filter_connection_querysetfrom ..core.descriptions import DEPRECATED_IN_3X_FIELDfrom ..core.enums import ReportingPeriod-from ..core.fields import ConnectionField, FilterConnectionField+from ..core.fields import ConnectionField, FilterConnectionField, PermissionsFieldfrom ..core.scalars import UUIDfrom ..core.types import FilterInputObjectType, TaxedMoneyfrom ..core.utils import from_global_id_or_error-from ..decorators import permission_requiredfrom .bulk_mutations.draft_orders import DraftOrderBulkDelete, DraftOrderLinesBulkDeletefrom .bulk_mutations.orders import OrderBulkCancelfrom .filters import DraftOrderFilter, OrderFilter@@ -76,11 +75,17 @@ class OrderQueries(graphene.ObjectType):"List of activity events to display on ""homepage (at the moment it only contains order-events)."),+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)- order = graphene.Field(+ order = PermissionsField(Order,description="Look up an order by ID.",id=graphene.Argument(graphene.ID, description="ID of an order.", required=True),+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)orders = FilterConnectionField(OrderCountableConnection,@@ -90,14 +95,20 @@ class OrderQueries(graphene.ObjectType):description="Slug of a channel for which the data should be returned."),description="List of orders.",+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)draft_orders = FilterConnectionField(OrderCountableConnection,sort_by=OrderSortingInput(description="Sort draft orders."),filter=OrderDraftFilterInput(description="Filtering options for draft orders."),description="List of draft orders.",+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)- orders_total = graphene.Field(+ orders_total = PermissionsField(TaxedMoney,description="Return the total sales amount from a specific period.",period=graphene.Argument(ReportingPeriod, description="A period of time."),@@ -105,6 +116,9 @@ class OrderQueries(graphene.ObjectType):graphene.String,description="Slug of a channel for which the data should be returned.",),+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)order_by_token = graphene.Field(Order,@@ -112,29 +126,24 @@ class OrderQueries(graphene.ObjectType):token=graphene.Argument(UUID, description="The order's token.", required=True),)- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_homepage_events(self, info, *_args, **kwargs):qs = resolve_homepage_events()return create_connection_slice(qs, info, kwargs, OrderEventCountableConnection)- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_order(self, info, **data):_, id = from_global_id_or_error(data.get("id"), Order)return resolve_order(id)- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_orders(self, info, channel=None, **kwargs):qs = resolve_orders(info, channel)qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, OrderCountableConnection)- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_draft_orders(self, info, **kwargs):qs = resolve_draft_orders(info)qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, OrderCountableConnection)- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_orders_total(self, info, period, channel=None, **_kwargs):return resolve_orders_total(info, period, channel)diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex dd1eef6932..db8ebaa005 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -15,6 +15,7 @@ from ...core.anonymize import obfuscate_address, obfuscate_emailfrom ...core.permissions import (AccountPermissions,AppPermission,+ AuthorizationFilters,OrderPermissions,ProductPermissions,has_one_of_permissions,@@ -46,7 +47,10 @@ from ...shipping.models import ShippingMethodChannelListingfrom ...shipping.utils import convert_to_shipping_method_datafrom ..account.dataloaders import AddressByIdLoader, UserByUserIdLoaderfrom ..account.types import User-from ..account.utils import check_requestor_access, requestor_has_access+from ..account.utils import (+ check_is_owner_or_has_one_of_perms,+ is_owner_or_has_one_of_perms,+)from ..app.dataloaders import AppByIdLoaderfrom ..app.types import Appfrom ..channel import ChannelContext@@ -55,6 +59,7 @@ from ..channel.types import Channelfrom ..core.connection import CountableConnectionfrom ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATUREfrom ..core.enums import LanguageCodeEnum+from ..core.fields import PermissionsFieldfrom ..core.mutations import validation_error_to_error_typefrom ..core.scalars import PositiveDecimalfrom ..core.types import (@@ -67,7 +72,6 @@ from ..core.types import (Weight,)from ..core.utils import str_to_enum-from ..decorators import one_of_permissions_required, permission_requiredfrom ..discount.dataloaders import OrderDiscountsByOrderIDLoader, VoucherByIdLoaderfrom ..discount.enums import DiscountValueTypeEnumfrom ..discount.types import Voucher@@ -179,7 +183,14 @@ class OrderEvent(ModelObjectType):)type = OrderEventsEnum(description="Order event type.")user = graphene.Field(User, description="User who performed the action.")- app = graphene.Field(App, description="App that performed the action.")+ app = graphene.Field(+ App,+ description=(+ "App that performed the action. Requires of of the following permissions: "+ f"{AppPermission.MANAGE_APPS}, {OrderPermissions.MANAGE_ORDERS}, "+ f"{AuthorizationFilters.OWNER}."+ ),+ )message = graphene.String(description="Content of the event.")email = graphene.String(description="Email of the customer.")email_type = OrderEventsEmailsEnum(@@ -242,7 +253,7 @@ class OrderEvent(ModelObjectType):@staticmethoddef resolve_app(root: models.OrderEvent, info):requestor = get_user_or_app_from_context(info.context)- check_requestor_access(+ check_is_owner_or_has_one_of_perms(requestor,root.user,AppPermission.MANAGE_APPS,@@ -486,7 +497,9 @@ class OrderLine(ModelObjectType):required=False,description=("A purchased product variant. Note: this field may be null if the variant "- "has been removed from stock at all."+ "has been removed from stock at all. Requires one of the following "+ "permissions to include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."),)translated_product_name = graphene.String(@@ -495,9 +508,13 @@ class OrderLine(ModelObjectType):translated_variant_name = graphene.String(required=True, description="Variant name in the customer's language")- allocations = NonNullList(- Allocation,+ allocations = PermissionsField(+ NonNullList(Allocation),description="List of allocations across warehouses.",+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ],)quantity_to_fulfill = graphene.Int(required=True,@@ -627,9 +644,6 @@ class OrderLine(ModelObjectType):return Promise.all([variant, channel]).then(requestor_has_access_to_variant)@staticmethod- @one_of_permissions_required(- [ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]- )def resolve_allocations(root: models.OrderLine, info):return AllocationsByOrderLineIdLoader(info.context).load(root.id)@@ -639,10 +653,32 @@ class Order(ModelObjectType):created = graphene.DateTime(required=True)updated_at = graphene.DateTime(required=True)status = OrderStatusEnum(required=True)- user = graphene.Field(User)+ user = graphene.Field(+ User,+ description=(+ "User who placed the order. This field is set only for orders placed by "+ "authenticated users. Requires one of the following permissions: "+ f"{AccountPermissions.MANAGE_USERS}, {OrderPermissions.MANAGE_ORDERS}, "+ f"{AuthorizationFilters.OWNER}."+ ),+ )tracking_client_id = graphene.String(required=True)- billing_address = graphene.Field("saleor.graphql.account.types.Address")- shipping_address = graphene.Field("saleor.graphql.account.types.Address")+ billing_address = graphene.Field(+ "saleor.graphql.account.types.Address",+ description=(+ "Billing address. Requires one of the following permissions to view the "+ f"full data: {OrderPermissions.MANAGE_ORDERS}, "+ f"{AuthorizationFilters.OWNER}."+ ),+ )+ shipping_address = graphene.Field(+ "saleor.graphql.account.types.Address",+ description=(+ "Shipping address. Requires one of the following permissions to view the "+ f"full data: {OrderPermissions.MANAGE_ORDERS}, "+ f"{AuthorizationFilters.OWNER}."+ ),+ )shipping_method_name = graphene.String()collection_point_name = graphene.String()channel = graphene.Field(Channel, required=True)@@ -677,7 +713,12 @@ class Order(ModelObjectType):),)invoices = NonNullList(- Invoice, required=False, description="List of order invoices."+ Invoice,+ required=False,+ description=(+ "List of order invoices. Requires one of the following permissions: "+ f"{OrderPermissions.MANAGE_ORDERS}, {AuthorizationFilters.OWNER}."+ ),)number = graphene.String(description="User-friendly number of an order.")original = graphene.ID(@@ -744,8 +785,10 @@ class Order(ModelObjectType):total_captured = graphene.Field(Money, description="Amount captured by payment.", required=True)- events = NonNullList(- OrderEvent, description="List of events associated with the order."+ events = PermissionsField(+ NonNullList(OrderEvent),+ description="List of events associated with the order.",+ permissions=[OrderPermissions.MANAGE_ORDERS],)total_balance = graphene.Field(Money,@@ -753,7 +796,12 @@ class Order(ModelObjectType):required=True,)user_email = graphene.String(- required=False, description="Email address of the customer."+ required=False,+ description=(+ "Email address of the customer. Requires the following permissions to "+ f"access the full data: {OrderPermissions.MANAGE_ORDERS}, "+ f"{AuthorizationFilters.OWNER}"+ ),)is_shipping_required = graphene.Boolean(description="Returns True, if order requires shipping.", required=True@@ -887,7 +935,9 @@ class Order(ModelObjectType):user, address = datarequester = get_user_or_app_from_context(info.context)- if requestor_has_access(requester, user, OrderPermissions.MANAGE_ORDERS):+ if is_owner_or_has_one_of_perms(+ requester, user, OrderPermissions.MANAGE_ORDERS+ ):return addressreturn obfuscate_address(address)@@ -914,7 +964,9 @@ class Order(ModelObjectType):else:user, address = datarequester = get_user_or_app_from_context(info.context)- if requestor_has_access(requester, user, OrderPermissions.MANAGE_ORDERS):+ if is_owner_or_has_one_of_perms(+ requester, user, OrderPermissions.MANAGE_ORDERS+ ):return addressreturn obfuscate_address(address)@@ -1015,7 +1067,6 @@ class Order(ModelObjectType):return OrderLinesByOrderIdLoader(info.context).load(root.id)@staticmethod- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_events(root: models.Order, _info):return OrderEventsByOrderIdLoader(_info.context).load(root.id)@@ -1077,7 +1128,9 @@ class Order(ModelObjectType):def resolve_user_email(root: models.Order, info):def _resolve_user_email(user):requester = get_user_or_app_from_context(info.context)- if requestor_has_access(requester, user, OrderPermissions.MANAGE_ORDERS):+ if is_owner_or_has_one_of_perms(+ requester, user, OrderPermissions.MANAGE_ORDERS+ ):return user.email if user else root.user_emailreturn obfuscate_email(user.email if user else root.user_email)@@ -1094,7 +1147,7 @@ class Order(ModelObjectType):def resolve_user(root: models.Order, info):def _resolve_user(user):requester = get_user_or_app_from_context(info.context)- check_requestor_access(+ check_is_owner_or_has_one_of_perms(requester,user,AccountPermissions.MANAGE_USERS,@@ -1197,7 +1250,9 @@ class Order(ModelObjectType):@staticmethoddef resolve_invoices(root: models.Order, info):requester = get_user_or_app_from_context(info.context)- check_requestor_access(requester, root.user, OrderPermissions.MANAGE_ORDERS)+ check_is_owner_or_has_one_of_perms(+ requester, root.user, OrderPermissions.MANAGE_ORDERS+ )return root.invoices.all()@staticmethoddiff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.pyindex 051963a8f6..310eb5a8ea 100644--- a/saleor/graphql/page/types.py+++ b/saleor/graphql/page/types.py@@ -14,9 +14,8 @@ from ..core.connection import ()from ..core.descriptions import DEPRECATED_IN_3X_FIELDfrom ..core.federation import federated_entity, resolve_federation_references-from ..core.fields import FilterConnectionField, JSONString+from ..core.fields import FilterConnectionField, JSONString, PermissionsFieldfrom ..core.types import ModelObjectType, NonNullList-from ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadatafrom ..translations.fields import TranslationFieldfrom ..translations.types import PageTranslation@@ -40,8 +39,17 @@ class PageType(ModelObjectType):AttributeCountableConnection,filter=AttributeFilterInput(),description="Attributes that can be assigned to the page type.",+ permissions=[+ PagePermissions.MANAGE_PAGES,+ ],+ )+ has_pages = PermissionsField(+ graphene.Boolean,+ description="Whether page type has pages assigned.",+ permissions=[+ PagePermissions.MANAGE_PAGES,+ ],)- has_pages = graphene.Boolean(description="Whether page type has pages assigned.")class Meta:description = (@@ -60,7 +68,6 @@ class PageType(ModelObjectType):return PageAttributesByPageTypeIdLoader(info.context).load(root.pk)@staticmethod- @permission_required(PagePermissions.MANAGE_PAGES)def resolve_available_attributes(root: models.PageType, info, **kwargs):qs = attribute_models.Attribute.objects.get_unassigned_page_type_attributes(root.pk@@ -69,7 +76,6 @@ class PageType(ModelObjectType):return create_connection_slice(qs, info, kwargs, AttributeCountableConnection)@staticmethod- @permission_required(PagePermissions.MANAGE_PAGES)def resolve_has_pages(root: models.PageType, info, **kwargs):return (PagesByPageTypeIdLoader(info.context)diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.pyindex 2b9cc5b267..4fd440a924 100644--- a/saleor/graphql/payment/schema.py+++ b/saleor/graphql/payment/schema.py@@ -2,9 +2,8 @@ import graphenefrom ...core.permissions import OrderPermissionsfrom ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.fields import FilterConnectionField+from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.utils import from_global_id_or_error-from ..decorators import permission_requiredfrom .filters import PaymentFilterInputfrom .mutations import (PaymentCapture,@@ -18,25 +17,29 @@ from .types import Payment, PaymentCountableConnectionclass PaymentQueries(graphene.ObjectType):- payment = graphene.Field(+ payment = PermissionsField(Payment,description="Look up a payment by ID.",id=graphene.Argument(graphene.ID, description="ID of the payment.", required=True),+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)payments = FilterConnectionField(PaymentCountableConnection,filter=PaymentFilterInput(description="Filtering options for payments."),description="List of payments.",+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_payment(self, info, **data):_, id = from_global_id_or_error(data["id"], Payment)return resolve_payment_by_id(id)- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_payments(self, info, **kwargs):qs = resolve_payments(info)qs = filter_connection_queryset(qs, kwargs)diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.pyindex 76d180c1dc..abe28c653d 100644--- a/saleor/graphql/payment/types.py+++ b/saleor/graphql/payment/types.py@@ -8,9 +8,8 @@ from ...payment import modelsfrom ..checkout.dataloaders import CheckoutByTokenLoaderfrom ..core.connection import CountableConnectionfrom ..core.descriptions import ADDED_IN_31-from ..core.fields import JSONString+from ..core.fields import JSONString, PermissionsFieldfrom ..core.types import ModelObjectType, Money, NonNullList-from ..decorators import permission_requiredfrom ..meta.permissions import public_payment_permissionsfrom ..meta.resolvers import resolve_metadatafrom ..meta.types import MetadataItem, ObjectWithMetadata@@ -93,29 +92,44 @@ class Payment(ModelObjectType):checkout = graphene.Field("saleor.graphql.checkout.types.Checkout")order = graphene.Field("saleor.graphql.order.types.Order")payment_method_type = graphene.String(required=True)- customer_ip_address = graphene.String()+ customer_ip_address = PermissionsField(+ graphene.String,+ description="IP address of the user who created the payment.",+ permissions=[OrderPermissions.MANAGE_ORDERS],+ )charge_status = PaymentChargeStatusEnum(description="Internal payment status.", required=True)- actions = NonNullList(- OrderAction,+ actions = PermissionsField(+ NonNullList(OrderAction),description=("List of actions that can be performed in the current state of a payment."),required=True,+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)total = graphene.Field(Money, description="Total amount of the payment.")captured_amount = graphene.Field(Money, description="Total amount captured for this payment.")- transactions = NonNullList(- Transaction, description="List of all transactions within this payment."+ transactions = PermissionsField(+ NonNullList(Transaction),+ description="List of all transactions within this payment.",+ permissions=[+ OrderPermissions.MANAGE_ORDERS,+ ],)- available_capture_amount = graphene.Field(- Money, description="Maximum amount of money that can be captured."+ available_capture_amount = PermissionsField(+ Money,+ description="Maximum amount of money that can be captured.",+ permissions=[OrderPermissions.MANAGE_ORDERS],)- available_refund_amount = graphene.Field(- Money, description="Maximum amount of money that can be refunded."+ available_refund_amount = PermissionsField(+ Money,+ description="Maximum amount of money that can be refunded.",+ permissions=[OrderPermissions.MANAGE_ORDERS],)credit_card = graphene.Field(CreditCard, description="The details of the card used for this payment."@@ -135,12 +149,10 @@ class Payment(ModelObjectType):return root.modified_at@staticmethod- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_customer_ip_address(root: models.Payment, _info):return root.customer_ip_address@staticmethod- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_actions(root: models.Payment, _info):actions = []if root.can_capture():@@ -161,19 +173,16 @@ class Payment(ModelObjectType):return root.get_captured_amount()@staticmethod- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_transactions(root: models.Payment, _info):return root.transactions.all()@staticmethod- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_available_refund_amount(root: models.Payment, _info):if not root.can_refund():return Nonereturn root.get_captured_amount()@staticmethod- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_available_capture_amount(root: models.Payment, _info):if not root.can_capture():return Nonediff --git a/saleor/graphql/plugins/schema.py b/saleor/graphql/plugins/schema.pyindex 29b90b61ef..ffc5bfff83 100644--- a/saleor/graphql/plugins/schema.py+++ b/saleor/graphql/plugins/schema.py@@ -3,8 +3,7 @@ import graphenefrom ...core.permissions import PluginsPermissionsfrom ...core.tracing import traced_resolverfrom ..core.connection import create_connection_slice-from ..core.fields import ConnectionField-from ..decorators import permission_required+from ..core.fields import ConnectionField, PermissionsFieldfrom .filters import PluginFilterInputfrom .mutations import PluginUpdatefrom .resolvers import resolve_plugin, resolve_plugins@@ -13,12 +12,15 @@ from .types import Plugin, PluginCountableConnectionclass PluginsQueries(graphene.ObjectType):- plugin = graphene.Field(+ plugin = PermissionsField(Plugin,id=graphene.Argument(graphene.ID, description="ID of the plugin.", required=True),description="Look up a plugin by ID.",+ permissions=[+ PluginsPermissions.MANAGE_PLUGINS,+ ],)plugins = ConnectionField(@@ -26,14 +28,15 @@ class PluginsQueries(graphene.ObjectType):filter=PluginFilterInput(description="Filtering options for plugins."),sort_by=PluginSortingInput(description="Sort plugins."),description="List of plugins.",+ permissions=[+ PluginsPermissions.MANAGE_PLUGINS,+ ],)- @permission_required(PluginsPermissions.MANAGE_PLUGINS)@traced_resolverdef resolve_plugin(self, info, **data):return resolve_plugin(data.get("id"), info.context.plugins)- @permission_required(PluginsPermissions.MANAGE_PLUGINS)@traced_resolverdef resolve_plugins(self, info, **kwargs):qs = resolve_plugins(info.context.plugins, **kwargs)diff --git a/saleor/graphql/product/mutations/digital_contents.py b/saleor/graphql/product/mutations/digital_contents.pyindex 340466b5a0..c8297474aa 100644--- a/saleor/graphql/product/mutations/digital_contents.py+++ b/saleor/graphql/product/mutations/digital_contents.py@@ -2,13 +2,13 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom ....core.db.utils import set_mutation_flag_in_context+from ....core.exceptions import PermissionDeniedfrom ....core.permissions import ProductPermissionsfrom ....product import modelsfrom ....product.error_codes import ProductErrorCodefrom ...channel import ChannelContextfrom ...core.mutations import BaseMutation, ModelMutationfrom ...core.types import ProductError, Upload-from ...decorators import permission_requiredfrom ..types import DigitalContent, DigitalContentUrl, ProductVariant@@ -64,9 +64,9 @@ class DigitalContentCreate(BaseMutation):)error_type_class = ProductErrorerror_type_field = "product_errors"+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)@classmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def clean_input(cls, info, data, instance):if hasattr(instance, "digital_content"):instance.digital_content.delete()@@ -92,7 +92,6 @@ class DigitalContentCreate(BaseMutation):return data@classmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def perform_mutation(cls, _root, info, variant_id, **data):variant = cls.get_node_or_error(info, variant_id, "id", only_type=ProductVariant@@ -132,11 +131,14 @@ class DigitalContentDelete(BaseMutation):description = "Remove digital content assigned to given variant."error_type_class = ProductErrorerror_type_field = "product_errors"+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)@classmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def mutate(cls, root, info, **data):set_mutation_flag_in_context(info.context)+ if not cls.check_permissions(info.context):+ raise PermissionDenied(permissions=cls._meta.permissions)+result = info.context.plugins.perform_mutation(mutation_cls=cls, root=root, info=info, data=data)@@ -171,9 +173,9 @@ class DigitalContentUpdate(BaseMutation):description = "Update digital content."error_type_class = ProductErrorerror_type_field = "product_errors"+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)@classmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def clean_input(cls, info, data):use_default_settings = data.get("use_default_settings")if use_default_settings:@@ -196,7 +198,6 @@ class DigitalContentUpdate(BaseMutation):return data@classmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def perform_mutation(cls, _root, info, variant_id, **data):variant = cls.get_node_or_error(info, variant_id, "id", only_type=ProductVariant@@ -253,8 +254,4 @@ class DigitalContentUrlCreate(ModelMutation):object_type = DigitalContentUrlerror_type_class = ProductErrorerror_type_field = "product_errors"-- @classmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)- def mutate(cls, root, info, **data):- return super().mutate(root, info, **data)+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 8d67e7e0ed..70f5d891b6 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -10,11 +10,10 @@ from ..channel import ChannelContextfrom ..channel.utils import get_default_channel_slug_or_graphql_errorfrom ..core.connection import create_connection_slice, filter_connection_querysetfrom ..core.enums import ReportingPeriod-from ..core.fields import ConnectionField, FilterConnectionField+from ..core.fields import ConnectionField, FilterConnectionField, PermissionsFieldfrom ..core.types import NonNullListfrom ..core.utils import from_global_id_or_errorfrom ..core.validators import validate_one_of_args_is_in_query-from ..decorators import permission_requiredfrom ..translations.mutations import (CategoryTranslate,CollectionTranslate,@@ -141,15 +140,22 @@ def sort_field_from_kwargs(kwargs: dict) -> Optional[List[str]]:class ProductQueries(graphene.ObjectType):- digital_content = graphene.Field(+ digital_content = PermissionsField(DigitalContent,description="Look up digital content by ID.",id=graphene.Argument(graphene.ID, description="ID of the digital content.", required=True),+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ ],)digital_contents = ConnectionField(- DigitalContentCountableConnection, description="List of digital content."+ DigitalContentCountableConnection,+ description="List of digital content.",+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ ],)categories = FilterConnectionField(CategoryCountableConnection,@@ -177,13 +183,21 @@ class ProductQueries(graphene.ObjectType):channel=graphene.String(description="Slug of a channel for which the data should be returned."),- description="Look up a collection by ID.",+ description=(+ "Look up a collection by ID. Requires one of the following permissions to "+ "include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),)collections = FilterConnectionField(CollectionCountableConnection,filter=CollectionFilterInput(description="Filtering options for collections."),sort_by=CollectionSortingInput(description="Sort collections."),- description="List of the shop's collections.",+ description=(+ "List of the shop's collections. Requires one of the following permissions "+ "to include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),channel=graphene.String(description="Slug of a channel for which the data should be returned."),@@ -198,7 +212,11 @@ class ProductQueries(graphene.ObjectType):channel=graphene.String(description="Slug of a channel for which the data should be returned."),- description="Look up a product by ID.",+ description=(+ "Look up a product by ID. Requires one of the following permissions to "+ "include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),)products = FilterConnectionField(ProductCountableConnection,@@ -207,7 +225,11 @@ class ProductQueries(graphene.ObjectType):channel=graphene.String(description="Slug of a channel for which the data should be returned."),- description="List of the shop's products.",+ description=(+ "List of the shop's products. Requires one of the following permissions to "+ "include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),)product_type = graphene.Field(ProductType,@@ -236,7 +258,11 @@ class ProductQueries(graphene.ObjectType):channel=graphene.String(description="Slug of a channel for which the data should be returned."),- description="Look up a product variant by ID or SKU.",+ description=(+ "Look up a product variant by ID or SKU. Requires one of the following "+ "permissions to include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),)product_variants = FilterConnectionField(ProductVariantCountableConnection,@@ -250,7 +276,11 @@ class ProductQueries(graphene.ObjectType):description="Filtering options for product variant."),sort_by=ProductVariantSortingInput(description="Sort products variants."),- description="List of product variants.",+ description=(+ "List of product variants. Requires one of the following permissions to "+ "include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),)report_product_sales = ConnectionField(ProductVariantCountableConnection,@@ -262,6 +292,9 @@ class ProductQueries(graphene.ObjectType):required=True,),description="List of top selling products.",+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ ],)@staticmethod@@ -322,13 +355,11 @@ class ProductQueries(graphene.ObjectType):return create_connection_slice(qs, info, kwargs, CollectionCountableConnection)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_digital_content(_root, _info: graphene.ResolveInfo, id):_, id = from_global_id_or_error(id, DigitalContent)return resolve_digital_content_by_id(id)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_digital_contents(_root, info: graphene.ResolveInfo, **kwargs):qs = resolve_digital_contents(info)return create_connection_slice(@@ -459,7 +490,6 @@ class ProductQueries(graphene.ObjectType):)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)@traced_resolverdef resolve_report_product_sales(_root, info: graphene.ResolveInfo, period, channel, **kwargsdiff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex 57f50af336..8b1084cfe3 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -17,8 +17,8 @@ from ...account import types as account_typesfrom ...channel.dataloaders import ChannelByIdLoaderfrom ...channel.types import Channelfrom ...core.descriptions import ADDED_IN_31, PREVIEW_FEATURE+from ...core.fields import PermissionsFieldfrom ...core.types import ModelObjectType-from ...decorators import permission_requiredfrom ...discount.dataloaders import DiscountsByDateTimeLoaderfrom ..dataloaders import (CollectionsByProductIdLoader,@@ -44,8 +44,16 @@ class ProductChannelListing(ModelObjectType):discounted_price = graphene.Field(Money, description="The price of the cheapest variant (including discounts).")- purchase_cost = graphene.Field(MoneyRange, description="Purchase cost of product.")- margin = graphene.Field(Margin, description="Range of margin percentage value.")+ purchase_cost = PermissionsField(+ MoneyRange,+ description="Purchase cost of product.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],+ )+ margin = PermissionsField(+ Margin,+ description="Range of margin percentage value.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],+ )is_available_for_purchase = graphene.Boolean(description="Whether the product is available for purchase.")@@ -77,7 +85,6 @@ class ProductChannelListing(ModelObjectType):@staticmethod@traced_resolver- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_purchase_cost(root: models.ProductChannelListing, info, *_kwargs):channel = ChannelByIdLoader(info.context).load(root.channel_id)@@ -115,7 +122,6 @@ class ProductChannelListing(ModelObjectType):@staticmethod@traced_resolver- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_margin(root: models.ProductChannelListing, info, *_kwargs):channel = ChannelByIdLoader(info.context).load(root.channel_id)@@ -252,7 +258,11 @@ class ProductVariantChannelListing(ModelObjectType):channel = graphene.Field(Channel, required=True)price = graphene.Field(Money)cost_price = graphene.Field(Money, description="Cost price of the variant.")- margin = graphene.Int(description="Gross margin percentage value.")+ margin = PermissionsField(+ graphene.Int,+ description="Gross margin percentage value.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],+ )preorder_threshold = graphene.Field(PreorderThreshold,required=False,@@ -269,7 +279,6 @@ class ProductVariantChannelListing(ModelObjectType):return ChannelByIdLoader(info.context).load(root.channel_id)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_margin(root: models.ProductVariantChannelListing, *_args):return get_margin_for_variant_channel_listing(root)diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex d5e6fe6c10..7a371d8b73 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -9,6 +9,7 @@ from graphene import relayfrom ....attribute import models as attribute_modelsfrom ....core.permissions import (+ AuthorizationFilters,OrderPermissions,ProductPermissions,has_one_of_permissions,@@ -53,7 +54,12 @@ from ...core.descriptions import ()from ...core.enums import ReportingPeriodfrom ...core.federation import federated_entity, resolve_federation_references-from ...core.fields import ConnectionField, FilterConnectionField, JSONString+from ...core.fields import (+ ConnectionField,+ FilterConnectionField,+ JSONString,+ PermissionsField,+)from ...core.types import (Image,ModelObjectType,@@ -64,11 +70,6 @@ from ...core.types import (Weight,)from ...core.utils import from_global_id_or_error-from ...decorators import (- one_of_permissions_required,- permission_required,- staff_member_or_app_required,-)from ...discount.dataloaders import DiscountsByDateTimeLoaderfrom ...meta.types import ObjectWithMetadatafrom ...order.dataloaders import (@@ -195,12 +196,17 @@ class ProductPricingInfo(BasePricingInfo):class PreorderData(graphene.ObjectType):- global_threshold = graphene.Int(- required=False, description="The global preorder threshold for product variant."+ global_threshold = PermissionsField(+ graphene.Int,+ required=False,+ description="The global preorder threshold for product variant.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)- global_sold_units = graphene.Int(+ global_sold_units = PermissionsField(+ graphene.Int,required=True,description="Total number of sold product variant during preorder.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)end_date = graphene.DateTime(required=False, description="Preorder end date.")@@ -208,12 +214,10 @@ class PreorderData(graphene.ObjectType):description = "Represents preorder settings for product variant."@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_global_threshold(root, *_args):return root.global_threshold@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_global_sold_units(root, *_args):return root.global_sold_units@@ -233,9 +237,13 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):"gateway to resolve this object in a federated query."),)- channel_listings = NonNullList(- ProductVariantChannelListing,+ channel_listings = PermissionsField(+ NonNullList(ProductVariantChannelListing),description="List of price information in channels for the product.",+ permissions=[+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],)pricing = graphene.Field(VariantPricingInfo,@@ -255,8 +263,12 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):),)margin = graphene.Int(description="Gross margin percentage value.")- quantity_ordered = graphene.Int(description="Total quantity ordered.")- revenue = graphene.Field(+ quantity_ordered = PermissionsField(+ graphene.Int,+ description="Total quantity ordered.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],+ )+ revenue = PermissionsField(TaxedMoney,period=graphene.Argument(ReportingPeriod),description=(@@ -264,6 +276,7 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):"field should be queried using `reportProductSales` query as it uses ""optimizations suitable for such calculations."),+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)images = NonNullList(lambda: ProductImage,@@ -279,10 +292,12 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):type_name="product variant",resolver=ChannelContextType.resolve_translation,)- digital_content = graphene.Field(- DigitalContent, description="Digital content for the product variant."+ digital_content = PermissionsField(+ DigitalContent,+ description="Digital content for the product variant.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)- stocks = graphene.Field(+ stocks = PermissionsField(NonNullList(Stock),description="Stocks for the product variant.",address=destination_address_argument,@@ -293,6 +308,10 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):f"{DEPRECATED_IN_3X_INPUT} Use `address` argument instead."),),+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ],)quantity_available = graphene.Int(required=False,@@ -341,9 +360,6 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):return root.channel_slug@staticmethod- @one_of_permissions_required(- [ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]- )def resolve_stocks(root: ChannelContext[models.ProductVariant],info,@@ -472,7 +488,6 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):).load((root.node.id, country_code, str(root.channel_slug)))@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_digital_content(root: ChannelContext[models.ProductVariant], *_args):return getattr(root.node, "digital_content", None)@@ -512,7 +527,6 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):)@staticmethod- @staff_member_or_app_requireddef resolve_channel_listings(root: ChannelContext[models.ProductVariant], info, **_kwargs):@@ -605,14 +619,12 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_quantity_ordered(root: ChannelContext[models.ProductVariant], *_args):# This field is added through annotation when using the# `resolve_report_product_sales` resolver.return getattr(root.node, "quantity_ordered", None)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)@traced_resolverdef resolve_revenue(root: ChannelContext[models.ProductVariant], info, period):start_date = reporting_period_to_date(period)@@ -780,9 +792,10 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):required=True,description="List of attributes assigned to this product.",)- channel_listings = NonNullList(- ProductChannelListing,+ channel_listings = PermissionsField(+ NonNullList(ProductChannelListing),description="List of availability in channels for the product.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)media_by_id = graphene.Field(lambda: ProductMedia,@@ -798,7 +811,12 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):),)variants = NonNullList(- ProductVariant, description="List of variants for the product."+ ProductVariant,+ description=(+ "List of variants for the product. Requires the following permissions to "+ "include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),)media = NonNullList(lambda: ProductMedia,@@ -810,7 +828,12 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):deprecation_reason=f"{DEPRECATED_IN_3X_FIELD} Use the `media` field instead.",)collections = NonNullList(- lambda: Collection, description="List of collections for the product."+ lambda: Collection,+ description=(+ "List of collections for the product. Requires the following permissions "+ "to include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),)translation = TranslationField(ProductTranslation,@@ -1078,7 +1101,6 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):return variants.then(map_channel_context)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_channel_listings(root: ChannelContext[models.Product], info, **_kwargs):return ProductChannelListingByProductIdLoader(info.context).load(root.node.id)@@ -1258,7 +1280,10 @@ class ProductType(ModelObjectType):Attribute, description="Product attributes of that product type.")available_attributes = FilterConnectionField(- AttributeCountableConnection, filter=AttributeFilterInput()+ AttributeCountableConnection,+ filter=AttributeFilterInput(),+ description="List of attributes which can be assigned to this product type.",+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)class Meta:@@ -1352,7 +1377,6 @@ class ProductType(ModelObjectType):return create_connection_slice(qs, info, kwargs, ProductCountableConnection)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_available_attributes(root: models.ProductType, info, **kwargs):qs = attribute_models.Attribute.objects.get_unassigned_product_type_attributes(root.pk@@ -1411,9 +1435,12 @@ class Collection(ChannelContextTypeWithMetadata, ModelObjectType):type_name="collection",resolver=ChannelContextType.resolve_translation,)- channel_listings = NonNullList(- CollectionChannelListing,+ channel_listings = PermissionsField(+ NonNullList(CollectionChannelListing),description="List of channels in which the collection is available.",+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ ],)class Meta:@@ -1453,7 +1480,6 @@ class Collection(ChannelContextTypeWithMetadata, ModelObjectType):return create_connection_slice(qs, info, kwargs, ProductCountableConnection)@staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_channel_listings(root: ChannelContext[models.Collection], info):return CollectionChannelListingByCollectionIdLoader(info.context).load(root.node.id@@ -1517,7 +1543,11 @@ class Category(ModelObjectType):channel=graphene.String(description="Slug of a channel for which the data should be returned."),- description="List of products in the category.",+ description=(+ "List of products in the category. Requires the following permissions to "+ "include the unpublished items: "+ f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ ),)children = ConnectionField(lambda: CategoryCountableConnection,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 069c66a1a8..7f39c09b43 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5,13 +5,17 @@ schema {}type Query {- """Look up a webhook by ID."""+ """+ Look up a webhook by ID. Requires one of the following permissions: AppPermission.MANAGE_APPS, AuthorizationFilters.OWNER+ """webhook("""ID of the webhook."""id: ID!): Webhook- """List of all available webhook events."""+ """+ List of all available webhook events. Requires one of the following permissions: MANAGE_APPS.+ """webhookEvents: [WebhookEvent!] @deprecated(reason: "This field will be removed in Saleor 4.0. Use `WebhookEventTypeAsyncEnum` and `WebhookEventTypeSyncEnum` to get available event types.")"""@@ -22,13 +26,17 @@ type Query {eventType: WebhookSampleEventTypeEnum!): JSONString- """Look up a warehouse by ID."""+ """+ Look up a warehouse by ID. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS, MANAGE_SHIPPING.+ """warehouse("""ID of an warehouse"""id: ID!): Warehouse- """List of warehouses."""+ """+ List of warehouses. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS, MANAGE_SHIPPING.+ """warehouses(filter: WarehouseFilterInputsortBy: WarehouseSortingInput@@ -46,7 +54,9 @@ type Query {last: Int): WarehouseCountableConnection- """Returns a list of all translatable items of a given kind."""+ """+ Returns a list of all translatable items of a given kind. Requires one of the following permissions: MANAGE_TRANSLATIONS.+ """translations("""Kind of objects to retrieve."""kind: TranslatableKinds!@@ -63,6 +73,8 @@ type Query {"""Return the last n elements from the list."""last: Int): TranslatableItemConnection++ """ Requires one of the following permissions: MANAGE_TRANSLATIONS."""translation("""ID of the object to retrieve."""id: ID!@@ -71,13 +83,17 @@ type Query {kind: TranslatableKinds!): TranslatableItem- """Look up a stock by ID"""+ """+ Look up a stock by ID Requires one of the following permissions: MANAGE_PRODUCTS.+ """stock("""ID of an warehouse"""id: ID!): Stock- """List of stocks."""+ """+ List of stocks. Requires one of the following permissions: MANAGE_PRODUCTS.+ """stocks(filter: StockFilterInput@@ -97,13 +113,19 @@ type Query {"""Return information about the shop."""shop: Shop!- """Order related settings from site settings."""+ """+ Order related settings from site settings. Requires one of the following permissions: MANAGE_ORDERS.+ """orderSettings: OrderSettings- """Gift card related settings from site settings."""+ """+ Gift card related settings from site settings. Requires one of the following permissions: MANAGE_GIFT_CARD.+ """giftCardSettings: GiftCardSettings!- """Look up a shipping zone by ID."""+ """+ Look up a shipping zone by ID. Requires one of the following permissions: MANAGE_SHIPPING.+ """shippingZone("""ID of the shipping zone."""id: ID!@@ -112,7 +134,9 @@ type Query {channel: String): ShippingZone- """List of the shop's shipping zones."""+ """+ List of the shop's shipping zones. Requires one of the following permissions: MANAGE_SHIPPING.+ """shippingZones("""Filtering options for shipping zones."""filter: ShippingZoneFilterInput@@ -133,13 +157,17 @@ type Query {last: Int): ShippingZoneCountableConnection- """Look up digital content by ID."""+ """+ Look up digital content by ID. Requires one of the following permissions: MANAGE_PRODUCTS.+ """digitalContent("""ID of the digital content."""id: ID!): DigitalContent- """List of digital content."""+ """+ List of digital content. Requires one of the following permissions: MANAGE_PRODUCTS.+ """digitalContents("""Return the elements in the list that come before the specified cursor."""before: String@@ -187,7 +215,9 @@ type Query {slug: String): Category- """Look up a collection by ID."""+ """+ Look up a collection by ID. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """collection("""ID of the collection."""id: ID@@ -199,7 +229,9 @@ type Query {channel: String): Collection- """List of the shop's collections."""+ """+ List of the shop's collections. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """collections("""Filtering options for collections."""filter: CollectionFilterInput@@ -223,7 +255,9 @@ type Query {last: Int): CollectionCountableConnection- """Look up a product by ID."""+ """+ Look up a product by ID. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """product("""ID of the product."""id: ID@@ -235,7 +269,9 @@ type Query {channel: String): Product- """List of the shop's products."""+ """+ List of the shop's products. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """products("""Filtering options for products."""filter: ProductFilterInput@@ -286,7 +322,9 @@ type Query {last: Int): ProductTypeCountableConnection- """Look up a product variant by ID or SKU."""+ """+ Look up a product variant by ID or SKU. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """productVariant("""ID of the product variant."""id: ID@@ -298,7 +336,9 @@ type Query {channel: String): ProductVariant- """List of product variants."""+ """+ List of product variants. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """productVariants("""Filter product variants by given IDs."""ids: [ID!]@@ -325,7 +365,9 @@ type Query {last: Int): ProductVariantCountableConnection- """List of top selling products."""+ """+ List of top selling products. Requires one of the following permissions: MANAGE_PRODUCTS.+ """reportProductSales("""Span of time."""period: ReportingPeriod!@@ -346,13 +388,17 @@ type Query {last: Int): ProductVariantCountableConnection- """Look up a payment by ID."""+ """+ Look up a payment by ID. Requires one of the following permissions: MANAGE_ORDERS.+ """payment("""ID of the payment."""id: ID!): Payment- """List of payments."""+ """+ List of payments. Requires one of the following permissions: MANAGE_ORDERS.+ """payments("""Filtering options for payments."""filter: PaymentFilterInput@@ -428,7 +474,7 @@ type Query {): PageTypeCountableConnection"""- List of activity events to display on homepage (at the moment it only contains order-events).+ List of activity events to display on homepage (at the moment it only contains order-events). Requires one of the following permissions: MANAGE_ORDERS."""homepageEvents("""Return the elements in the list that come before the specified cursor."""@@ -444,13 +490,17 @@ type Query {last: Int): OrderEventCountableConnection- """Look up an order by ID."""+ """+ Look up an order by ID. Requires one of the following permissions: MANAGE_ORDERS.+ """order("""ID of an order."""id: ID!): Order- """List of orders."""+ """+ List of orders. Requires one of the following permissions: MANAGE_ORDERS.+ """orders("""Sort orders."""sortBy: OrderSortingInput@@ -474,7 +524,9 @@ type Query {last: Int): OrderCountableConnection- """List of draft orders."""+ """+ List of draft orders. Requires one of the following permissions: MANAGE_ORDERS.+ """draftOrders("""Sort draft orders."""sortBy: OrderSortingInput@@ -495,7 +547,9 @@ type Query {last: Int): OrderCountableConnection- """Return the total sales amount from a specific period."""+ """+ Return the total sales amount from a specific period. Requires one of the following permissions: MANAGE_ORDERS.+ """ordersTotal("""A period of time."""period: ReportingPeriod@@ -582,13 +636,17 @@ type Query {last: Int): MenuItemCountableConnection- """Look up a gift card by ID."""+ """+ Look up a gift card by ID. Requires one of the following permissions: MANAGE_GIFT_CARD.+ """giftCard("""ID of the gift card."""id: ID!): GiftCard- """List of gift cards."""+ """+ List of gift cards. Requires one of the following permissions: MANAGE_GIFT_CARD.+ """giftCards("""New in Saleor 3.1. Sort gift cards. Note: this feature is in a preview state and can be subject to changes at later point.@@ -614,12 +672,12 @@ type Query {): GiftCardCountableConnection"""- New in Saleor 3.1. List of gift card currencies. Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. List of gift card currencies. Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: MANAGE_GIFT_CARD."""giftCardCurrencies: [String!]!"""- New in Saleor 3.1. List of gift card tags. Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. List of gift card tags. Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: MANAGE_GIFT_CARD."""giftCardTags("""Filtering options for gift card tags."""@@ -638,13 +696,17 @@ type Query {last: Int): GiftCardTagCountableConnection- """Look up a plugin by ID."""+ """+ Look up a plugin by ID. Requires one of the following permissions: MANAGE_PLUGINS.+ """plugin("""ID of the plugin."""id: ID!): Plugin- """List of plugins."""+ """+ List of plugins. Requires one of the following permissions: MANAGE_PLUGINS.+ """plugins("""Filtering options for plugins."""filter: PluginFilterInput@@ -665,7 +727,9 @@ type Query {last: Int): PluginCountableConnection- """Look up a sale by ID."""+ """+ Look up a sale by ID. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """sale("""ID of the sale."""id: ID!@@ -674,7 +738,9 @@ type Query {channel: String): Sale- """List of the shop's sales."""+ """+ List of the shop's sales. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """sales("""Filtering options for sales."""filter: SaleFilterInput@@ -705,7 +771,9 @@ type Query {last: Int): SaleCountableConnection- """Look up a voucher by ID."""+ """+ Look up a voucher by ID. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """voucher("""ID of the voucher."""id: ID!@@ -714,7 +782,9 @@ type Query {channel: String): Voucher- """List of the shop's vouchers."""+ """+ List of the shop's vouchers. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """vouchers("""Filtering options for vouchers."""filter: VoucherFilterInput@@ -745,13 +815,17 @@ type Query {last: Int): VoucherCountableConnection- """Look up a export file by ID."""+ """+ Look up a export file by ID. Requires one of the following permissions: MANAGE_PRODUCTS.+ """exportFile("""ID of the export file job."""id: ID!): ExportFile- """List of export files."""+ """+ List of export files. Requires one of the following permissions: MANAGE_PRODUCTS.+ """exportFiles("""Filtering options for export files."""filter: ExportFileFilterInput@@ -781,7 +855,9 @@ type Query {token: UUID): Checkout- """List of checkouts."""+ """+ List of checkouts. Requires one of the following permissions: MANAGE_CHECKOUTS.+ """checkouts("""New in Saleor 3.1. Sort checkouts."""sortBy: CheckoutSortingInput@@ -805,7 +881,9 @@ type Query {last: Int): CheckoutCountableConnection- """List of checkout lines."""+ """+ List of checkout lines. Requires one of the following permissions: MANAGE_CHECKOUTS.+ """checkoutLines("""Return the elements in the list that come before the specified cursor."""before: String@@ -820,13 +898,17 @@ type Query {last: Int): CheckoutLineCountableConnection- """Look up a channel by ID."""+ """+ Look up a channel by ID. Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ """channel("""ID of the channel."""id: ID): Channel- """List of all channels."""+ """+ List of all channels. Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ """channels: [Channel!]"""List of the shop's attributes."""@@ -862,10 +944,14 @@ type Query {slug: String): Attribute- """List of all apps installations"""+ """+ List of all apps installations Requires one of the following permissions: MANAGE_APPS.+ """appsInstallations: [AppInstallation!]!- """List of the apps."""+ """+ List of the apps. Requires one of the following permissions: MANAGE_APPS.+ """apps("""Filtering options for apps."""filter: AppFilterInput@@ -887,7 +973,7 @@ type Query {): AppCountableConnection"""- Look up an app by ID. If ID is not provided, return the currently authenticated app.+ Look up an app by ID. If ID is not provided, return the currently authenticated app. Requires one of the following permissions: AuthorizationFilters.OWNER, AppPermission.MANAGE_APPS."""app("""ID of the app."""@@ -895,7 +981,7 @@ type Query {): App"""- New in Saleor 3.1. List of all extensions. Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. List of all extensions. Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP."""appExtensions("""Filtering options for apps extensions."""@@ -915,7 +1001,7 @@ type Query {): AppExtensionCountableConnection"""- New in Saleor 3.1. Look up an app extension by ID. Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. Look up an app extension by ID. Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP."""appExtension("""ID of the app extension."""@@ -943,7 +1029,9 @@ type Query {id: ID!): Address- """List of the shop's customers."""+ """+ List of the shop's customers. Requires one of the following permissions: MANAGE_ORDERS, MANAGE_USERS.+ """customers("""Filtering options for customers."""filter: CustomerFilterInput@@ -964,7 +1052,9 @@ type Query {last: Int): UserCountableConnection- """List of permission groups."""+ """+ List of permission groups. Requires one of the following permissions: MANAGE_STAFF.+ """permissionGroups("""Filtering options for permission groups."""filter: PermissionGroupFilterInput@@ -985,7 +1075,9 @@ type Query {last: Int): GroupCountableConnection- """Look up permission group by ID."""+ """+ Look up permission group by ID. Requires one of the following permissions: MANAGE_STAFF.+ """permissionGroup("""ID of the group."""id: ID!@@ -994,7 +1086,9 @@ type Query {"""Return the currently authenticated user."""me: User- """List of the shop's staff users."""+ """+ List of the shop's staff users. Requires one of the following permissions: MANAGE_STAFF.+ """staffUsers("""Filtering options for staff users."""filter: StaffUserInput@@ -1015,7 +1109,9 @@ type Query {last: Int): UserCountableConnection- """Look up a user by ID or email address."""+ """+ Look up a user by ID or email address. Requires one of the following permissions: MANAGE_STAFF, MANAGE_USERS, MANAGE_ORDERS.+ """user("""ID of the user."""id: ID@@ -2066,7 +2162,9 @@ type ShippingMethodType implements Node & ObjectWithMetadata {languageCode: LanguageCodeEnum!): ShippingMethodTranslation- """List of channels available for the method."""+ """+ List of channels available for the method. Requires one of the following permissions: MANAGE_SHIPPING.+ """channelListings: [ShippingMethodChannelListing!]"""The price of the cheapest variant (including discounts)."""@@ -2080,7 +2178,9 @@ type ShippingMethodType implements Node & ObjectWithMetadata {"""postalCodeRules: [ShippingMethodPostalCodeRule!]- """List of excluded products for the shipping method."""+ """+ List of excluded products for the shipping method. Requires one of the following permissions: MANAGE_SHIPPING.+ """excludedProducts("""Return the elements in the list that come before the specified cursor."""before: String@@ -2931,7 +3031,9 @@ type Channel implements Node {currencyCode: String!slug: String!- """Whether a channel has associated orders."""+ """+ Whether a channel has associated orders. Requires one of the following permissions: MANAGE_CHANNELS.+ """hasOrders: Boolean!"""@@ -3041,7 +3143,9 @@ type Product implements Node & ObjectWithMetadata {"""List of attributes assigned to this product."""attributes: [SelectedAttribute!]!- """List of availability in channels for the product."""+ """+ List of availability in channels for the product. Requires one of the following permissions: MANAGE_PRODUCTS.+ """channelListings: [ProductChannelListing!]"""Get a single product media by ID."""@@ -3056,7 +3160,9 @@ type Product implements Node & ObjectWithMetadata {id: ID): ProductImage @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `mediaById` field instead.")- """List of variants for the product."""+ """+ List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """variants: [ProductVariant!]"""List of media for the product."""@@ -3065,7 +3171,9 @@ type Product implements Node & ObjectWithMetadata {"""List of images for the product."""images: [ProductImage!] @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `media` field instead.")- """List of collections for the product."""+ """+ List of collections for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """collections: [Collection!]"""Returns translated product fields for the given language code."""@@ -3141,6 +3249,10 @@ type ProductType implements Node & ObjectWithMetadata {"""Product attributes of that product type."""productAttributes: [Attribute!]++ """+ List of attributes which can be assigned to this product type. Requires one of the following permissions: MANAGE_PRODUCTS.+ """availableAttributes(filter: AttributeFilterInput@@ -3244,32 +3356,42 @@ type Attribute implements Node & ObjectWithMetadata {last: Int): AttributeValueCountableConnection- """Whether the attribute requires values to be passed or not."""+ """+ Whether the attribute requires values to be passed or not. Requires one of the following permissions: PagePermissions.MANAGE_PAGES, PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES, ProductPermissions.MANAGE_PRODUCTS, ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """valueRequired: Boolean!- """Whether the attribute should be visible or not in storefront."""+ """+ Whether the attribute should be visible or not in storefront. Requires one of the following permissions: PagePermissions.MANAGE_PAGES, PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES, ProductPermissions.MANAGE_PRODUCTS, ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """visibleInStorefront: Boolean!- """Whether the attribute can be filtered in storefront."""+ """+ Whether the attribute can be filtered in storefront. Requires one of the following permissions: PagePermissions.MANAGE_PAGES, PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES, ProductPermissions.MANAGE_PRODUCTS, ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """filterableInStorefront: Boolean!- """Whether the attribute can be filtered in dashboard."""+ """+ Whether the attribute can be filtered in dashboard. Requires one of the following permissions: PagePermissions.MANAGE_PAGES, PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES, ProductPermissions.MANAGE_PRODUCTS, ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """filterableInDashboard: Boolean!- """Whether the attribute can be displayed in the admin product list."""+ """+ Whether the attribute can be displayed in the admin product list. Requires one of the following permissions: PagePermissions.MANAGE_PAGES, PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES, ProductPermissions.MANAGE_PRODUCTS, ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """availableInGrid: Boolean!+ """+ The position of the attribute in the storefront navigation (0 by default). Requires one of the following permissions: PagePermissions.MANAGE_PAGES, PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES, ProductPermissions.MANAGE_PRODUCTS, ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """+ storefrontSearchPosition: Int!+"""Returns translated attribute fields for the given language code."""translation("""A language code to return the translation for attribute."""languageCode: LanguageCodeEnum!): AttributeTranslation- """- The position of the attribute in the storefront navigation (0 by default).- """- storefrontSearchPosition: Int!-"""Flag indicating that attribute has predefined choices."""withChoices: Boolean!productTypes(@@ -3595,7 +3717,9 @@ type Category implements Node & ObjectWithMetadata {last: Int): CategoryCountableConnection- """List of products in the category."""+ """+ List of products in the category. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """products("""Slug of a channel for which the data should be returned."""channel: String@@ -3702,7 +3826,9 @@ type ProductVariant implements Node & ObjectWithMetadata {"""channel: String- """List of price information in channels for the product."""+ """+ List of price information in channels for the product. Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ """channelListings: [ProductVariantChannelListing!]"""@@ -3724,11 +3850,13 @@ type ProductVariant implements Node & ObjectWithMetadata {"""Gross margin percentage value."""margin: Int- """Total quantity ordered."""+ """+ Total quantity ordered. Requires one of the following permissions: MANAGE_PRODUCTS.+ """quantityOrdered: Int"""- Total revenue generated by a variant in given period of time. Note: this field should be queried using `reportProductSales` query as it uses optimizations suitable for such calculations.+ Total revenue generated by a variant in given period of time. Note: this field should be queried using `reportProductSales` query as it uses optimizations suitable for such calculations. Requires one of the following permissions: MANAGE_PRODUCTS."""revenue(period: ReportingPeriod): TaxedMoney@@ -3744,10 +3872,14 @@ type ProductVariant implements Node & ObjectWithMetadata {languageCode: LanguageCodeEnum!): ProductVariantTranslation- """Digital content for the product variant."""+ """+ Digital content for the product variant. Requires one of the following permissions: MANAGE_PRODUCTS.+ """digitalContent: DigitalContent- """Stocks for the product variant."""+ """+ Stocks for the product variant. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ """stocks("""Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration.@@ -3796,7 +3928,9 @@ type ProductVariantChannelListing implements Node {"""Cost price of the variant."""costPrice: Money- """Gross margin percentage value."""+ """+ Gross margin percentage value. Requires one of the following permissions: MANAGE_PRODUCTS.+ """margin: Int"""@@ -4249,23 +4383,31 @@ type Stock implements Node {productVariant: ProductVariant!"""- Quantity of a product in the warehouse's possession, including the allocated stock that is waiting for shipment.+ Quantity of a product in the warehouse's possession, including the allocated stock that is waiting for shipment. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS."""quantity: Int!- """Quantity allocated for orders"""+ """+ Quantity allocated for orders. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ """quantityAllocated: Int!- """Quantity reserved for checkouts"""+ """+ Quantity reserved for checkouts. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ """quantityReserved: Int!}"""Represents preorder settings for product variant."""type PreorderData {- """The global preorder threshold for product variant."""+ """+ The global preorder threshold for product variant. Requires one of the following permissions: MANAGE_PRODUCTS.+ """globalThreshold: Int- """Total number of sold product variant during preorder."""+ """+ Total number of sold product variant during preorder. Requires one of the following permissions: MANAGE_PRODUCTS.+ """globalSoldUnits: Int!"""Preorder end date."""@@ -4316,10 +4458,14 @@ type ProductChannelListing implements Node {"""The price of the cheapest variant (including discounts)."""discountedPrice: Money- """Purchase cost of product."""+ """+ Purchase cost of product. Requires one of the following permissions: MANAGE_PRODUCTS.+ """purchaseCost: MoneyRange- """Range of margin percentage value."""+ """+ Range of margin percentage value. Requires one of the following permissions: MANAGE_PRODUCTS.+ """margin: Margin"""Whether the product is available for purchase."""@@ -4397,7 +4543,9 @@ type Collection implements Node & ObjectWithMetadata {languageCode: LanguageCodeEnum!): CollectionTranslation- """List of channels in which the collection is available."""+ """+ List of channels in which the collection is available. Requires one of the following permissions: MANAGE_PRODUCTS.+ """channelListings: [CollectionChannelListing!]}@@ -4852,7 +5000,9 @@ type PageType implements Node & ObjectWithMetadata {"""Page attributes of that page type."""attributes: [Attribute!]- """Attributes that can be assigned to the page type."""+ """+ Attributes that can be assigned to the page type. Requires one of the following permissions: MANAGE_PAGES.+ """availableAttributes(filter: AttributeFilterInput@@ -4869,7 +5019,9 @@ type PageType implements Node & ObjectWithMetadata {last: Int): AttributeCountableConnection- """Whether page type has pages assigned."""+ """+ Whether page type has pages assigned. Requires one of the following permissions: MANAGE_PAGES.+ """hasPages: Boolean}@@ -4885,7 +5037,7 @@ type ShippingMethodTranslatableContent implements Node {): ShippingMethodTranslation"""- Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers.+ Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers. Requires one of the following permissions: MANAGE_SHIPPING."""shippingMethod: ShippingMethodType @deprecated(reason: "This field will be removed in Saleor 4.0. Get model fields from the root level queries.")}@@ -4901,7 +5053,7 @@ type SaleTranslatableContent implements Node {): SaleTranslation"""- Sales allow creating discounts for categories, collections or products and are visible to all the customers.+ Sales allow creating discounts for categories, collections or products and are visible to all the customers. Requires one of the following permissions: MANAGE_DISCOUNTS."""sale: Sale @deprecated(reason: "This field will be removed in Saleor 4.0. Get model fields from the root level queries.")}@@ -4949,7 +5101,9 @@ type Sale implements Node & ObjectWithMetadata {last: Int): CategoryCountableConnection- """List of collections this sale applies to."""+ """+ List of collections this sale applies to. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """collections("""Return the elements in the list that come before the specified cursor."""before: String@@ -4964,7 +5118,9 @@ type Sale implements Node & ObjectWithMetadata {last: Int): CollectionCountableConnection- """List of products this sale applies to."""+ """+ List of products this sale applies to. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """products("""Return the elements in the list that come before the specified cursor."""before: String@@ -4979,7 +5135,9 @@ type Sale implements Node & ObjectWithMetadata {last: Int): ProductCountableConnection- """New in Saleor 3.1. List of product variants this sale applies to."""+ """+ New in Saleor 3.1. List of product variants this sale applies to. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """variants("""Return the elements in the list that come before the specified cursor."""before: String@@ -5000,7 +5158,9 @@ type Sale implements Node & ObjectWithMetadata {languageCode: LanguageCodeEnum!): SaleTranslation- """List of channels available for the sale."""+ """+ List of channels available for the sale. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """channelListings: [SaleChannelListing!]"""Sale value."""@@ -5068,7 +5228,7 @@ type VoucherTranslatableContent implements Node {): VoucherTranslation"""- Vouchers allow giving discounts to particular customers on categories, collections or specific products. They can be used during checkout by providing valid voucher codes.+ Vouchers allow giving discounts to particular customers on categories, collections or specific products. They can be used during checkout by providing valid voucher codes. Requires one of the following permissions: MANAGE_DISCOUNTS."""voucher: Voucher @deprecated(reason: "This field will be removed in Saleor 4.0. Get model fields from the root level queries.")}@@ -5120,7 +5280,9 @@ type Voucher implements Node & ObjectWithMetadata {last: Int): CategoryCountableConnection- """List of collections this voucher applies to."""+ """+ List of collections this voucher applies to. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """collections("""Return the elements in the list that come before the specified cursor."""before: String@@ -5135,7 +5297,9 @@ type Voucher implements Node & ObjectWithMetadata {last: Int): CollectionCountableConnection- """List of products this voucher applies to."""+ """+ List of products this voucher applies to. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """products("""Return the elements in the list that come before the specified cursor."""before: String@@ -5150,7 +5314,9 @@ type Voucher implements Node & ObjectWithMetadata {last: Int): ProductCountableConnection- """New in Saleor 3.1. List of product variants this voucher applies to."""+ """+ New in Saleor 3.1. List of product variants this voucher applies to. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """variants("""Return the elements in the list that come before the specified cursor."""before: String@@ -5189,7 +5355,9 @@ type Voucher implements Node & ObjectWithMetadata {"""Determines a type of voucher."""type: VoucherTypeEnum!- """List of availability in channels for the voucher."""+ """+ List of availability in channels for the voucher. Requires one of the following permissions: MANAGE_DISCOUNTS.+ """channelListings: [VoucherChannelListing!]}@@ -5254,7 +5422,15 @@ type MenuItem implements Node & ObjectWithMetadata {menu: Menu!parent: MenuItemcategory: Category++ """+ A collection associated with this menu item. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ """collection: Collection++ """+ A page associated with this menu item. Requires one of the following permissions to include unpublished items: PagePermissions.MANAGE_PAGES.+ """page: Pagelevel: Int!children: [MenuItem!]@@ -5354,7 +5530,7 @@ type Shop {): [ShippingMethod!]"""- New in Saleor 3.1. List of all currencies supported by shop's channels.+ New in Saleor 3.1. List of all currencies supported by shop's channels. Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP."""channelCurrencies: [String!]!@@ -5374,10 +5550,14 @@ type Shop {"""Shop's default country."""defaultCountry: CountryDisplay- """Default shop's email sender's name."""+ """+ Default shop's email sender's name. Requires one of the following permissions: MANAGE_SETTINGS.+ """defaultMailSenderName: String- """Default shop's email sender's address."""+ """+ Default shop's email sender's address. Requires one of the following permissions: MANAGE_SETTINGS.+ """defaultMailSenderAddress: String"""Shop's description."""@@ -5428,28 +5608,34 @@ type Shop {languageCode: LanguageCodeEnum!): ShopTranslation- """Enable automatic fulfillment for all digital products."""+ """+ Enable automatic fulfillment for all digital products. Requires one of the following permissions: MANAGE_SETTINGS.+ """automaticFulfillmentDigitalProducts: Boolean"""- New in Saleor 3.1. Default number of minutes stock will be reserved for anonymous checkout or null when stock reservation is disabled.+ New in Saleor 3.1. Default number of minutes stock will be reserved for anonymous checkout or null when stock reservation is disabled. Requires one of the following permissions: MANAGE_SETTINGS."""reserveStockDurationAnonymousUser: Int"""- New in Saleor 3.1. Default number of minutes stock will be reserved for authenticated checkout or null when stock reservation is disabled.+ New in Saleor 3.1. Default number of minutes stock will be reserved for authenticated checkout or null when stock reservation is disabled. Requires one of the following permissions: MANAGE_SETTINGS."""reserveStockDurationAuthenticatedUser: Int"""- New in Saleor 3.1. Default number of maximum line quantity in single checkout (per single checkout line). Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. Default number of maximum line quantity in single checkout (per single checkout line). Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: MANAGE_SETTINGS."""limitQuantityPerCheckout: Int- """Default number of max downloads per digital content URL."""+ """+ Default number of max downloads per digital content URL. Requires one of the following permissions: MANAGE_SETTINGS.+ """defaultDigitalMaxDownloads: Int- """Default number of days which digital content URL will be valid."""+ """+ Default number of days which digital content URL will be valid. Requires one of the following permissions: MANAGE_SETTINGS.+ """defaultDigitalUrlValidDays: Int"""Company address."""@@ -5458,13 +5644,19 @@ type Shop {"""URL of a view where customers can set their password."""customerSetPasswordUrl: String- """List of staff notification recipients."""+ """+ List of staff notification recipients. Requires one of the following permissions: MANAGE_SETTINGS.+ """staffNotificationRecipients: [StaffNotificationRecipient!]- """Resource limitations and current usage if any set for a shop"""+ """+ Resource limitations and current usage if any set for a shop Requires one of the following permissions: AUTHENTICATED_STAFF_USER.+ """limits: LimitInfo!- """Saleor API version."""+ """+ Saleor API version. Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP.+ """version: String!}@@ -5648,10 +5840,14 @@ type User implements Node & ObjectWithMetadata {last: Int): GiftCardCountableConnection- """A note about the customer."""+ """+ A note about the customer. Requires one of the following permissions: MANAGE_USERS, MANAGE_STAFF.+ """note: String- """List of user's orders."""+ """+ List of user's orders. Requires one of the following permissions: AccountPermissions.MANAGE_STAFF, AuthorizationFilters.OWNER+ """orders("""Return the elements in the list that come before the specified cursor."""before: String@@ -5679,7 +5875,9 @@ type User implements Node & ObjectWithMetadata {size: Int): Image- """List of events associated with the user."""+ """+ List of events associated with the user. Requires one of the following permissions: MANAGE_USERS, MANAGE_STAFF.+ """events: [CustomerEvent!]"""List of stored payment sources."""@@ -5803,7 +6001,7 @@ type GiftCard implements Node & ObjectWithMetadata {last4CodeChars: String!"""- Gift card code. Can be fetched by staff member with manage gift card permission when gift card wasn't used yet and by the gift card owner.+ Gift card code. Can be fetched by a staff member with GiftcardPermissions.MANAGE_GIFT_CARD when gift card wasn't yet used and by the gift card owner."""code: String!created: DateTime!@@ -5819,7 +6017,7 @@ type GiftCard implements Node & ObjectWithMetadata {usedBy: User"""- New in Saleor 3.1. Email address of the user who bought or issued gift card. Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. Email address of the user who bought or issued gift card. Requires one of the following permissions: AccountPermissions.MANAGE_USERS, AuthorizationFilters.OWNER. Note: this feature is in a preview state and can be subject to changes at later point."""createdByEmail: String@@ -5831,7 +6029,7 @@ type GiftCard implements Node & ObjectWithMetadata {expiryDate: Date"""- New in Saleor 3.1. App which created the gift card. Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. App which created the gift card. Requires one of the following permissions: AppPermission.MANAGE_APPS, AuthorizationFilters.OWNER. Note: this feature is in a preview state and can be subject to changes at later point."""app: App@@ -5841,7 +6039,7 @@ type GiftCard implements Node & ObjectWithMetadata {product: Product"""- New in Saleor 3.1. List of events associated with the gift card. Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. List of events associated with the gift card. Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: MANAGE_GIFT_CARD."""events("""Filtering options for gift card events."""@@ -5849,7 +6047,7 @@ type GiftCard implements Node & ObjectWithMetadata {): [GiftCardEvent!]!"""- New in Saleor 3.1. The gift card tag. Note: this feature is in a preview state and can be subject to changes at later point.+ New in Saleor 3.1. The gift card tag. Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: MANAGE_GIFT_CARD."""tags: [GiftCardTag!]!@@ -5883,10 +6081,14 @@ type GiftCardEvent implements Node {"""Gift card event type."""type: GiftCardEventsEnum- """User who performed the action."""+ """+ User who performed the action. Requires one of the following permissions: AccountPermissions.MANAGE_USERS, AccountPermissions.MANAGE_STAFF, AuthorizationFilters.OWNER.+ """user: User- """App that performed the action."""+ """+ App that performed the action. Requires one of the following permissions: AppPermission.MANAGE_APPS, AuthorizationFilters.OWNER.+ """app: App"""Content of the event."""@@ -6026,9 +6228,21 @@ type Order implements Node & ObjectWithMetadata {created: DateTime!updatedAt: DateTime!status: OrderStatus!++ """+ User who placed the order. This field is set only for orders placed by authenticated users. Requires one of the following permissions: AccountPermissions.MANAGE_USERS, OrderPermissions.MANAGE_ORDERS, AuthorizationFilters.OWNER.+ """user: UsertrackingClientId: String!++ """+ Billing address. Requires one of the following permissions to view the full data: OrderPermissions.MANAGE_ORDERS, AuthorizationFilters.OWNER.+ """billingAddress: Address++ """+ Shipping address. Requires one of the following permissions to view the full data: OrderPermissions.MANAGE_ORDERS, AuthorizationFilters.OWNER.+ """shippingAddress: AddressshippingMethodName: StringcollectionPointName: String@@ -6056,7 +6270,9 @@ type Order implements Node & ObjectWithMetadata {"""availableCollectionPoints: [Warehouse!]!- """List of order invoices."""+ """+ List of order invoices. Requires one of the following permissions: OrderPermissions.MANAGE_ORDERS, AuthorizationFilters.OWNER.+ """invoices: [Invoice!]"""User-friendly number of an order."""@@ -6119,13 +6335,17 @@ type Order implements Node & ObjectWithMetadata {"""Amount captured by payment."""totalCaptured: Money!- """List of events associated with the order."""+ """+ List of events associated with the order. Requires one of the following permissions: MANAGE_ORDERS.+ """events: [OrderEvent!]"""The difference between the paid and the order total amount."""totalBalance: Money!- """Email address of the customer."""+ """+ Email address of the customer. Requires the following permissions to access the full data: OrderPermissions.MANAGE_ORDERS, AuthorizationFilters.OWNER+ """userEmail: String"""Returns True, if order requires shipping."""@@ -6250,7 +6470,7 @@ type OrderLine implements Node {totalPrice: TaxedMoney!"""- A purchased product variant. Note: this field may be null if the variant has been removed from stock at all.+ A purchased product variant. Note: this field may be null if the variant has been removed from stock at all. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""variant: ProductVariant@@ -6260,7 +6480,9 @@ type OrderLine implements Node {"""Variant name in the customer's language"""translatedVariantName: String!- """List of allocations across warehouses."""+ """+ List of allocations across warehouses. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ """allocations: [Allocation!]"""New in Saleor 3.1. A quantity of items remaining to be fulfilled."""@@ -6281,10 +6503,14 @@ scalar PositiveDecimaltype Allocation implements Node {id: ID!- """Quantity allocated for orders."""+ """+ Quantity allocated for orders. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ """quantity: Int!- """The warehouse were items were allocated."""+ """+ The warehouse were items were allocated. Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ """warehouse: Warehouse!}@@ -6387,13 +6613,17 @@ type Payment implements Node & ObjectWithMetadata {checkout: Checkoutorder: OrderpaymentMethodType: String!++ """+ IP address of the user who created the payment. Requires one of the following permissions: MANAGE_ORDERS.+ """customerIpAddress: String"""Internal payment status."""chargeStatus: PaymentChargeStatusEnum!"""- List of actions that can be performed in the current state of a payment.+ List of actions that can be performed in the current state of a payment. Requires one of the following permissions: MANAGE_ORDERS."""actions: [OrderAction!]!@@ -6403,13 +6633,19 @@ type Payment implements Node & ObjectWithMetadata {"""Total amount captured for this payment."""capturedAmount: Money- """List of all transactions within this payment."""+ """+ List of all transactions within this payment. Requires one of the following permissions: MANAGE_ORDERS.+ """transactions: [Transaction!]- """Maximum amount of money that can be captured."""+ """+ Maximum amount of money that can be captured. Requires one of the following permissions: MANAGE_ORDERS.+ """availableCaptureAmount: Money- """Maximum amount of money that can be refunded."""+ """+ Maximum amount of money that can be refunded. Requires one of the following permissions: MANAGE_ORDERS.+ """availableRefundAmount: Money"""The details of the card used for this payment."""@@ -6475,7 +6711,9 @@ type OrderEvent implements Node {"""User who performed the action."""user: User- """App that performed the action."""+ """+ App that performed the action. Requires of of the following permissions: AppPermission.MANAGE_APPS, OrderPermissions.MANAGE_ORDERS, AuthorizationFilters.OWNER.+ """app: App"""Content of the event."""@@ -6642,7 +6880,9 @@ type OrderDiscount implements Node {"""Value of the discount. Can store fixed value or percent value"""value: PositiveDecimal!- """Explanation for the applied discount."""+ """+ Explanation for the applied discount. Requires one of the following permissions: MANAGE_ORDERS.+ """reason: String"""Returns amount of discount."""@@ -6740,7 +6980,9 @@ type Group implements Node {id: ID!name: String!- """List of group users"""+ """+ List of group users Requires one of the following permissions: MANAGE_STAFF.+ """users: [User!]"""List of group permissions"""@@ -7636,10 +7878,14 @@ type ExportEvent implements Node {"""Export event type."""type: ExportEventsEnum!- """User who performed the action."""+ """+ User who performed the action. Requires one of the following permissions: AuthorizationFilters.OWNER, AccountPermissions.MANAGE_STAFF.+ """user: User- """App which performed the action."""+ """+ App which performed the action. Requires one of the following permissions: AuthorizationFilters.OWNER, AppPermission.MANAGE_APPS.+ """app: App"""Content of the event."""@@ -8642,7 +8888,7 @@ type Mutation {): ProductReorderAttributeValues"""- Create new digital content. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec+ Create new digital content. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec Requires one of the following permissions: MANAGE_PRODUCTS."""digitalContentCreate("""Fields required to create a digital content."""@@ -8652,13 +8898,17 @@ type Mutation {variantId: ID!): DigitalContentCreate- """Remove digital content assigned to given variant."""+ """+ Remove digital content assigned to given variant. Requires one of the following permissions: MANAGE_PRODUCTS.+ """digitalContentDelete("""ID of a product variant with digital content to remove."""variantId: ID!): DigitalContentDelete- """Update digital content."""+ """+ Update digital content. Requires one of the following permissions: MANAGE_PRODUCTS.+ """digitalContentUpdate("""Fields required to update a digital content."""input: DigitalContentInput!@@ -8667,7 +8917,9 @@ type Mutation {variantId: ID!): DigitalContentUpdate- """Generate new URL to digital content."""+ """+ Generate new URL to digital content. Requires one of the following permissions: MANAGE_PRODUCTS.+ """digitalContentUrlCreate("""Fields required to create a new url."""input: DigitalContentUrlCreateInput!@@ -9825,7 +10077,7 @@ type Mutation {): ExportGiftCards"""- Upload a file. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec+ Upload a file. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""fileUpload("""Represents a file in a multipart request."""@@ -10729,14 +10981,16 @@ type Mutation {): StaffBulkDelete"""- Create a user avatar. Only for staff members. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec+ Create a user avatar. Only for staff members. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec Requires one of the following permissions: AUTHENTICATED_STAFF_USER."""userAvatarUpdate("""Represents an image file in a multipart request."""image: Upload!): UserAvatarUpdate- """Deletes a user avatar. Only for staff members."""+ """+ Deletes a user avatar. Only for staff members. Requires one of the following permissions: AUTHENTICATED_STAFF_USER.+ """userAvatarDelete: UserAvatarDelete"""@@ -12401,7 +12655,7 @@ type ProductReorderAttributeValues {}"""-Create new digital content. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec+Create new digital content. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec Requires one of the following permissions: MANAGE_PRODUCTS."""type DigitalContentCreate {variant: ProductVariant@@ -12431,14 +12685,18 @@ input DigitalContentUploadInput {contentFile: Upload!}-"""Remove digital content assigned to given variant."""+"""+Remove digital content assigned to given variant. Requires one of the following permissions: MANAGE_PRODUCTS.+"""type DigitalContentDelete {variant: ProductVariantproductErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")errors: [ProductError!]!}-"""Update digital content."""+"""+Update digital content. Requires one of the following permissions: MANAGE_PRODUCTS.+"""type DigitalContentUpdate {variant: ProductVariantcontent: DigitalContent@@ -12464,7 +12722,9 @@ input DigitalContentInput {automaticFulfillment: Boolean}-"""Generate new URL to digital content."""+"""+Generate new URL to digital content. Requires one of the following permissions: MANAGE_PRODUCTS.+"""type DigitalContentUrlCreate {productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")errors: [ProductError!]!@@ -14942,7 +15202,7 @@ input ExportGiftCardsInput {}"""-Upload a file. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec+Upload a file. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""type FileUpload {uploadedFile: File@@ -16525,7 +16785,7 @@ type StaffBulkDelete {}"""-Create a user avatar. Only for staff members. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec+Create a user avatar. Only for staff members. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec Requires one of the following permissions: AUTHENTICATED_STAFF_USER."""type UserAvatarUpdate {"""An updated user instance."""@@ -16534,7 +16794,9 @@ type UserAvatarUpdate {errors: [AccountError!]!}-"""Deletes a user avatar. Only for staff members."""+"""+Deletes a user avatar. Only for staff members. Requires one of the following permissions: AUTHENTICATED_STAFF_USER.+"""type UserAvatarDelete {"""An updated user instance."""user: Userdiff --git a/saleor/graphql/shipping/schema.py b/saleor/graphql/shipping/schema.pyindex e7d51d8c4b..0488457e96 100644--- a/saleor/graphql/shipping/schema.py+++ b/saleor/graphql/shipping/schema.py@@ -4,9 +4,8 @@ from ...core.permissions import ShippingPermissionsfrom ...shipping import modelsfrom ..channel.types import ChannelContextfrom ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.fields import FilterConnectionField+from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.utils import from_global_id_or_error-from ..decorators import permission_requiredfrom ..translations.mutations import ShippingPriceTranslatefrom .bulk_mutations import ShippingPriceBulkDelete, ShippingZoneBulkDeletefrom .filters import ShippingZoneFilterInput@@ -26,7 +25,7 @@ from .types import ShippingZone, ShippingZoneCountableConnectionclass ShippingQueries(graphene.ObjectType):- shipping_zone = graphene.Field(+ shipping_zone = PermissionsField(ShippingZone,id=graphene.Argument(graphene.ID, description="ID of the shipping zone.", required=True@@ -35,6 +34,7 @@ class ShippingQueries(graphene.ObjectType):description="Slug of a channel for which the data should be returned."),description="Look up a shipping zone by ID.",+ permissions=[ShippingPermissions.MANAGE_SHIPPING],)shipping_zones = FilterConnectionField(ShippingZoneCountableConnection,@@ -45,15 +45,14 @@ class ShippingQueries(graphene.ObjectType):description="Slug of a channel for which the data should be returned."),description="List of the shop's shipping zones.",+ permissions=[ShippingPermissions.MANAGE_SHIPPING],)- @permission_required(ShippingPermissions.MANAGE_SHIPPING)def resolve_shipping_zone(self, info, id, channel=None):_, id = from_global_id_or_error(id, ShippingZone)instance = models.ShippingZone.objects.filter(id=id).first()return ChannelContext(node=instance, channel_slug=channel) if instance else None- @permission_required(ShippingPermissions.MANAGE_SHIPPING)def resolve_shipping_zones(self, info, channel=None, **kwargs):qs = resolve_shipping_zones(channel)qs = filter_connection_queryset(qs, kwargs)diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.pyindex 5c9fd51388..93890ea76b 100644--- a/saleor/graphql/shipping/types.py+++ b/saleor/graphql/shipping/types.py@@ -18,7 +18,7 @@ from ..channel.types import ()from ..core.connection import CountableConnection, create_connection_slicefrom ..core.descriptions import DEPRECATED_IN_3X_FIELD-from ..core.fields import ConnectionField, JSONString+from ..core.fields import ConnectionField, JSONString, PermissionsFieldfrom ..core.types import (CountryDisplay,ModelObjectType,@@ -27,7 +27,6 @@ from ..core.types import (NonNullList,Weight,)-from ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadatafrom ..shipping.resolvers import resolve_price_range, resolve_shipping_translationfrom ..translations.fields import TranslationField@@ -90,9 +89,12 @@ class ShippingMethodType(ChannelContextTypeWithMetadataForObjectType):type_name="shipping method",resolver=None, # Disable default resolver)- channel_listings = NonNullList(- ShippingMethodChannelListing,+ channel_listings = PermissionsField(+ NonNullList(ShippingMethodChannelListing),description="List of channels available for the method.",+ permissions=[+ ShippingPermissions.MANAGE_SHIPPING,+ ],)maximum_order_price = graphene.Field(Money, description="The price of the cheapest variant (including discounts)."@@ -109,6 +111,7 @@ class ShippingMethodType(ChannelContextTypeWithMetadataForObjectType):excluded_products = ConnectionField("saleor.graphql.product.types.products.ProductCountableConnection",description="List of excluded products for the shipping method.",+ permissions=[ShippingPermissions.MANAGE_SHIPPING],)minimum_order_weight = graphene.Field(Weight, description="Minimum order weight to use this shipping method."@@ -193,7 +196,6 @@ class ShippingMethodType(ChannelContextTypeWithMetadataForObjectType):return convert_weight_to_default_weight_unit(root.node.minimum_order_weight)@staticmethod- @permission_required(ShippingPermissions.MANAGE_SHIPPING)def resolve_channel_listings(root: ChannelContext[models.ShippingMethod], info, **_kwargs):@@ -202,7 +204,6 @@ class ShippingMethodType(ChannelContextTypeWithMetadataForObjectType):)@staticmethod- @permission_required(ShippingPermissions.MANAGE_SHIPPING)def resolve_excluded_products(root: ChannelContext[models.ShippingMethod], info, **kwargs):diff --git a/saleor/graphql/shop/schema.py b/saleor/graphql/shop/schema.pyindex 578e35bb13..25f262c3af 100644--- a/saleor/graphql/shop/schema.py+++ b/saleor/graphql/shop/schema.py@@ -1,7 +1,7 @@import graphenefrom ...core.permissions import GiftcardPermissions, OrderPermissions-from ..decorators import permission_required+from ..core.fields import PermissionsFieldfrom ..translations.mutations import ShopSettingsTranslatefrom .mutations import (GiftCardSettingsUpdate,@@ -23,23 +23,24 @@ class ShopQueries(graphene.ObjectType):description="Return information about the shop.",required=True,)- order_settings = graphene.Field(- OrderSettings, description="Order related settings from site settings."+ order_settings = PermissionsField(+ OrderSettings,+ description="Order related settings from site settings.",+ permissions=[OrderPermissions.MANAGE_ORDERS],)- gift_card_settings = graphene.Field(+ gift_card_settings = PermissionsField(GiftCardSettings,description="Gift card related settings from site settings.",required=True,+ permissions=[GiftcardPermissions.MANAGE_GIFT_CARD],)def resolve_shop(self, _info):return Shop()- @permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_order_settings(self, info, *args, **_kwargs):return info.context.site.settings- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)def resolve_gift_card_settings(self, info, *args, **_kwargs):return info.context.site.settingsdiff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex cd7960fe0f..ba6bd13970 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -9,13 +9,14 @@ from phonenumbers import COUNTRY_CODE_TO_REGION_CODEfrom ... import __version__from ...account import models as account_modelsfrom ...channel import models as channel_models-from ...core.permissions import SitePermissions, get_permissions+from ...core.permissions import AuthorizationFilters, SitePermissions, get_permissionsfrom ...core.tracing import traced_resolverfrom ...site import models as site_modelsfrom ..account.types import Address, AddressInput, StaffNotificationRecipientfrom ..checkout.types import PaymentGatewayfrom ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATUREfrom ..core.enums import LanguageCodeEnum, WeightUnitsEnum+from ..core.fields import PermissionsFieldfrom ..core.types import (CountryDisplay,LanguageDisplay,@@ -25,11 +26,6 @@ from ..core.types import (TimePeriod,)from ..core.utils import str_to_enum-from ..decorators import (- permission_required,- staff_member_or_app_required,- staff_member_required,-)from ..shipping.types import ShippingMethodfrom ..translations.fields import TranslationFieldfrom ..translations.resolvers import resolve_translation@@ -152,12 +148,16 @@ class Shop(graphene.ObjectType):required=False,description="Shipping methods that are available for the shop.",)- channel_currencies = NonNullList(- graphene.String,+ channel_currencies = PermissionsField(+ NonNullList(graphene.String),description=(f"{ADDED_IN_31} List of all currencies supported by shop's channels."),required=True,+ permissions=[+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ ],)countries = NonNullList(CountryDisplay,@@ -178,11 +178,15 @@ class Shop(graphene.ObjectType):default_country = graphene.Field(CountryDisplay, description="Shop's default country.")- default_mail_sender_name = graphene.String(- description="Default shop's email sender's name."+ default_mail_sender_name = PermissionsField(+ graphene.String,+ description="Default shop's email sender's name.",+ permissions=[SitePermissions.MANAGE_SETTINGS],)- default_mail_sender_address = graphene.String(- description="Default shop's email sender's address."+ default_mail_sender_address = PermissionsField(+ graphene.String,+ description="Default shop's email sender's address.",+ permissions=[SitePermissions.MANAGE_SETTINGS],)description = graphene.String(description="Shop's description.")domain = graphene.Field(Domain, required=True, description="Shop's domain data.")@@ -221,34 +225,44 @@ class Shop(graphene.ObjectType):)default_weight_unit = WeightUnitsEnum(description="Default weight unit.")translation = TranslationField(ShopTranslation, type_name="shop", resolver=None)- automatic_fulfillment_digital_products = graphene.Boolean(- description="Enable automatic fulfillment for all digital products."+ automatic_fulfillment_digital_products = PermissionsField(+ graphene.Boolean,+ description="Enable automatic fulfillment for all digital products.",+ permissions=[SitePermissions.MANAGE_SETTINGS],)-- reserve_stock_duration_anonymous_user = graphene.Int(+ reserve_stock_duration_anonymous_user = PermissionsField(+ graphene.Int,description=(f"{ADDED_IN_31} Default number of minutes stock will be reserved for ""anonymous checkout or null when stock reservation is disabled."- )+ ),+ permissions=[SitePermissions.MANAGE_SETTINGS],)- reserve_stock_duration_authenticated_user = graphene.Int(+ reserve_stock_duration_authenticated_user = PermissionsField(+ graphene.Int,description=(f"{ADDED_IN_31} Default number of minutes stock will be reserved for ""authenticated checkout or null when stock reservation is disabled."- )+ ),+ permissions=[SitePermissions.MANAGE_SETTINGS],)- limit_quantity_per_checkout = graphene.Int(+ limit_quantity_per_checkout = PermissionsField(+ graphene.Int,description=(f"{ADDED_IN_31} Default number of maximum line quantity in single checkout "f"(per single checkout line). {PREVIEW_FEATURE}"- )+ ),+ permissions=[SitePermissions.MANAGE_SETTINGS],)-- default_digital_max_downloads = graphene.Int(- description="Default number of max downloads per digital content URL."+ default_digital_max_downloads = PermissionsField(+ graphene.Int,+ description="Default number of max downloads per digital content URL.",+ permissions=[SitePermissions.MANAGE_SETTINGS],)- default_digital_url_valid_days = graphene.Int(- description="Default number of days which digital content URL will be valid."+ default_digital_url_valid_days = PermissionsField(+ graphene.Int,+ description="Default number of days which digital content URL will be valid.",+ permissions=[SitePermissions.MANAGE_SETTINGS],)company_address = graphene.Field(Address, description="Company address.", required=False@@ -257,17 +271,27 @@ class Shop(graphene.ObjectType):description="URL of a view where customers can set their password.",required=False,)- staff_notification_recipients = NonNullList(- StaffNotificationRecipient,+ staff_notification_recipients = PermissionsField(+ NonNullList(StaffNotificationRecipient),description="List of staff notification recipients.",required=False,+ permissions=[SitePermissions.MANAGE_SETTINGS],)- limits = graphene.Field(+ limits = PermissionsField(LimitInfo,required=True,description="Resource limitations and current usage if any set for a shop",+ permissions=[AuthorizationFilters.AUTHENTICATED_STAFF_USER],+ )+ version = PermissionsField(+ graphene.String,+ description="Saleor API version.",+ required=True,+ permissions=[+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ ],)- version = graphene.String(description="Saleor API version.", required=True)class Meta:description = (@@ -293,7 +317,6 @@ class Shop(graphene.ObjectType):return resolve_available_shipping_methods(info, channel, address)@staticmethod- @staff_member_or_app_requireddef resolve_channel_currencies(_, info):return set(channel_models.Channel.objects.values_list("currency_code", flat=True)@@ -386,12 +409,10 @@ class Shop(graphene.ObjectType):return default_country@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_default_mail_sender_name(_, info):return info.context.site.settings.default_mail_sender_name@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_default_mail_sender_address(_, info):return info.context.site.settings.default_mail_sender_address@@ -408,50 +429,41 @@ class Shop(graphene.ObjectType):return resolve_translation(info.context.site.settings, info, language_code)@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_automatic_fulfillment_digital_products(_, info):site_settings = info.context.site.settingsreturn site_settings.automatic_fulfillment_digital_products@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_reserve_stock_duration_anonymous_user(_, info):site_settings = info.context.site.settingsreturn site_settings.reserve_stock_duration_anonymous_user@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_reserve_stock_duration_authenticated_user(_, info):site_settings = info.context.site.settingsreturn site_settings.reserve_stock_duration_authenticated_user@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_limit_quantity_per_checkout(_, info):site_settings = info.context.site.settingsreturn site_settings.limit_quantity_per_checkout@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_default_digital_max_downloads(_, info):return info.context.site.settings.default_digital_max_downloads@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_default_digital_url_valid_days(_, info):return info.context.site.settings.default_digital_url_valid_days@staticmethod- @permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_staff_notification_recipients(_, info):return account_models.StaffNotificationRecipient.objects.all()@staticmethod- @staff_member_requireddef resolve_limits(_, _info):return LimitInfo(current_usage=Limits(), allowed_usage=Limits())@staticmethod- @staff_member_or_app_requireddef resolve_version(_, _info):return __version__diff --git a/saleor/graphql/tests/test_decorators.py b/saleor/graphql/tests/test_decorators.pyindex f5253660f9..07c12aecb3 100644--- a/saleor/graphql/tests/test_decorators.py+++ b/saleor/graphql/tests/test_decorators.py@@ -48,7 +48,7 @@ def test_permission_required_with_limited_permissions(request.user = staff_userrequest.app = Nonerequestor = get_user_or_app_from_context(request)- has_perms = core_permission_required(permissions_required, requestor)+ has_perms = core_permission_required(requestor, permissions_required)assert has_perms == access_granted@@ -84,5 +84,5 @@ def test_permission_required(request.user = staff_userrequest.app = Nonerequestor = get_user_or_app_from_context(request)- has_perms = core_permission_required(permissions_required, requestor)+ has_perms = core_permission_required(requestor, permissions_required)assert has_perms == access_granteddiff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.pyindex a02af32acc..88c796fb91 100644--- a/saleor/graphql/translations/schema.py+++ b/saleor/graphql/translations/schema.py@@ -9,9 +9,8 @@ from ...product.models import Category, Collection, Product, ProductVariantfrom ...shipping.models import ShippingMethodfrom ..attribute.resolvers import resolve_attributesfrom ..core.connection import CountableConnection, create_connection_slice-from ..core.fields import ConnectionField+from ..core.fields import ConnectionField, PermissionsFieldfrom ..core.utils import from_global_id_or_error-from ..decorators import permission_requiredfrom ..menu.resolvers import resolve_menu_itemsfrom ..page.resolvers import resolve_pagesfrom ..product.resolvers import resolve_categories@@ -80,8 +79,11 @@ class TranslationQueries(graphene.ObjectType):kind=graphene.Argument(TranslatableKinds, required=True, description="Kind of objects to retrieve."),+ permissions=[+ SitePermissions.MANAGE_TRANSLATIONS,+ ],)- translation = graphene.Field(+ translation = PermissionsField(TranslatableItem,id=graphene.Argument(graphene.ID, description="ID of the object to retrieve.", required=True@@ -91,9 +93,9 @@ class TranslationQueries(graphene.ObjectType):required=True,description="Kind of the object to retrieve.",),+ permissions=[SitePermissions.MANAGE_TRANSLATIONS],)- @permission_required(SitePermissions.MANAGE_TRANSLATIONS)def resolve_translations(self, info, kind, **kwargs):if kind == TranslatableKinds.PRODUCT:qs = resolve_products(info)@@ -120,7 +122,6 @@ class TranslationQueries(graphene.ObjectType):return create_connection_slice(qs, info, kwargs, TranslatableItemConnection)- @permission_required(SitePermissions.MANAGE_TRANSLATIONS)def resolve_translation(self, info, id, kind, **_kwargs):_type, kind_id = from_global_id_or_error(id)if not _type == kind:diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.pyindex 66fa212f42..4e959d1f90 100644--- a/saleor/graphql/translations/types.py+++ b/saleor/graphql/translations/types.py@@ -17,10 +17,9 @@ from ...site import models as site_modelsfrom ..channel import ChannelContextfrom ..core.descriptions import DEPRECATED_IN_3X_FIELDfrom ..core.enums import LanguageCodeEnum-from ..core.fields import JSONString+from ..core.fields import JSONString, PermissionsFieldfrom ..core.types import LanguageDisplay, ModelObjectType, NonNullListfrom ..core.utils import str_to_enum-from ..decorators import permission_requiredfrom ..page.dataloaders import SelectedAttributesByPageIdLoaderfrom ..product.dataloaders import (SelectedAttributesByProductIdLoader,@@ -454,7 +453,7 @@ class VoucherTranslatableContent(ModelObjectType):id = graphene.GlobalID(required=True)name = graphene.String()translation = TranslationField(VoucherTranslation, type_name="voucher")- voucher = graphene.Field(+ voucher = PermissionsField("saleor.graphql.discount.types.Voucher",description=("Vouchers allow giving discounts to particular customers on categories, "@@ -464,6 +463,7 @@ class VoucherTranslatableContent(ModelObjectType):deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Get model fields from the root level queries."),+ permissions=[DiscountPermissions.MANAGE_DISCOUNTS],)class Meta:@@ -471,7 +471,6 @@ class VoucherTranslatableContent(ModelObjectType):interfaces = [graphene.relay.Node]@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_voucher(root: discount_models.Voucher, _info):return ChannelContext(node=root, channel_slug=None)@@ -489,7 +488,7 @@ class SaleTranslatableContent(ModelObjectType):id = graphene.GlobalID(required=True)name = graphene.String(required=True)translation = TranslationField(SaleTranslation, type_name="sale")- sale = graphene.Field(+ sale = PermissionsField("saleor.graphql.discount.types.Sale",description=("Sales allow creating discounts for categories, collections "@@ -498,6 +497,7 @@ class SaleTranslatableContent(ModelObjectType):deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Get model fields from the root level queries."),+ permissions=[DiscountPermissions.MANAGE_DISCOUNTS],)class Meta:@@ -505,7 +505,6 @@ class SaleTranslatableContent(ModelObjectType):interfaces = [graphene.relay.Node]@staticmethod- @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_sale(root: discount_models.Sale, _info):return ChannelContext(node=root, channel_slug=None)@@ -570,7 +569,7 @@ class ShippingMethodTranslatableContent(ModelObjectType):translation = TranslationField(ShippingMethodTranslation, type_name="shipping method")- shipping_method = graphene.Field(+ shipping_method = PermissionsField("saleor.graphql.shipping.types.ShippingMethodType",description=("Shipping method are the methods you'll use to get customer's orders "@@ -579,6 +578,9 @@ class ShippingMethodTranslatableContent(ModelObjectType):deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Get model fields from the root level queries."),+ permissions=[+ ShippingPermissions.MANAGE_SHIPPING,+ ],)class Meta:@@ -586,6 +588,5 @@ class ShippingMethodTranslatableContent(ModelObjectType):interfaces = [graphene.relay.Node]@staticmethod- @permission_required(ShippingPermissions.MANAGE_SHIPPING)def resolve_shipping_method(root: shipping_models.ShippingMethod, _info):return ChannelContext(node=root, channel_slug=None)diff --git a/saleor/graphql/warehouse/schema.py b/saleor/graphql/warehouse/schema.pyindex c197b05230..1bbe4a6040 100644--- a/saleor/graphql/warehouse/schema.py+++ b/saleor/graphql/warehouse/schema.py@@ -6,9 +6,8 @@ from ...core.permissions import (ShippingPermissions,)from ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.fields import FilterConnectionField+from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.utils import from_global_id_or_error-from ..decorators import one_of_permissions_required, permission_requiredfrom .filters import StockFilterInput, WarehouseFilterInputfrom .mutations import (WarehouseCreate,@@ -33,39 +32,35 @@ from .types import (class WarehouseQueries(graphene.ObjectType):- warehouse = graphene.Field(+ warehouse = PermissionsField(Warehouse,description="Look up a warehouse by ID.",id=graphene.Argument(graphene.ID, description="ID of an warehouse", required=True),+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ShippingPermissions.MANAGE_SHIPPING,+ ],)warehouses = FilterConnectionField(WarehouseCountableConnection,description="List of warehouses.",filter=WarehouseFilterInput(),sort_by=WarehouseSortingInput(),- )-- @one_of_permissions_required(- [+ permissions=[ProductPermissions.MANAGE_PRODUCTS,OrderPermissions.MANAGE_ORDERS,ShippingPermissions.MANAGE_SHIPPING,- ]+ ],)+def resolve_warehouse(self, info, **data):warehouse_pk = data.get("id")_, id = from_global_id_or_error(warehouse_pk, Warehouse)return resolve_warehouse(id)- @one_of_permissions_required(- [- ProductPermissions.MANAGE_PRODUCTS,- OrderPermissions.MANAGE_ORDERS,- ShippingPermissions.MANAGE_SHIPPING,- ]- )def resolve_warehouses(self, info, **kwargs):qs = resolve_warehouses()qs = filter_connection_queryset(qs, kwargs)@@ -81,24 +76,24 @@ class WarehouseMutations(graphene.ObjectType):class StockQueries(graphene.ObjectType):- stock = graphene.Field(+ stock = PermissionsField(Stock,description="Look up a stock by ID",id=graphene.ID(required=True, description="ID of an warehouse"),+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)stocks = FilterConnectionField(StockCountableConnection,description="List of stocks.",filter=StockFilterInput(),+ permissions=[ProductPermissions.MANAGE_PRODUCTS],)- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_stock(self, info, **kwargs):stock_id = kwargs.get("id")_, id = from_global_id_or_error(stock_id, Stock)return resolve_stock(id)- @permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_stocks(self, info, **kwargs):qs = resolve_stocks()qs = filter_connection_queryset(qs, kwargs)diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex 97511e7acf..f15b844b44 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -10,9 +10,8 @@ from ..account.dataloaders import AddressByIdLoaderfrom ..channel import ChannelContextfrom ..core.connection import CountableConnection, create_connection_slicefrom ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE-from ..core.fields import ConnectionField+from ..core.fields import ConnectionField, PermissionsFieldfrom ..core.types import ModelObjectType, NonNullList-from ..decorators import one_of_permissions_requiredfrom ..meta.types import ObjectWithMetadatafrom .dataloaders import WarehouseByIdLoaderfrom .enums import WarehouseClickAndCollectOptionEnum@@ -131,16 +130,35 @@ class Stock(ModelObjectType):product_variant = graphene.Field("saleor.graphql.product.types.ProductVariant", required=True)- quantity = graphene.Int(+ quantity = PermissionsField(+ graphene.Int,required=True,- description="Quantity of a product in the warehouse's possession, "- "including the allocated stock that is waiting for shipment.",+ description=(+ "Quantity of a product in the warehouse's possession, including the "+ "allocated stock that is waiting for shipment."+ ),+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ],)- quantity_allocated = graphene.Int(- required=True, description="Quantity allocated for orders"+ quantity_allocated = PermissionsField(+ graphene.Int,+ required=True,+ description="Quantity allocated for orders.",+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ],)- quantity_reserved = graphene.Int(- required=True, description="Quantity reserved for checkouts"+ quantity_reserved = PermissionsField(+ graphene.Int,+ required=True,+ description="Quantity reserved for checkouts.",+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ],)class Meta:@@ -149,25 +167,16 @@ class Stock(ModelObjectType):interfaces = [graphene.relay.Node]@staticmethod- @one_of_permissions_required(- [ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]- )def resolve_quantity(root, *_args):return root.quantity@staticmethod- @one_of_permissions_required(- [ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]- )def resolve_quantity_allocated(root, *_args):return root.allocations.aggregate(quantity_allocated=Coalesce(Sum("quantity_allocated"), 0))["quantity_allocated"]@staticmethod- @one_of_permissions_required(- [ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]- )def resolve_quantity_reserved(root, info, *_args):if not is_reservation_enabled(info.context.site.settings):return 0@@ -200,9 +209,23 @@ class StockCountableConnection(CountableConnection):class Allocation(graphene.ObjectType):id = graphene.GlobalID(required=True)- quantity = graphene.Int(required=True, description="Quantity allocated for orders.")- warehouse = graphene.Field(- Warehouse, required=True, description="The warehouse were items were allocated."+ quantity = PermissionsField(+ graphene.Int,+ required=True,+ description="Quantity allocated for orders.",+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ],+ )+ warehouse = PermissionsField(+ Warehouse,+ required=True,+ description="The warehouse were items were allocated.",+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ],)class Meta:@@ -218,21 +241,9 @@ class Allocation(graphene.ObjectType):return None@staticmethod- @one_of_permissions_required(- [- ProductPermissions.MANAGE_PRODUCTS,- OrderPermissions.MANAGE_ORDERS,- ]- )def resolve_warehouse(root, *_args):return root.stock.warehouse@staticmethod- @one_of_permissions_required(- [- ProductPermissions.MANAGE_PRODUCTS,- OrderPermissions.MANAGE_ORDERS,- ]- )def resolve_quantity(root, *_args):return root.quantity_allocateddiff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.pyindex d9e22dd745..c1db3c221e 100644--- a/saleor/graphql/webhook/resolvers.py+++ b/saleor/graphql/webhook/resolvers.py@@ -8,18 +8,6 @@ from ..core.utils import from_global_id_or_errorfrom .types import Webhook, WebhookEvent-def resolve_webhooks(info, **_kwargs):- app = info.context.app- if app:- qs = models.Webhook.objects.filter(app=app)- else:- user = info.context.user- if not user.has_perm(AppPermission.MANAGE_APPS):- raise PermissionDenied(permissions=[AppPermission.MANAGE_APPS])- qs = models.Webhook.objects.all()- return qs--def resolve_webhook(info, id):app = info.context.app_, id = from_global_id_or_error(id, Webhook)diff --git a/saleor/graphql/webhook/schema.py b/saleor/graphql/webhook/schema.pyindex b172a0783f..7d51b59d4a 100644--- a/saleor/graphql/webhook/schema.py+++ b/saleor/graphql/webhook/schema.py@@ -1,10 +1,9 @@import graphene-from ...core.permissions import AppPermission+from ...core.permissions import AppPermission, AuthorizationFiltersfrom ..core.descriptions import DEPRECATED_IN_3X_FIELD-from ..core.fields import JSONString+from ..core.fields import JSONString, PermissionsFieldfrom ..core.types import NonNullList-from ..decorators import permission_requiredfrom .enums import WebhookSampleEventTypeEnumfrom .mutations import EventDeliveryRetry, WebhookCreate, WebhookDelete, WebhookUpdatefrom .resolvers import resolve_sample_payload, resolve_webhook, resolve_webhook_events@@ -17,15 +16,19 @@ class WebhookQueries(graphene.ObjectType):id=graphene.Argument(graphene.ID, required=True, description="ID of the webhook."),- description="Look up a webhook by ID.",+ description=(+ "Look up a webhook by ID. Requires one of the following permissions: "+ f"{AppPermission.MANAGE_APPS}, {AuthorizationFilters.OWNER}"+ ),)- webhook_events = NonNullList(- WebhookEvent,+ webhook_events = PermissionsField(+ NonNullList(WebhookEvent),description="List of all available webhook events.",deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Use `WebhookEventTypeAsyncEnum` and ""`WebhookEventTypeSyncEnum` to get available event types."),+ permissions=[AppPermission.MANAGE_APPS],)webhook_sample_payload = graphene.Field(JSONString,@@ -49,7 +52,6 @@ class WebhookQueries(graphene.ObjectType):return resolve_webhook(info, data["id"])@staticmethod- @permission_required(AppPermission.MANAGE_APPS)def resolve_webhook_events(_, *_args, **_data):return resolve_webhook_events()