Skip to content

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

Update code after code review

Mateusz Grzyb59627352a0cf
diff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.py
index 7d4e52ac91..768dafa095 100644
--- a/saleor/graphql/meta/mutations.py
+++ b/saleor/graphql/meta/mutations.py
@@ -16,10 +16,7 @@ from ..core.mutations import BaseMutation
from ..core.types.common import MetadataError
from ..core.utils import from_global_id_or_error
from .extra_methods import MODEL_EXTRA_METHODS, MODEL_EXTRA_PREFETCH
-from .permissions import (
- PRIVATE_META_PERMISSION_MAP,
- PUBLIC_META_MUTATION_PERMISSION_MAP,
-)
+from .permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_PERMISSION_MAP
from .types import ObjectWithMetadata
@@ -168,7 +165,7 @@ class MetadataInput(graphene.InputObjectType):
class UpdateMetadata(BaseMetadataMutation):
class Meta:
description = "Updates metadata of an object."
- permission_map = PUBLIC_META_MUTATION_PERMISSION_MAP
+ permission_map = PUBLIC_META_PERMISSION_MAP
error_type_class = MetadataError
error_type_field = "metadata_errors"
@@ -195,7 +192,7 @@ class UpdateMetadata(BaseMetadataMutation):
class DeleteMetadata(BaseMetadataMutation):
class Meta:
description = "Delete metadata of an object."
- permission_map = PUBLIC_META_MUTATION_PERMISSION_MAP
+ permission_map = PUBLIC_META_PERMISSION_MAP
error_type_class = MetadataError
error_type_field = "metadata_errors"
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.py
index daf4c340a7..6e6e84ac77 100644
--- a/saleor/graphql/meta/permissions.py
+++ b/saleor/graphql/meta/permissions.py
@@ -20,7 +20,7 @@ from ...core.permissions import (
ProductTypePermissions,
ShippingPermissions,
)
-from ...payment.models import Payment
+from ...payment.utils import payment_has_user
def no_permissions(_info, _object_pk: Any) -> List[None]:
@@ -107,10 +107,9 @@ def discount_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:
def public_payment_permissions(info, payment_pk: int) -> List[BasePermissionEnum]:
context_user = info.context.user
- payment = Payment.objects.get(pk=payment_pk)
if info.context.app is not None or info.context.user.is_staff:
return [PaymentPermissions.HANDLE_PAYMENTS]
- if payment.get_user() == context_user:
+ if payment_has_user(payment_pk, context_user):
return []
raise PermissionDenied()
@@ -125,7 +124,7 @@ def gift_card_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:
return [GiftcardPermissions.MANAGE_GIFT_CARD]
-PUBLIC_META_MUTATION_PERMISSION_MAP = {
+PUBLIC_META_PERMISSION_MAP = {
"App": app_permissions,
"Attribute": attribute_permissions,
"Category": product_permissions,
@@ -152,32 +151,6 @@ PUBLIC_META_MUTATION_PERMISSION_MAP = {
"Warehouse": product_permissions,
}
-PUBLIC_META_QUERY_PERMISSION_MAP = {
- "App": no_permissions,
- "Attribute": no_permissions,
- "Category": no_permissions,
- "Checkout": no_permissions,
- "Collection": no_permissions,
- "DigitalContent": no_permissions,
- "Fulfillment": no_permissions,
- "GiftCard": no_permissions,
- "Invoice": no_permissions,
- "Menu": no_permissions,
- "MenuItem": no_permissions,
- "Order": no_permissions,
- "Page": no_permissions,
- "PageType": no_permissions,
- "Payment": public_payment_permissions,
- "Product": no_permissions,
- "ProductType": no_permissions,
- "ProductVariant": no_permissions,
- "Sale": no_permissions,
- "ShippingMethod": no_permissions,
- "ShippingZone": no_permissions,
- "User": no_permissions,
- "Voucher": no_permissions,
- "Warehouse": no_permissions,
-}
PRIVATE_META_PERMISSION_MAP = {
"App": app_permissions,
diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.py
index e3d23ae24a..e47b1a35cc 100644
--- a/saleor/graphql/meta/resolvers.py
+++ b/saleor/graphql/meta/resolvers.py
@@ -15,7 +15,7 @@ from ...product import models as product_models
from ...shipping import models as shipping_models
from ...warehouse import models as warehouse_models
from ..utils import get_user_or_app_from_context
-from .permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_QUERY_PERMISSION_MAP
+from .permissions import PRIVATE_META_PERMISSION_MAP
def resolve_object_with_metadata_type(instance: ModelWithMetadata):
@@ -66,16 +66,14 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):
return MODEL_TO_TYPE_MAP.get(instance.__class__, None)
-def _resolve_metadata(metadata: dict):
+def resolve_metadata(metadata: dict):
return sorted(
[{"key": k, "value": v} for k, v in metadata.items()],
key=itemgetter("key"),
)
-def _resolve_metadata_with_permissions(
- permission_map, root: ModelWithMetadata, metadata: dict, info
-):
+def resolve_private_metadata(root: ModelWithMetadata, info):
item_type = resolve_object_with_metadata_type(root)
if not item_type:
raise NotImplementedError(
@@ -83,29 +81,17 @@ def _resolve_metadata_with_permissions(
"Make sure that model exists inside MODEL_TO_TYPE_MAP."
)
- get_required_permission = permission_map[item_type.__name__]
+ get_required_permission = PRIVATE_META_PERMISSION_MAP[item_type.__name__]
if not get_required_permission:
raise PermissionDenied()
required_permission = get_required_permission(info, root.pk)
if not required_permission:
- return _resolve_metadata(metadata)
+ raise PermissionDenied()
requester = get_user_or_app_from_context(info.context)
if not requester.has_perms(required_permission):
raise PermissionDenied()
- return _resolve_metadata(metadata)
-
-
-def resolve_metadata(root: ModelWithMetadata, info):
- return _resolve_metadata_with_permissions(
- PUBLIC_META_QUERY_PERMISSION_MAP, root, root.metadata, info
- )
-
-
-def resolve_private_metadata(root: ModelWithMetadata, info):
- return _resolve_metadata_with_permissions(
- PRIVATE_META_PERMISSION_MAP, root, root.private_metadata, info
- )
+ return resolve_metadata(root.private_metadata)
diff --git a/saleor/graphql/meta/tests/__init__.py b/saleor/graphql/meta/tests/__init__.py
index c024aadaf9..e69de29bb2 100644
--- a/saleor/graphql/meta/tests/__init__.py
+++ b/saleor/graphql/meta/tests/__init__.py
@@ -1,23 +0,0 @@
-import pytest
-
-pytest_plugins = ["saleor.plugins.webhook.tests.test_payment_webhook"]
-
-PRIVATE_KEY = "private_key"
-PRIVATE_VALUE = "private_vale"
-
-PUBLIC_KEY = "key"
-PUBLIC_VALUE = "value"
-
-
-def payment_with_public_metadata(payment):
- payment.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
- payment.save(update_fields=["metadata"])
- return payment
-
-
-def payment_with_private_metadata(payment):
- payment.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
- payment.save(update_fields=["private_metadata"])
- return payment
diff --git a/saleor/graphql/meta/tests/conftest.py b/saleor/graphql/meta/tests/conftest.py
new file mode 100644
index 0000000000..6059789a30
--- /dev/null
+++ b/saleor/graphql/meta/tests/conftest.py
@@ -0,0 +1,21 @@
+import pytest
+
+PRIVATE_KEY = "private_key"
+PRIVATE_VALUE = "private_vale"
+
+PUBLIC_KEY = "key"
+PUBLIC_VALUE = "value"
+
+
+def payment_with_public_metadata(payment):
+ payment.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ payment.save(update_fields=["metadata"])
+ return payment
+
+
+def payment_with_private_metadata(payment):
+ payment.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ payment.save(update_fields=["private_metadata"])
+ return payment
diff --git a/saleor/graphql/meta/tests/test_meta_mutations.py b/saleor/graphql/meta/tests/test_meta_mutations.py
index 365efeaa83..552dccd408 100644
--- a/saleor/graphql/meta/tests/test_meta_mutations.py
+++ b/saleor/graphql/meta/tests/test_meta_mutations.py
@@ -9,11 +9,9 @@ from django.core.exceptions import ValidationError
from ....core.error_codes import MetadataErrorCode
from ....core.models import ModelWithMetadata
from ....invoice.models import Invoice
+from ....payment.utils import payment_has_user
from ...tests.utils import assert_no_permission, get_graphql_content
-pytest_plugins = ["saleor.graphql.meta.tests"]
-
-
PRIVATE_KEY = "private_key"
PRIVATE_VALUE = "private_vale"
@@ -740,7 +738,7 @@ def test_update_public_metadata_for_payment_by_logged_user(
):
# given
payment_with_public_metadata.order.user = user_api_client.user
- payment_with_public_metadata.save()
+ payment_with_public_metadata.order.save()
payment_id = graphene.Node.to_global_id("Payment", payment_with_public_metadata.pk)
# when
@@ -761,7 +759,7 @@ def test_update_public_metadata_for_payment_by_different_logged_user(
user2_api_client, payment_with_public_metadata
):
# given
- assert payment_with_public_metadata.get_user() != user2_api_client.user
+ assert not payment_has_user(payment_with_public_metadata.pk, user2_api_client.user)
payment_id = graphene.Node.to_global_id("Payment", payment_with_public_metadata.pk)
variables = {
"id": payment_id,
diff --git a/saleor/graphql/meta/tests/test_meta_queries.py b/saleor/graphql/meta/tests/test_meta_queries.py
index fdfe5786fb..a9a983963d 100644
--- a/saleor/graphql/meta/tests/test_meta_queries.py
+++ b/saleor/graphql/meta/tests/test_meta_queries.py
@@ -6,6 +6,7 @@ from django.http import HttpResponse
from saleor.core.models import ModelWithMetadata
from saleor.payment.models import Payment
+from saleor.payment.utils import payment_has_user
from ...tests.fixtures import ApiClient
from ...tests.utils import assert_no_permission, get_graphql_content
@@ -16,8 +17,6 @@ PRIVATE_VALUE = "private_vale"
PUBLIC_KEY = "key"
PUBLIC_VALUE = "value"
-pytest_plugins = ["saleor.graphql.meta.tests"]
-
def execute_query(
query_str: str,
@@ -1064,7 +1063,7 @@ def test_query_public_meta_for_payment_as_customer(
user_api_client, payment_with_public_metadata, permission_manage_orders
):
# given
- assert user_api_client.user == payment_with_public_metadata.get_user()
+ assert payment_has_user(payment_with_public_metadata.pk, user_api_client.user)
# when
response = execute_query_public_metadata_for_payment(
@@ -1083,8 +1082,7 @@ def test_query_public_meta_for_payment_as_another_customer(
permission_manage_orders,
):
# given
- assert user2_api_client.user != payment_with_public_metadata.get_user()
-
+ assert not payment_has_user(payment_with_public_metadata.pk, user2_api_client.user)
# when
response = execute_query_public_metadata_for_payment(
user2_api_client,
@@ -1102,9 +1100,6 @@ def test_query_public_meta_for_payment_as_staff_with_permission(
permission_manage_orders,
permission_manage_payments,
):
- # given
- ...
-
# when
response = execute_query_public_metadata_for_payment(
staff_api_client,
@@ -1119,9 +1114,6 @@ def test_query_public_meta_for_payment_as_staff_with_permission(
def test_query_public_meta_for_payment_as_staff_without_permission(
staff_api_client, payment_with_public_metadata
):
- # given
- ...
-
# when
response = execute_query_public_metadata_for_payment(
staff_api_client, payment_with_public_metadata
@@ -1137,9 +1129,6 @@ def test_query_public_meta_for_payment_as_app_with_permission(
permission_manage_orders,
permission_manage_payments,
):
- # given
- ...
-
# when
response = execute_query_public_metadata_for_payment(
app_api_client,
@@ -1154,9 +1143,6 @@ def test_query_public_meta_for_payment_as_app_with_permission(
def test_query_public_meta_for_payment_as_app_without_permission(
app_api_client, payment_with_public_metadata
):
- # given
- ...
-
# when
response = execute_query_public_metadata_for_payment(
app_api_client, payment_with_public_metadata
@@ -2684,9 +2670,6 @@ def test_query_private_meta_for_payment_as_staff_with_permission(
permission_manage_orders,
permission_manage_payments,
):
- # given
- ...
-
# when
response = execute_query_private_metadata_for_payment(
staff_api_client,
@@ -2701,9 +2684,6 @@ def test_query_private_meta_for_payment_as_staff_with_permission(
def test_query_private_meta_for_payment_as_staff_without_permission(
staff_api_client, payment_with_private_metadata
):
- # given
- ...
-
# when
response = execute_query_private_metadata_for_payment(
staff_api_client, payment_with_private_metadata
@@ -2719,9 +2699,6 @@ def test_query_private_meta_for_payment_as_app_with_permission(
permission_manage_orders,
permission_manage_payments,
):
- # given
- ...
-
# when
response = execute_query_private_metadata_for_payment(
app_api_client,
@@ -2736,9 +2713,6 @@ def test_query_private_meta_for_payment_as_app_with_permission(
def test_query_private_meta_for_payment_as_app_without_permission(
app_api_client, payment_with_private_metadata
):
- # given
- ...
-
# when
response = execute_query_private_metadata_for_payment(
app_api_client, payment_with_private_metadata
diff --git a/saleor/graphql/meta/types.py b/saleor/graphql/meta/types.py
index 8ccbe616e4..16cba9d967 100644
--- a/saleor/graphql/meta/types.py
+++ b/saleor/graphql/meta/types.py
@@ -32,8 +32,8 @@ class ObjectWithMetadata(graphene.Interface):
)
@staticmethod
- def resolve_metadata(root: ModelWithMetadata, info):
- return resolve_metadata(root, info)
+ def resolve_metadata(root: ModelWithMetadata, _info):
+ return resolve_metadata(root.metadata)
@staticmethod
def resolve_private_metadata(root: ModelWithMetadata, info):
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index dbfeba4f33..aac7c747f1 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -1,11 +1,15 @@
import graphene
from graphene import relay
+from ...core.exceptions import PermissionDenied
from ...core.tracing import traced_resolver
from ...payment import models
from ..core.connection import CountableDjangoObjectType
from ..core.types import Money
+from ..meta.permissions import public_payment_permissions
+from ..meta.resolvers import resolve_metadata
from ..meta.types import ObjectWithMetadata
+from ..utils import get_user_or_app_from_context
from .enums import OrderAction, PaymentChargeStatusEnum
@@ -162,6 +166,14 @@ class Payment(CountableDjangoObjectType):
return None
return CreditCard(**data)
+ @staticmethod
+ def resolve_metadata(root: models.Payment, info):
+ permissions = public_payment_permissions(info, root.pk)
+ requester = get_user_or_app_from_context(info.context)
+ if not requester.has_perms(permissions):
+ raise PermissionDenied()
+ return resolve_metadata(root.metadata)
+
class PaymentInitialized(graphene.ObjectType):
class Meta:
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 3e515c4730..415047e91e 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -162,12 +162,6 @@ class Payment(ModelWithMetadata):
"""Retrieve the maximum capture possible."""
return self.total - self.captured_amount
- def get_user(self):
- if (order := self.order) is not None and (user := order.user) is not None:
- return user
- if (checkout := self.checkout) is not None:
- return checkout.user
-
@property
def is_authorized(self):
return any(
diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.py
index 6c0582f93c..06dbd370e5 100644
--- a/saleor/payment/tests/test_payment.py
+++ b/saleor/payment/tests/test_payment.py
@@ -2,6 +2,7 @@ from decimal import Decimal
from unittest.mock import Mock, patch
import pytest
+from django.contrib.auth.models import AnonymousUser
from ...checkout.calculations import checkout_total
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -18,6 +19,7 @@ from ..utils import (
create_payment_information,
create_transaction,
is_currency_supported,
+ payment_has_user,
update_payment,
validate_gateway_response,
)
@@ -556,23 +558,21 @@ def test_update_payment(gateway_response, payment_txn_captured):
assert payment.payment_method_type == gateway_response.payment_method_info.type
-def test_get_user_from_order(payment, customer_user2):
+def test_payment_has_user_from_order(payment, customer_user2):
# given
assert payment.checkout is None
- assert payment.order.user != customer_user2
payment.order.user = customer_user2
- payment.save()
+ payment.order.save()
# when
- payment_user = payment.get_user()
+ has_user = payment_has_user(payment.pk, customer_user2)
# then
- assert payment_user == customer_user2
+ assert has_user
-def test_get_user_from_checkout(payment, checkout, customer_user2):
+def test_payment_has_user_from_checkout(payment, checkout, customer_user2):
# given
- assert checkout.user != customer_user2
checkout.user = customer_user2
checkout.save()
payment.checkout = checkout
@@ -580,17 +580,17 @@ def test_get_user_from_checkout(payment, checkout, customer_user2):
payment.save()
# when
- payment_user = payment.get_user()
+ has_user = payment_has_user(payment.pk, customer_user2)
# then
- assert payment_user == customer_user2
+ assert has_user
@pytest.mark.parametrize(
["not_none", "none"],
[(["order"], ["checkout"]), (["checkout"], ["order"]), ([], ["checkout", "order"])],
)
-def test_get_none_user(payment, checkout, not_none, none):
+def test_payment_does_not_have_user(payment, checkout, not_none, none, customer_user2):
# given
for attr in none:
setattr(payment, attr, None)
@@ -604,7 +604,18 @@ def test_get_none_user(payment, checkout, not_none, none):
assert getattr(payment, attr).user is None
# when
- payment_user = payment.get_user()
+ has_user = payment_has_user(payment.pk, customer_user2)
+
+ # then
+ assert not has_user
+
+
+def test_payment_has_user_anonymous_user(payment):
+ # given
+ user = AnonymousUser()
+
+ # when
+ has_user = payment_has_user(payment.pk, user)
# then
- assert payment_user is None
+ assert not has_user
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index c456a92531..d138ca2508 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -5,7 +5,9 @@ from typing import TYPE_CHECKING, Dict, List, Optional
import graphene
from babel.numbers import get_currency_precision
+from django.contrib.auth.models import AnonymousUser
from django.core.serializers.json import DjangoJSONEncoder
+from django.db.models import Q
from ..account.models import User
from ..checkout.models import Checkout
@@ -427,3 +429,14 @@ def price_to_minor_unit(value: Decimal, currency: str):
number_places = Decimal("10.0") ** precision
value_without_comma = value * number_places
return str(value_without_comma.quantize(Decimal("1")))
+
+
+def payment_has_user(payment_pk: int, user) -> bool:
+ if user == AnonymousUser():
+ return False
+ return (
+ Payment.objects.filter(
+ (Q(order__user=user) | Q(checkout__user=user)) & Q(pk=payment_pk)
+ ).first()
+ is not None
+ )