Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' of github.com:mirumee/saleor into SALEOR-2542-error-decode-id
Damian Wa61a0bfba8ee
diff --cc CHANGELOG.mdindex aec5c1f16d,79492b683d..d2ab7176ac--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -42,7 -46,7 +46,8 @@@ All notable, unreleased changes to thi- Fix dataloader for fetching checkout info - #7084 by @IKarbowiak- Update also draft order line total price after getting the unit price from plugin - #7080 by @IKarbowiak- Fix failing product tasks when instances are removed - #7092 by @IKarbowiak- - Catch invalid ID in query and raise ValidationError - #7114 by @d-wysocki++- Catch invalid object ID and raise ValidationError - #7114 by @d-wysocki+ - Update GraphQL endpoint to only match exactly `/graphql/` without trailing characters - #7117 by @IKarbowiak### Breaking- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysockidiff --cc saleor/graphql/attribute/utils.pyindex 82f709658c,6002d9ff4e..f6a10fcbe5--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@@ -5,8 -5,10 +5,9 @@@ from typing import TYPE_CHECKING, Dictimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db.models import Q+ from django.template.defaultfilters import truncatecharsfrom django.utils.text import slugifyfrom graphql.error import GraphQLError-from graphql_relay import from_global_idfrom ...attribute import AttributeEntityType, AttributeInputType, AttributeTypefrom ...attribute import models as attribute_models@@@ -115,15 -118,12 +118,9 @@@ class AttributeAssignmentMixin@classmethoddef _resolve_attribute_global_id(cls, error_class, global_id: str) -> int:"""Resolve an Attribute global ID into an internal ID (int)."""- # TODO : remove type- graphene_type, internal_id = from_global_id(global_id) # type: str, str- if graphene_type != "Attribute":- raise ValidationError(- f"Must receive an Attribute id, got {graphene_type}.",- code=error_class.INVALID.value,- )+ graphene_type, internal_id = from_global_id_or_error(- global_id- ) # type: str, str- if graphene_type != "Attribute":- raise ValidationError(- f"Must receive an Attribute id, got {graphene_type}.",- code=error_class.INVALID.value,- )++ global_id, only_type="Attribute"++ )if not internal_id.isnumeric():raise ValidationError(f"An invalid ID value was passed: {global_id}",diff --cc saleor/graphql/checkout/mutations.pyindex b63a98b102,bc4b7576bc..e910f0d3dc--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@@ -625,7 -625,7 +625,9 @@@ class CheckoutShippingAddressUpdate(Bas@classmethoddef perform_mutation(cls, _root, info, checkout_id, shipping_address):- _type, pk = from_global_id_or_error(checkout_id, Checkout, field="checkout_id")- pk = from_global_id_strict_type(checkout_id, Checkout, field="checkout_id")++ _type, pk = from_global_id_or_error(++ checkout_id, only_type=Checkout, field="checkout_id"++ )try:checkout = models.Checkout.objects.prefetch_related(@@@ -892,8 -892,8 +894,8 @@@ class CheckoutComplete(BaseMutation)field="checkout_id",)except ValidationError as e:- checkout_token = from_global_id_strict_type(- checkout_id, Checkout, field="checkout_id"+ _type, checkout_token = from_global_id_or_error(- checkout_id, Checkout, field="checkout_id"++ checkout_id, only_type=Checkout, field="checkout_id")order = order_models.Order.objects.get_by_checkout_token(checkout_token)diff --cc saleor/graphql/core/mutations.pyindex f7d45027f5,74efc5186f..74fe4b168e--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@@ -156,16 -156,16 +156,12 @@@ class BaseMutation(graphene.Mutation)return Nonetry:-- if only_type is not None:- _type, pk = from_global_id_or_error(node_id, only_type, field=field)- pk = from_global_id_strict_type(node_id, only_type, field=field)-- else:-- # FIXME: warn when supplied only_type is None?- only_type, pk = from_global_id_or_error(node_id)- only_type, pk = graphene.Node.from_global_id(node_id)++ object_type, pk = from_global_id_or_error(node_id, only_type, field=field)-- if isinstance(only_type, str):-- only_type = info.schema.get_type(only_type).graphene_type++ if isinstance(object_type, str):++ object_type = info.schema.get_type(object_type).graphene_type-- node = cls.get_node_by_pk(info, graphene_type=only_type, pk=pk, qs=qs)++ node = cls.get_node_by_pk(info, graphene_type=object_type, pk=pk, qs=qs)except (AssertionError, GraphQLError) as e:raise ValidationError({field: ValidationError(str(e), code="graphql_error")}diff --cc saleor/graphql/core/tests/test_graphql.pyindex 8da153a74d,95c201e5ec..742ef2ff6d--- a/saleor/graphql/core/tests/test_graphql.py+++ b/saleor/graphql/core/tests/test_graphql.py@@@ -285,13 -283,3 +285,35 @@@ def test_filter_by_query_param(qs)q_objects |= Q(**{q: test_kwargs[q]})# FIXME: django 1.11 fails on called_once_with(q_objects)qs.filter.call_count == 1+++def test_from_global_id_or_error(product):+ invalid_id = "invalid"+ message = f"Couldn't resolve id: {invalid_id}."++ with pytest.raises(ValidationError) as error:+ from_global_id_or_error(invalid_id)++ assert error.value.error_dict["id"][0].message == message++++++def test_from_global_id_or_error_wth_invalid_type(product):++ product_id = graphene.Node.to_global_id("Product", product.id)++ message = "Must receive a ProductVariant id."++++ with pytest.raises(ValidationError) as error:++ from_global_id_or_error(product_id, "ProductVariant")++++ assert error.value.error_dict["id"][0].message == message++++++def test_from_global_id_or_error_wth_type(product):++ expected_product_type = str(Product)++ expected_product_id = graphene.Node.to_global_id(expected_product_type, product.id)++++ product_type, product_id = from_global_id_or_error(++ expected_product_id, expected_product_type++ )++++ assert product_id == str(product.id)++ assert product_type == expected_product_typediff --cc saleor/graphql/core/utils/__init__.pyindex 91349c88d0,201edcf482..cb8599ad63--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@@ -97,24 -119,3 +97,24 @@@ def validate_required_string_field(cleaelse:raise ValidationError(f"{field_name.capitalize()} is required.")return cleaned_input+++def from_global_id_or_error(+ id: str, only_type: Union[ObjectType, str] = None, field: str = "id"+):- """Resolve id from global or raise ValidationError.++ """Resolve database ID from global ID or raise ValidationError.+- Optional validate object type.++ Optionally validate the object type, if `only_type` is provided.+ """+ try:+ _type, _id = graphene.Node.from_global_id(id)+ except (binascii.Error, UnicodeDecodeError):+ raise ValidationError(+ {field: ValidationError(f"Couldn't resolve id: {id}.", code="not_found")}+ )++ if only_type and str(_type) != str(only_type):+ raise ValidationError(+ {field: ValidationError(f"Must receive a {only_type} id.", code="invalid")}+ )+ return _type, _iddiff --cc saleor/graphql/product/mutations/products.pyindex 1dcadfe9ac,f6aa65e309..d5a9cf6af6--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@@ -1202,9 -1208,7 +1208,9 @@@ class ProductTypeDelete(ModelDeleteMuta@classmethoddef perform_mutation(cls, _root, info, **data):node_id = data.get("id")- product_type_pk = from_global_id_strict_type(node_id, ProductType, field="pk")+ _type, product_type_pk = from_global_id_or_error(- node_id, ProductType, field="pk"++ node_id, only_type=ProductType, field="pk"+ )variants_pks = models.Product.objects.filter(product_type__pk=product_type_pk).values_list("variants__pk", flat=True)@@@ -1481,7 -1485,7 +1487,7 @@@ class ProductVariantReorder(BaseMutatio@classmethoddef perform_mutation(cls, _root, info, product_id, moves):- _type, pk = from_global_id_or_error(product_id, only_type=Product, field="id")- pk = from_global_id_strict_type(product_id, only_type=Product, field="id")++ _type, pk = from_global_id_or_error(product_id, only_type=Product)try:product = models.Product.objects.prefetched_for_webhook().get(pk=pk)diff --cc saleor/graphql/product/resolvers.pyindex 6362ec175d,1f1b11c481..16e4bb9d0e--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@@ -116,9 -115,7 +116,10 @@@ def resolve_product_variantsqs = models.ProductVariant.objects.filter(product__id__in=visible_products)if ids:- db_ids = [get_database_id(info, node_id, "ProductVariant") for node_id in ids]+ db_ids = [- from_global_id_or_error(node_id, "ProductVariant")[1] for node_id in ids++ from_global_id_or_error(node_id, only_type="ProductVariant")[1]++ for node_id in ids+ ]qs = qs.filter(pk__in=db_ids)return ChannelQsContext(qs=qs, channel_slug=channel_slug)diff --cc saleor/graphql/product/types/products.pyindex 12992917a7,e37d6d025d..4128a8b0ca--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@@ -746,7 -749,7 +746,7 @@@ class Product(ChannelContextTypeWithMet@staticmethoddef resolve_media_by_id(root: ChannelContext[models.Product], info, id):- _type, pk = from_global_id_or_error(id, "ProductMedia")- pk = get_database_id(info, id, ProductMedia)++ _type, pk = from_global_id_or_error(id, only_type="ProductMedia")try:return root.node.media.get(pk=pk)except models.ProductMedia.DoesNotExist:@@@ -754,7 -757,7 +754,7 @@@@staticmethoddef resolve_image_by_id(root: ChannelContext[models.Product], info, id):- _type, pk = from_global_id_or_error(id, "ProductMedia")- pk = get_database_id(info, id, ProductMedia)++ _type, pk = from_global_id_or_error(id, only_type="ProductMedia")try:return root.node.media.get(pk=pk)except models.ProductMedia.DoesNotExist:diff --cc saleor/graphql/translations/mutations.pyindex c5e3aaa63d,daf5ff6a24..afd4277e76--- a/saleor/graphql/translations/mutations.py+++ b/saleor/graphql/translations/mutations.py@@@ -91,7 -95,7 +95,7 @@@ class ProductTranslate(BaseTranslateMut{"id": ValidationError("This field is required", code="required")})- _type, product_pk = from_global_id_or_error(data["id"], Product, field="id")- product_pk = from_global_id_strict_type(data["id"], Product, field="id")++ _type, product_pk = from_global_id_or_error(data["id"], only_type=Product)product = product_models.Product.objects.get(pk=product_pk)product.translations.update_or_create(language_code=data["language_code"], defaults=data["input"]@@@ -145,9 -149,7 +149,9 @@@ class ProductVariantTranslate(BaseTrans{"id": ValidationError("This field is required", code="required")})- variant_pk = from_global_id_strict_type(data["id"], ProductVariant, field="id")+ _type, variant_pk = from_global_id_or_error(- data["id"], ProductVariant, field="id"++ data["id"], only_type=ProductVariant+ )variant = product_models.ProductVariant.objects.prefetched_for_webhook().get(pk=variant_pk)