Skip to content

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

Fix products visibility (#6704)

Iga Karbowiakff4beeaca890
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e1c3aa6932..028dcce4b0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Get tax rate from plugins - #6649 by @IKarbowiak
- Added support for querying user by email - #6632 @LeOndaz
- Add order shipping tax rate - #6678 by @IKarbowiak
+- Fix products visibility - #6704 by @IKarbowiak
# 2.11.1
diff --git a/saleor/account/tests/test_account.py b/saleor/account/tests/test_account.py
index 8f0bae603a..390b9943b2 100644
--- a/saleor/account/tests/test_account.py
+++ b/saleor/account/tests/test_account.py
@@ -10,7 +10,7 @@ from django_countries.fields import Country
from .. import forms, i18n
from ..models import User
from ..templatetags.i18n_address_tags import format_address
-from ..utils import remove_staff_member
+from ..utils import remove_staff_member, requestor_is_staff_member_or_app
from ..validators import validate_possible_number
@@ -304,3 +304,33 @@ def test_remove_staff_member_with_orders(staff_user, permission_manage_products,
def test_remove_staff_member(staff_user):
remove_staff_member(staff_user)
assert not User.objects.filter(pk=staff_user.pk).exists()
+
+
+def test_requestor_is_staff_member_or_app_active_app(app):
+ assert app.is_active is True
+ assert requestor_is_staff_member_or_app(app) is True
+
+
+def test_requestor_is_staff_member_or_app_not_active_app(app):
+ app.is_active = False
+ app.save(update_fields=["is_active"])
+ assert requestor_is_staff_member_or_app(app) is False
+
+
+def test_requestor_is_staff_member_or_app_not_active_staff_user(staff_user):
+ staff_user.is_active = False
+ staff_user.save(update_fields=["is_active"])
+ assert requestor_is_staff_member_or_app(staff_user) is False
+
+
+def test_requestor_is_staff_member_or_app_active_staff_user(staff_user):
+ assert staff_user.is_active is True
+ assert requestor_is_staff_member_or_app(staff_user) is True
+
+
+def test_requestor_is_staff_member_or_app_superuser(superuser):
+ assert requestor_is_staff_member_or_app(superuser) is True
+
+
+def test_requestor_is_staff_member_or_app_customer_user(customer_user):
+ assert requestor_is_staff_member_or_app(customer_user) is False
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index 4656afc87a..bc820aab7a 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -1,3 +1,6 @@
+from typing import Union
+
+from ..app.models import App
from ..checkout import AddressType
from ..core.utils import create_thumbnails
from ..plugins.manager import get_plugins_manager
@@ -77,3 +80,13 @@ def remove_staff_member(staff):
staff.save()
else:
staff.delete()
+
+
+def requestor_is_staff_member_or_app(requestor: Union[User, App]):
+ """Return true if requestor is an active app or active staff user."""
+ is_staff = False
+ if isinstance(requestor, User):
+ is_staff = getattr(requestor, "is_staff")
+ elif isinstance(requestor, App):
+ is_staff = True
+ return is_staff and requestor.is_active
diff --git a/saleor/attribute/models.py b/saleor/attribute/models.py
index 8c761b3729..1b93977492 100644
--- a/saleor/attribute/models.py
+++ b/saleor/attribute/models.py
@@ -3,8 +3,8 @@ from typing import TYPE_CHECKING, Union
from django.db import models
from django.db.models import F, Q
+from ..account.utils import requestor_is_staff_member_or_app
from ..core.models import ModelWithMetadata, SortableModel
-from ..core.permissions import ProductPermissions
from ..core.utils.translations import TranslationProxy
from ..page.models import Page, PageType
from ..product.models import Product, ProductType, ProductVariant
@@ -14,18 +14,15 @@ if TYPE_CHECKING:
from django.db.models import OrderBy
from ..account.models import User
+ from ..app.models import App
class BaseAttributeQuerySet(models.QuerySet):
- @staticmethod
- def user_has_access_to_all(user: "User") -> bool:
- return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
-
def get_public_attributes(self):
raise NotImplementedError
- def get_visible_to_user(self, user: "User"):
- if self.user_has_access_to_all(user):
+ def get_visible_to_user(self, requestor: Union["User", "App"]):
+ if requestor_is_staff_member_or_app(requestor):
return self.all()
return self.get_public_attributes()
diff --git a/saleor/core/models.py b/saleor/core/models.py
index 11a36da026..2a0f0ed626 100644
--- a/saleor/core/models.py
+++ b/saleor/core/models.py
@@ -6,7 +6,6 @@ from django.db.models import JSONField # type: ignore
from django.db.models import F, Max, Q
from . import JobStatus
-from .permissions import ProductPermissions
from .utils.json_serializer import CustomJsonEncoder
@@ -48,12 +47,10 @@ class PublishedQuerySet(models.QuerySet):
is_published=True,
)
- @staticmethod
- def user_has_access_to_all(user):
- return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
+ def visible_to_user(self, requestor):
+ from ..account.utils import requestor_is_staff_member_or_app
- def visible_to_user(self, user):
- if self.user_has_access_to_all(user):
+ if requestor_is_staff_member_or_app(requestor):
return self.all()
return self.published()
diff --git a/saleor/graphql/attribute/filters.py b/saleor/graphql/attribute/filters.py
index 9cf482ea1f..6e1986be9e 100644
--- a/saleor/graphql/attribute/filters.py
+++ b/saleor/graphql/attribute/filters.py
@@ -2,6 +2,7 @@ import django_filters
from django.db.models import Q
from graphene_django.filter import GlobalIDFilter, GlobalIDMultipleChoiceFilter
+from ...account.utils import requestor_is_staff_member_or_app
from ...attribute.models import Attribute
from ...product.models import Category, Product
from ..attribute.enums import AttributeTypeEnum
@@ -31,7 +32,7 @@ def filter_attributes_by_product_types(qs, field, value, requestor, channel_slug
tree = category.get_descendants(include_self=True)
product_qs = product_qs.filter(category__in=tree)
- if not product_qs.user_has_access_to_all(requestor):
+ if not requestor_is_staff_member_or_app(requestor):
product_qs = product_qs.annotate_visible_in_listings(channel_slug).exclude(
visible_in_listings=False
)
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_filter.py b/saleor/graphql/attribute/tests/queries/test_attribute_filter.py
index 44d6ed32d6..30d9a72f62 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_filter.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_filter.py
@@ -178,11 +178,10 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_with_per
assert len(attributes) == attribute_count
-def test_filter_attributes_in_category_not_visible_in_listings_by_staff_without_perm(
+def test_filter_attributes_in_category_not_in_listings_by_staff_without_manage_products(
staff_api_client,
product_list,
weight_attribute,
- permission_manage_products,
channel_USD,
):
# given
@@ -219,10 +218,7 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_without_
)["data"]["attributes"]["edges"]
# then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
+ assert len(attributes) == attribute_count
def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
@@ -271,11 +267,10 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
assert len(attributes) == attribute_count
-def test_filter_attributes_in_category_not_visible_in_listings_by_app_without_perm(
+def test_filter_attributes_in_category_not_in_listings_by_app_without_manage_products(
app_api_client,
product_list,
weight_attribute,
- permission_manage_products,
channel_USD,
):
# given
@@ -312,10 +307,7 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_without_pe
)["data"]["attributes"]["edges"]
# then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
+ assert len(attributes) == attribute_count
def test_filter_attributes_in_category_not_published_by_customer(
@@ -407,11 +399,10 @@ def test_filter_attributes_in_category_not_published_by_staff_with_perm(
assert len(attributes) == attribute_count
-def test_filter_attributes_in_category_not_published_by_staff_without_perm(
+def test_filter_attributes_in_category_not_published_by_staff_without_manage_products(
staff_api_client,
product_list,
weight_attribute,
- permission_manage_products,
channel_USD,
):
# given
@@ -448,10 +439,7 @@ def test_filter_attributes_in_category_not_published_by_staff_without_perm(
)["data"]["attributes"]["edges"]
# then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
+ assert len(attributes) == attribute_count
def test_filter_attributes_in_category_not_published_by_app_with_perm(
@@ -500,11 +488,10 @@ def test_filter_attributes_in_category_not_published_by_app_with_perm(
assert len(attributes) == attribute_count
-def test_filter_attributes_in_category_not_published_by_app_without_perm(
+def test_filter_attributes_in_category_not_published_by_app_without_manage_products(
app_api_client,
product_list,
weight_attribute,
- permission_manage_products,
channel_USD,
):
# given
@@ -541,10 +528,7 @@ def test_filter_attributes_in_category_not_published_by_app_without_perm(
)["data"]["attributes"]["edges"]
# then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
+ assert len(attributes) == attribute_count
def test_filter_attributes_in_collection_not_visible_in_listings_by_customer(
@@ -683,11 +667,10 @@ def test_filter_in_collection_not_published_by_staff_with_perm(
assert len(attributes) == attribute_count
-def test_filter_in_collection_not_published_by_staff_without_perm(
+def test_filter_in_collection_not_published_by_staff_without_manage_products(
staff_api_client,
product_list,
weight_attribute,
- permission_manage_products,
collection,
channel_USD,
):
@@ -727,10 +710,7 @@ def test_filter_in_collection_not_published_by_staff_without_perm(
)["data"]["attributes"]["edges"]
# then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
+ assert len(attributes) == attribute_count
def test_filter_in_collection_not_published_by_app_with_perm(
@@ -782,11 +762,10 @@ def test_filter_in_collection_not_published_by_app_with_perm(
assert len(attributes) == attribute_count
-def test_filter_in_collection_not_published_by_app_without_perm(
+def test_filter_in_collection_not_published_by_app_without_manage_products(
app_api_client,
product_list,
weight_attribute,
- permission_manage_products,
collection,
channel_USD,
):
@@ -826,10 +805,7 @@ def test_filter_in_collection_not_published_by_app_without_perm(
)["data"]["attributes"]["edges"]
# then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
+ assert len(attributes) == attribute_count
def test_filter_attributes_by_page_type(
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
index 2b485a29eb..b00f09a196 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
@@ -298,7 +298,7 @@ def test_attributes_query_hidden_attribute(user_api_client, product, color_attri
def test_attributes_query_hidden_attribute_as_staff_user(
- staff_api_client, product, color_attribute, permission_manage_products
+ staff_api_client, product, color_attribute
):
query = QUERY_ATTRIBUTES
@@ -308,13 +308,6 @@ def test_attributes_query_hidden_attribute_as_staff_user(
attribute_count = Attribute.objects.all().count()
- # The user doesn't have the permission yet to manage products,
- # the user shouldn't be able to see the hidden attributes
- assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1
-
- # The user should now be able to see the attributes
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
response = staff_api_client.post_graphql(query)
content = get_graphql_content(response)
attributes_data = content["data"]["attributes"]["edges"]
diff --git a/saleor/graphql/menu/types.py b/saleor/graphql/menu/types.py
index 956c9b7c17..ca7632b3c2 100644
--- a/saleor/graphql/menu/types.py
+++ b/saleor/graphql/menu/types.py
@@ -1,9 +1,9 @@
import graphene
from graphene import relay
+from ...account.utils import requestor_is_staff_member_or_app
from ...core.permissions import PagePermissions
from ...menu import models
-from ...product.models import Collection
from ..channel.dataloaders import ChannelBySlugLoader
from ..channel.types import (
ChannelContext,
@@ -104,10 +104,8 @@ class MenuItem(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
return None
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = Collection.objects.user_has_access_to_all(
- requestor
- )
- if requestor_has_access_to_all:
+ is_staff = requestor_is_staff_member_or_app(requestor)
+ if is_staff:
return (
CollectionByIdLoader(info.context)
.load(root.node.collection_id)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index bd1770a6d3..2c50a35bdd 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -3,6 +3,7 @@ from django.core.exceptions import ValidationError
from graphene import relay
from promise import Promise
+from ...account.utils import requestor_is_staff_member_or_app
from ...core.anonymize import obfuscate_address, obfuscate_email
from ...core.exceptions import PermissionDenied
from ...core.permissions import AccountPermissions, OrderPermissions, ProductPermissions
@@ -12,7 +13,6 @@ from ...order import OrderStatus, models
from ...order.models import FulfillmentStatus
from ...order.utils import get_order_country, get_valid_shipping_methods_for_order
from ...plugins.manager import get_plugins_manager
-from ...product.models import Product
from ...product.templatetags.product_images import get_product_image_thumbnail
from ...warehouse import models as warehouse_models
from ..account.types import User
@@ -331,10 +331,8 @@ class OrderLine(CountableDjangoObjectType):
variant, channel = data
requester = get_user_or_app_from_context(context)
- requestor_has_access_to_all = Product.objects.user_has_access_to_all(
- requester
- )
- if requestor_has_access_to_all:
+ is_staff = requestor_is_staff_member_or_app(requester)
+ if is_staff:
return ChannelContext(node=variant, channel_slug=channel.slug)
def product_is_available(product_channel_listing):
diff --git a/saleor/graphql/page/tests/test_page.py b/saleor/graphql/page/tests/test_page.py
index c55de6e691..4da63d6605 100644
--- a/saleor/graphql/page/tests/test_page.py
+++ b/saleor/graphql/page/tests/test_page.py
@@ -88,7 +88,7 @@ def test_customer_query_unpublished_page(user_api_client, page):
assert content["data"]["page"] is None
-def test_staff_query_unpublished_page(staff_api_client, page, permission_manage_pages):
+def test_staff_query_unpublished_page(staff_api_client, page):
page.is_published = False
page.save()
@@ -96,32 +96,12 @@ def test_staff_query_unpublished_page(staff_api_client, page, permission_manage_
variables = {"id": graphene.Node.to_global_id("Page", page.id)}
response = staff_api_client.post_graphql(PAGE_QUERY, variables)
content = get_graphql_content(response)
- assert content["data"]["page"] is None
+ assert content["data"]["page"] is not None
+
# query by slug
variables = {"slug": page.slug}
response = staff_api_client.post_graphql(PAGE_QUERY, variables)
content = get_graphql_content(response)
- assert content["data"]["page"] is None
-
- # query by ID with page permissions
- variables = {"id": graphene.Node.to_global_id("Page", page.id)}
- response = staff_api_client.post_graphql(
- PAGE_QUERY,
- variables,
- permissions=[permission_manage_pages],
- check_no_permissions=False,
- )
- content = get_graphql_content(response)
- assert content["data"]["page"] is not None
- # query by slug with page permissions
- variables = {"slug": page.slug}
- response = staff_api_client.post_graphql(
- PAGE_QUERY,
- variables,
- permissions=[permission_manage_pages],
- check_no_permissions=False,
- )
- content = get_graphql_content(response)
assert content["data"]["page"] is not None
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index bce9969560..1f1b11c481 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -1,9 +1,10 @@
from django.db.models import Sum
+from ...account.utils import requestor_is_staff_member_or_app
from ...order import OrderStatus
from ...product import models
from ..channel import ChannelQsContext
-from ..utils import get_database_id
+from ..utils import get_database_id, get_user_or_app_from_context
from ..utils.filters import filter_by_period
from .filters import filter_products_by_stock_availability
@@ -36,8 +37,8 @@ def resolve_collection_by_slug(info, slug, channel_slug, requestor):
def resolve_collections(info, channel_slug):
- user = info.context.user
- qs = models.Collection.objects.visible_to_user(user, channel_slug)
+ requestor = get_user_or_app_from_context(info.context)
+ qs = models.Collection.objects.visible_to_user(requestor, channel_slug)
return ChannelQsContext(qs=qs, channel_slug=channel_slug)
@@ -68,7 +69,7 @@ def resolve_products(
qs = models.Product.objects.visible_to_user(requestor, channel_slug)
if stock_availability:
qs = filter_products_by_stock_availability(qs, stock_availability)
- if not qs.user_has_access_to_all(requestor):
+ if not requestor_is_staff_member_or_app(requestor):
qs = qs.annotate_visible_in_listings(channel_slug).exclude(
visible_in_listings=False
)
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 2b7dc8f174..1580457631 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -1,7 +1,7 @@
import graphene
+from ...account.utils import requestor_is_staff_member_or_app
from ...core.permissions import ProductPermissions
-from ...product import models
from ..channel import ChannelContext
from ..channel.utils import get_default_channel_slug_or_graphql_error
from ..core.enums import ReportingPeriod
@@ -259,10 +259,8 @@ class ProductQueries(graphene.ObjectType):
validate_one_of_args_is_in_query("id", id, "slug", slug)
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = models.Collection.objects.user_has_access_to_all(
- requestor
- )
- if channel is None and not requestor_has_access_to_all:
+ is_staff = requestor_is_staff_member_or_app(requestor)
+ if channel is None and not is_staff:
channel = get_default_channel_slug_or_graphql_error()
if id:
_, id = graphene.Node.from_global_id(id)
@@ -279,10 +277,8 @@ class ProductQueries(graphene.ObjectType):
def resolve_collections(self, info, channel=None, *_args, **_kwargs):
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = models.Collection.objects.user_has_access_to_all(
- requestor
- )
- if channel is None and not requestor_has_access_to_all:
+ is_staff = requestor_is_staff_member_or_app(requestor)
+ if channel is None and not is_staff:
channel = get_default_channel_slug_or_graphql_error()
return resolve_collections(info, channel)
@@ -297,11 +293,9 @@ class ProductQueries(graphene.ObjectType):
def resolve_product(self, info, id=None, slug=None, channel=None, **_kwargs):
validate_one_of_args_is_in_query("id", id, "slug", slug)
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = models.Collection.objects.user_has_access_to_all(
- requestor
- )
+ is_staff = requestor_is_staff_member_or_app(requestor)
- if channel is None and not requestor_has_access_to_all:
+ if channel is None and not is_staff:
channel = get_default_channel_slug_or_graphql_error()
if id:
_, id = graphene.Node.from_global_id(id)
@@ -316,10 +310,7 @@ class ProductQueries(graphene.ObjectType):
def resolve_products(self, info, channel=None, **kwargs):
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
- requestor
- )
- if channel is None and not requestor_has_access_to_all:
+ if channel is None and not requestor_is_staff_member_or_app(requestor):
channel = get_default_channel_slug_or_graphql_error()
return resolve_products(info, requestor, channel_slug=channel, **kwargs)
@@ -338,10 +329,8 @@ class ProductQueries(graphene.ObjectType):
):
validate_one_of_args_is_in_query("id", id, "sku", sku)
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
- requestor
- )
- if channel is None and not requestor_has_access_to_all:
+ is_staff = requestor_is_staff_member_or_app(requestor)
+ if channel is None and not is_staff:
channel = get_default_channel_slug_or_graphql_error()
if id:
_, id = graphene.Node.from_global_id(id)
@@ -354,22 +343,20 @@ class ProductQueries(graphene.ObjectType):
sku=sku,
channel_slug=channel,
requestor=requestor,
- requestor_has_access_to_all=requestor_has_access_to_all,
+ requestor_has_access_to_all=is_staff,
)
return ChannelContext(node=variant, channel_slug=channel) if variant else None
def resolve_product_variants(self, info, ids=None, channel=None, **_kwargs):
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
- requestor
- )
- if channel is None and not requestor_has_access_to_all:
+ is_staff = requestor_is_staff_member_or_app(requestor)
+ if channel is None and not is_staff:
channel = get_default_channel_slug_or_graphql_error()
return resolve_product_variants(
info,
ids=ids,
channel_slug=channel,
- requestor_has_access_to_all=requestor_has_access_to_all,
+ requestor_has_access_to_all=is_staff,
requestor=requestor,
)
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index 24a45a12b6..671e6a2a23 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -125,7 +125,7 @@ def test_query_category_product_only_visible_in_listings_as_customer(
assert len(content["data"]["category"]["products"]["edges"]) == product_count - 1
-def test_query_category_product_only_visible_in_listings_as_staff_without_perm(
+def test_query_category_product_visible_in_listings_as_staff_without_manage_products(
staff_api_client, product_list, channel_USD
):
# given
@@ -145,7 +145,7 @@ def test_query_category_product_only_visible_in_listings_as_staff_without_perm(
# then
content = get_graphql_content(response, ignore_errors=True)
- assert len(content["data"]["category"]["products"]["edges"]) == product_count - 1
+ assert len(content["data"]["category"]["products"]["edges"]) == product_count
def test_query_category_product_only_visible_in_listings_as_staff_with_perm(
@@ -170,7 +170,7 @@ def test_query_category_product_only_visible_in_listings_as_staff_with_perm(
assert len(content["data"]["category"]["products"]["edges"]) == product_count
-def test_query_category_product_only_visible_in_listings_as_app_without_perm(
+def test_query_category_product_only_visible_in_listings_as_app_without_manage_products(
app_api_client, product_list, channel_USD
):
# given
@@ -190,7 +190,7 @@ def test_query_category_product_only_visible_in_listings_as_app_without_perm(
# then
content = get_graphql_content(response, ignore_errors=True)
- assert len(content["data"]["category"]["products"]["edges"]) == product_count - 1
+ assert len(content["data"]["category"]["products"]["edges"]) == product_count
def test_query_category_product_only_visible_in_listings_as_app_with_perm(
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 459e981c12..5fb287030f 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -854,10 +854,10 @@ def test_product_query_is_available_for_purchase_false_no_available_for_purchase
def test_product_query_unpublished_products_by_slug(
- user_api_client, product, permission_manage_products, channel_USD
+ staff_api_client, product, permission_manage_products, channel_USD
):
# given
- user = user_api_client.user
+ user = staff_api_client.user
user.user_permissions.add(permission_manage_products)
ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
@@ -869,7 +869,7 @@ def test_product_query_unpublished_products_by_slug(
}
# when
- response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ response = staff_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
# then
content = get_graphql_content(response)
@@ -1251,8 +1251,8 @@ def test_fetch_all_products_visible_in_listings_by_staff_with_perm(
assert len(product_data) == product_count
-def test_fetch_all_products_visible_in_listings_by_staff_without_perm(
- staff_api_client, product_list, permission_manage_products, channel_USD
+def test_fetch_all_products_visible_in_listings_by_staff_without_manage_products(
+ staff_api_client, product_list, channel_USD
):
# given
product_list[0].channel_listings.update(visible_in_listings=False)
@@ -1266,9 +1266,7 @@ def test_fetch_all_products_visible_in_listings_by_staff_without_perm(
# then
content = get_graphql_content(response)
product_data = content["data"]["products"]["edges"]
- assert len(product_data) == product_count - 1
- products_ids = [product["node"]["id"] for product in product_data]
- assert graphene.Node.to_global_id("Product", product_list[0].pk) not in products_ids
+ assert len(product_data) == product_count
def test_fetch_all_products_visible_in_listings_by_app_with_perm(
@@ -1294,8 +1292,8 @@ def test_fetch_all_products_visible_in_listings_by_app_with_perm(
assert len(product_data) == product_count
-def test_fetch_all_products_visible_in_listings_by_app_without_perm(
- app_api_client, product_list, permission_manage_products, channel_USD
+def test_fetch_all_products_visible_in_listings_by_app_without_manage_products(
+ app_api_client, product_list, channel_USD
):
# given
product_list[0].channel_listings.update(visible_in_listings=False)
@@ -1309,9 +1307,7 @@ def test_fetch_all_products_visible_in_listings_by_app_without_perm(
# then
content = get_graphql_content(response)
product_data = content["data"]["products"]["edges"]
- assert len(product_data) == product_count - 1
- products_ids = [product["node"]["id"] for product in product_data]
- assert graphene.Node.to_global_id("Product", product_list[0].pk) not in products_ids
+ assert len(product_data) == product_count
def test_fetch_product_from_category_query(
@@ -5186,13 +5182,27 @@ def test_product_update_variants_names(mock__update_variants_names, product_type
assert mock__update_variants_names.call_count == 1
-def test_product_variants_by_ids(user_api_client, variant, channel_USD):
+def test_product_variants_by_ids(staff_api_client, variant, channel_USD):
query = """
query getProduct($ids: [ID!], $channel: String) {
productVariants(ids: $ids, first: 1, channel: $channel) {
edges {
node {
id
+ name
+ sku
+ channelListings {
+ channel {
+ id
+ isActive
+ name
+ currencyCode
+ }
+ price {
+ amount
+ currency
+ }
+ }
}
}
}
@@ -5201,13 +5211,46 @@ def test_product_variants_by_ids(user_api_client, variant, channel_USD):
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {"ids": [variant_id], "channel": channel_USD.slug}
- response = user_api_client.post_graphql(query, variables)
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["productVariants"]
assert data["edges"][0]["node"]["id"] == variant_id
assert len(data["edges"]) == 1
+def test_product_variants_by_customer(user_api_client, variant, channel_USD):
+ query = """
+ query getProduct($ids: [ID!], $channel: String) {
+ productVariants(ids: $ids, first: 1, channel: $channel) {
+ edges {
+ node {
+ id
+ name
+ sku
+ channelListings {
+ channel {
+ id
+ isActive
+ name
+ currencyCode
+ }
+ price {
+ amount
+ currency
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {"ids": [variant_id], "channel": channel_USD.slug}
+ response = user_api_client.post_graphql(query, variables)
+ assert_no_permission(response)
+
+
def test_product_variants_no_ids_list(user_api_client, variant, channel_USD):
query = """
query getProductVariants($channel: String) {
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 72c0381c33..30d038b70b 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -140,7 +140,6 @@ QUERY_PRODUCT_VARIANT_CHANNEL_LISTING = """
def test_get_product_variant_channel_listing_as_staff_user(
staff_api_client,
product_available_in_many_channels,
- permission_manage_products,
channel_USD,
):
# given
@@ -152,7 +151,6 @@ def test_get_product_variant_channel_listing_as_staff_user(
response = staff_api_client.post_graphql(
QUERY_PRODUCT_VARIANT_CHANNEL_LISTING,
variables,
- permissions=[permission_manage_products],
)
content = get_graphql_content(response)
@@ -177,7 +175,6 @@ def test_get_product_variant_channel_listing_as_staff_user(
def test_get_product_variant_channel_listing_as_app(
app_api_client,
product_available_in_many_channels,
- permission_manage_products,
channel_USD,
):
# given
@@ -189,7 +186,6 @@ def test_get_product_variant_channel_listing_as_app(
response = app_api_client.post_graphql(
QUERY_PRODUCT_VARIANT_CHANNEL_LISTING,
variables,
- permissions=[permission_manage_products],
)
content = get_graphql_content(response)
@@ -1644,7 +1640,7 @@ def test_product_variants_visible_in_listings_by_customer(
assert data["totalCount"] == product_count - 1
-def test_product_variants_visible_in_listings_by_staff_without_perm(
+def test_product_variants_visible_in_listings_by_staff_without_manage_products(
staff_api_client, product_list, channel_USD
):
# given
@@ -1657,7 +1653,7 @@ def test_product_variants_visible_in_listings_by_staff_without_perm(
staff_api_client, variables={"channel": channel_USD.slug}
)
- assert data["totalCount"] == product_count - 1
+ assert data["totalCount"] == product_count
def test_product_variants_visible_in_listings_by_staff_with_perm(
@@ -1678,7 +1674,7 @@ def test_product_variants_visible_in_listings_by_staff_with_perm(
assert data["totalCount"] == product_count
-def test_product_variants_visible_in_listings_by_app_without_perm(
+def test_product_variants_visible_in_listings_by_app_without_manage_products(
app_api_client, product_list, channel_USD
):
# given
@@ -1689,7 +1685,7 @@ def test_product_variants_visible_in_listings_by_app_without_perm(
# when
data = _fetch_all_variants(app_api_client, variables={"channel": channel_USD.slug})
- assert data["totalCount"] == product_count - 1
+ assert data["totalCount"] == product_count
def test_product_variants_visible_in_listings_by_app_with_perm(
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 35444d3f1e..ad71eed936 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -7,6 +7,7 @@ from graphene import relay
from graphene_federation import key
from graphql.error import GraphQLError
+from ....account.utils import requestor_is_staff_member_or_app
from ....attribute import models as attribute_models
from ....core.permissions import OrderPermissions, ProductPermissions
from ....core.weight import convert_weight_to_default_weight_unit
@@ -38,7 +39,11 @@ from ...core.fields import (
PrefetchingConnectionField,
)
from ...core.types import Image, Money, TaxedMoney, TaxedMoneyRange, TaxType
-from ...decorators import one_of_permissions_required, permission_required
+from ...decorators import (
+ one_of_permissions_required,
+ permission_required,
+ staff_member_or_app_required,
+)
from ...discount.dataloaders import DiscountsByDateTimeLoader
from ...meta.types import ObjectWithMetadata
from ...order.dataloaders import (
@@ -281,7 +286,7 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
)
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ @staff_member_or_app_required
def resolve_channel_listings(
root: ChannelContext[models.ProductVariant], info, **_kwargs
):
@@ -672,12 +677,10 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
@staticmethod
def resolve_collections(root: ChannelContext[models.Product], info, **_kwargs):
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = models.Collection.objects.user_has_access_to_all(
- requestor
- )
+ is_staff = requestor_is_staff_member_or_app(requestor)
def return_collections(collections):
- if requestor_has_access_to_all:
+ if is_staff:
return [
ChannelContext(node=collection, channel_slug=root.channel_slug)
for collection in collections
@@ -853,10 +856,10 @@ class ProductType(CountableDjangoObjectType):
@staticmethod
def resolve_products(root: models.ProductType, info, channel=None, **_kwargs):
- user = info.context.user
+ requestor = get_user_or_app_from_context(info.context)
if channel is None:
channel = get_default_channel_slug_or_graphql_error()
- qs = root.products.visible_to_user(user, channel)
+ qs = root.products.visible_to_user(requestor, channel)
return ChannelQsContext(qs=qs, channel_slug=channel)
@staticmethod
@@ -928,8 +931,8 @@ class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
@staticmethod
def resolve_products(root: ChannelContext[models.Collection], info, **kwargs):
- user = info.context.user
- qs = root.node.products.visible_to_user(user, root.channel_slug)
+ requestor = get_user_or_app_from_context(info.context)
+ qs = root.node.products.visible_to_user(requestor, root.channel_slug)
return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
@staticmethod
@@ -1014,14 +1017,12 @@ class Category(CountableDjangoObjectType):
@staticmethod
def resolve_products(root: models.Category, info, channel=None, **_kwargs):
requestor = get_user_or_app_from_context(info.context)
- requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
- requestor
- )
+ is_staff = requestor_is_staff_member_or_app(requestor)
tree = root.get_descendants(include_self=True)
- if channel is None and not requestor_has_access_to_all:
+ if channel is None and not is_staff:
channel = get_default_channel_slug_or_graphql_error()
qs = models.Product.objects.all()
- if not requestor_has_access_to_all:
+ if not is_staff:
qs = (
qs.published(channel)
.annotate_visible_in_listings(channel)
@@ -1029,7 +1030,7 @@ class Category(CountableDjangoObjectType):
visible_in_listings=False,
)
)
- if channel and requestor_has_access_to_all:
+ if channel and is_staff:
qs = qs.filter(channel_listings__channel__slug=channel)
qs = qs.filter(category__in=tree)
return ChannelQsContext(qs=qs, channel_slug=channel)
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index 0a73f1a9cb..77d98344be 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -1685,11 +1685,11 @@ QUERY_TRANSLATION_PAGE = """
@pytest.mark.parametrize(
- "is_published, perm_codenames, return_page",
+ "is_published, perm_codenames",
[
- (True, ["manage_translations"], True),
- (False, ["manage_translations"], False),
- (False, ["manage_translations", "manage_pages"], True),
+ (True, ["manage_translations"]),
+ (False, ["manage_translations"]),
+ (False, ["manage_translations", "manage_pages"]),
],
)
def test_translation_query_page(
@@ -1698,7 +1698,6 @@ def test_translation_query_page(
page_translation_fr,
is_published,
perm_codenames,
- return_page,
):
page.is_published = is_published
page.save()
@@ -1718,10 +1717,7 @@ def test_translation_query_page(
data = content["data"]["translation"]
assert data["title"] == page.title
assert data["translation"]["title"] == page_translation_fr.title
- if return_page:
- assert data["page"]["title"] == page.title
- else:
- assert not data["page"]
+ assert data["page"]["title"] == page.title
QUERY_TRANSLATION_SHIPPING_METHOD = """
diff --git a/saleor/page/models.py b/saleor/page/models.py
index 81a7fd435e..6795763d81 100644
--- a/saleor/page/models.py
+++ b/saleor/page/models.py
@@ -1,19 +1,13 @@
from django.db import models
from ..core.db.fields import SanitizedJSONField
-from ..core.models import ModelWithMetadata, PublishableModel, PublishedQuerySet
+from ..core.models import ModelWithMetadata, PublishableModel
from ..core.permissions import PagePermissions, PageTypePermissions
from ..core.sanitizers.editorjs_sanitizer import clean_editor_js
from ..core.utils.translations import TranslationProxy
from ..seo.models import SeoModel, SeoModelTranslation
-class PagePublishedQuerySet(PublishedQuerySet):
- @staticmethod
- def user_has_access_to_all(user):
- return user.is_active and user.has_perm(PagePermissions.MANAGE_PAGES)
-
-
class Page(ModelWithMetadata, SeoModel, PublishableModel):
slug = models.SlugField(unique=True, max_length=255)
title = models.CharField(max_length=250)
@@ -26,7 +20,6 @@ class Page(ModelWithMetadata, SeoModel, PublishableModel):
)
created = models.DateTimeField(auto_now_add=True)
- objects = PagePublishedQuerySet.as_manager()
translated = TranslationProxy()
class Meta:
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 6b010167f2..84bf54a8a3 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -31,6 +31,7 @@ from mptt.managers import TreeManager
from mptt.models import MPTTModel
from versatileimagefield.fields import PPOIField, VersatileImageField
+from ..account.utils import requestor_is_staff_member_or_app
from ..channel.models import Channel
from ..core.db.fields import SanitizedJSONField
from ..core.models import ModelWithMetadata, PublishableModel, SortableModel
@@ -50,6 +51,7 @@ if TYPE_CHECKING:
from prices import Money
from ..account.models import User
+ from ..app.models import App
class Category(MPTTModel, ModelWithMetadata, SeoModel):
@@ -161,17 +163,13 @@ class ProductsQueryset(models.QuerySet):
).values_list("variant", flat=True)
return published.filter(variants__in=query).distinct()
- def visible_to_user(self, user: "User", channel_slug: str):
- if self.user_has_access_to_all(user):
+ def visible_to_user(self, requestor: Union["User", "App"], channel_slug: str):
+ if requestor_is_staff_member_or_app(requestor):
if channel_slug:
return self.filter(channel_listings__channel__slug=str(channel_slug))
return self.all()
return self.published_with_variants(channel_slug)
- @staticmethod
- def user_has_access_to_all(user):
- return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
-
def annotate_publication_info(self, channel_slug: str):
return self.annotate_is_published(channel_slug).annotate_publication_date(
channel_slug
@@ -668,10 +666,6 @@ class CollectionProduct(SortableModel):
class CollectionsQueryset(models.QuerySet):
- @staticmethod
- def user_has_access_to_all(user):
- return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
-
def published(self, channel_slug: str):
today = datetime.date.today()
return self.filter(
@@ -682,8 +676,8 @@ class CollectionsQueryset(models.QuerySet):
channel_listings__is_published=True,
)
- def visible_to_user(self, user: "User", channel_slug: str):
- if self.user_has_access_to_all(user):
+ def visible_to_user(self, requestor: Union["User", "App"], channel_slug: str):
+ if requestor_is_staff_member_or_app(requestor):
if channel_slug:
return self.filter(channel_listings__channel__slug=str(channel_slug))
return self.all()
diff --git a/saleor/product/tests/test_product_availability.py b/saleor/product/tests/test_product_availability.py
index 5f9ead74ba..760513586b 100644
--- a/saleor/product/tests/test_product_availability.py
+++ b/saleor/product/tests/test_product_availability.py
@@ -269,14 +269,13 @@ def test_visible_to_customer_user(customer_user, product_list, channel_USD):
def test_visible_to_staff_user(
- customer_user, product_list, channel_USD, permission_manage_products
+ staff_user, product_list, channel_USD, permission_manage_products
):
product = product_list[0]
product.variants.all().delete()
- customer_user.user_permissions.add(permission_manage_products)
available_products = models.Product.objects.visible_to_user(
- customer_user, channel_USD.slug
+ staff_user, channel_USD.slug
)
assert available_products.count() == 3