Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add possibility to attach user to checkout by App or staff user (#7754)
Maciej Korycinski8b1190712cfb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 655074171a..1a2a4636a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -142,8 +142,10 @@ All notable, unreleased changes to this project will be documented in this file.- Add `page_type_id` when it's possible for `AttributeValue` translations webhook. - #7825 by @fowczarek- Optimize available quantity loader. - #7802 by @fowczarek- Configure a periodic task for removing empty allocations - #7885 by @fowczarek-- Add webhooks for stock changes: `PRODUCT_VARIANT_OUT_OF_STOCK` and `PRODUCT_VARIANT_BACK_IN_STOCK` - #7590 by @mstrumeck+- Allow impersonating user by an app/staff - #7754 by @korycins:+ - Add `customerId` to `checkoutCustomerAttach` mutation+ - Add new permision `IMPERSONATE_USER`### Breaking- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysockidiff --git a/saleor/account/migrations/0055_alter_user_options.py b/saleor/account/migrations/0055_alter_user_options.pynew file mode 100644index 0000000000..c473e607c6--- /dev/null+++ b/saleor/account/migrations/0055_alter_user_options.py@@ -0,0 +1,43 @@+# Generated by Django 3.2.6 on 2021-08-25 10:29+from django.core.management.sql import emit_post_migrate_signal+from django.db import migrations+++def assing_permissions(apps, schema_editor):+ # force post signal as permissions are created in post migrate signals+ # related Django issue https://code.djangoproject.com/ticket/23422+ emit_post_migrate_signal(2, False, "default")+ Group = apps.get_model("auth", "Group")+ Permission = apps.get_model("auth", "Permission")++ impersonate_user = Permission.objects.filter(+ codename="impersonate_user", content_type__app_label="account"+ ).first()+ manage_users = Permission.objects.filter(+ codename="manage_users", content_type__app_label="account"+ )++ for group in Group.objects.filter(permissions__in=manage_users).iterator():+ group.permissions.add(impersonate_user)+++class Migration(migrations.Migration):++ dependencies = [+ ("account", "0054_alter_user_language_code"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="user",+ options={+ "ordering": ("email",),+ "permissions": (+ ("manage_users", "Manage customers."),+ ("manage_staff", "Manage staff."),+ ("impersonate_user", "Impersonate user."),+ ),+ },+ ),+ migrations.RunPython(assing_permissions, migrations.RunPython.noop),+ ]diff --git a/saleor/account/models.py b/saleor/account/models.pyindex 2ecfcb2bd8..0d085c5dc0 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -180,6 +180,7 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):permissions = ((AccountPermissions.MANAGE_USERS.codename, "Manage customers."),(AccountPermissions.MANAGE_STAFF.codename, "Manage staff."),+ (AccountPermissions.IMPERSONATE_USER.codename, "Impersonate user."),)indexes = [*ModelWithMetadata.Meta.indexes,diff --git a/saleor/core/permissions.py b/saleor/core/permissions.pyindex a077d0cdc6..9bc252fc45 100644--- a/saleor/core/permissions.py+++ b/saleor/core/permissions.py@@ -13,6 +13,7 @@ class BasePermissionEnum(Enum):class AccountPermissions(BasePermissionEnum):MANAGE_USERS = "account.manage_users"MANAGE_STAFF = "account.manage_staff"+ IMPERSONATE_USER = "account.impersonate_user"class AppPermission(BasePermissionEnum):diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 6672e46983..0d26e59c02 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Unionimport graphenefrom django.conf import settings+from django.contrib.auth.models import AnonymousUserfrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db.models import Q@@ -31,6 +32,7 @@ from ...checkout.utils import ()from ...core import analyticsfrom ...core.exceptions import InsufficientStock, PermissionDenied, ProductNotPublished+from ...core.permissions import AccountPermissionsfrom ...core.tracing import traced_atomic_transactionfrom ...core.transactions import transaction_with_commit_on_errorsfrom ...order import models as order_models@@ -59,6 +61,7 @@ from ..core.validators import (from ..order.types import Orderfrom ..product.types import ProductVariantfrom ..shipping.types import ShippingMethod+from ..utils import get_user_or_app_from_contextfrom ..warehouse.types import Warehousefrom .types import Checkout, CheckoutLinefrom .utils import prepare_insufficient_stock_checkout_validation_error@@ -621,6 +624,13 @@ class CheckoutCustomerAttach(BaseMutation):f"The ID of the checkout. {DEPRECATED_IN_3X_INPUT} Use token instead."),)+ customer_id = graphene.ID(+ required=False,+ description=(+ "ID of customer to attach to checkout. Can be used to attach customer "+ "to checkout by staff or app. Requires IMPERSONATE_USER permission."+ ),+ )token = UUID(description="Checkout token.", required=False)class Meta:@@ -630,7 +640,7 @@ class CheckoutCustomerAttach(BaseMutation):@classmethoddef check_permissions(cls, context):- return context.user.is_authenticated+ return context.user.is_authenticated or context.app@classmethoddef perform_mutation(@@ -651,11 +661,19 @@ class CheckoutCustomerAttach(BaseMutation):# Raise error when trying to attach a user to a checkout# that is already owned by another user.- if checkout.user:+ if checkout.user_id:raise PermissionDenied()- checkout.user = info.context.user- checkout.email = info.context.user.email+ if customer_id:+ requestor = get_user_or_app_from_context(info.context)+ if not requestor.has_perm(AccountPermissions.IMPERSONATE_USER):+ raise PermissionDenied()+ customer = cls.get_node_or_error(info, customer_id, only_type="User")+ else:+ customer = info.context.user++ checkout.user = customer+ checkout.email = customer.emailcheckout.save(update_fields=["email", "user", "last_change"])info.context.plugins.checkout_updated(checkout)@@ -681,7 +699,7 @@ class CheckoutCustomerDetach(BaseMutation):@classmethoddef check_permissions(cls, context):- return context.user.is_authenticated+ return context.user.is_authenticated or context.app@classmethoddef perform_mutation(cls, _root, info, checkout_id=None, token=None):@@ -698,9 +716,11 @@ class CheckoutCustomerDetach(BaseMutation):info, checkout_id or token, only_type=Checkout, field="checkout_id")- # Raise error if the current user doesn't own the checkout of the given ID.- if checkout.user and checkout.user != info.context.user:- raise PermissionDenied()+ requestor = get_user_or_app_from_context(info.context)+ if not requestor.has_perm(AccountPermissions.IMPERSONATE_USER):+ # Raise error if the current user doesn't own the checkout of the given ID.+ if checkout.user and checkout.user != info.context.user:+ raise PermissionDenied()checkout.user = Nonecheckout.save(update_fields=["user", "last_change"])@@ -1312,6 +1332,15 @@ class CheckoutComplete(BaseMutation):checkout_info = fetch_checkout_info(checkout, lines, info.context.discounts, manager)++ requestor = get_user_or_app_from_context(info.context)+ if requestor.has_perm(AccountPermissions.IMPERSONATE_USER):+ # Allow impersonating user and process a checkout by using user details+ # assigned to checkout.+ customer = checkout.user or AnonymousUser()+ else:+ customer = info.context.user+order, action_required, action_data = complete_checkout(manager=manager,checkout_info=checkout_info,@@ -1319,7 +1348,7 @@ class CheckoutComplete(BaseMutation):payment_data=data.get("payment_data", {}),store_source=store_source,discounts=info.context.discounts,- user=info.context.user,+ user=customer,app=info.context.app,site_settings=info.context.site.settings,tracking_code=tracking_code,@@ -1376,12 +1405,6 @@ class CheckoutAddPromoCode(BaseMutation):lines = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)- if info.context.user and checkout.user == info.context.user:- # reassign user from request to make sure that we will take into account- # that user can have granted staff permissions from external resources.- # Which is required to determine if user has access to 'staff discount'- checkout_info.user = info.context.user-add_promo_code_to_checkout(manager,checkout_info,diff --git a/saleor/graphql/checkout/resolvers.py b/saleor/graphql/checkout/resolvers.pyindex 00058f003a..ae33c6878a 100644--- a/saleor/graphql/checkout/resolvers.py+++ b/saleor/graphql/checkout/resolvers.py@@ -1,5 +1,5 @@from ...checkout import models-from ...core.permissions import CheckoutPermissions+from ...core.permissions import AccountPermissions, CheckoutPermissionsfrom ...core.tracing import traced_resolverfrom ..utils import get_user_or_app_from_context@@ -35,7 +35,10 @@ def resolve_checkout(info, token):# resolve checkout for staff userrequester = get_user_or_app_from_context(info.context)- if requester.has_perm(CheckoutPermissions.MANAGE_CHECKOUTS):++ has_manage_checkout = requester.has_perm(CheckoutPermissions.MANAGE_CHECKOUTS)+ has_impersonate_user = requester.has_perm(AccountPermissions.IMPERSONATE_USER)+ if has_manage_checkout or has_impersonate_user:return checkoutreturn Nonediff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex ca64bd39cc..bf89db53fd 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -1620,6 +1620,75 @@ def test_checkout_customer_attach(assert checkout.email == customer_user.email+def test_checkout_customer_attach_by_app(+ app_api_client, checkout_with_item, customer_user, permission_impersonate_user+):+ checkout = checkout_with_item+ checkout.email = "[email protected]"+ checkout.save()+ assert checkout.user is None++ query = """+ mutation checkoutCustomerAttach($token: UUID, $customerId: ID) {+ checkoutCustomerAttach(token: $token, customerId: $customerId) {+ checkout {+ token+ }+ errors {+ field+ message+ }+ }+ }+ """+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)+ variables = {"token": checkout.token, "customerId": customer_id}++ # Mutation should succeed for authenticated customer+ response = app_api_client.post_graphql(+ query, variables, permissions=[permission_impersonate_user]+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutCustomerAttach"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.user == customer_user+ assert checkout.email == customer_user.email+++def test_checkout_customer_attach_by_app_without_permission(+ app_api_client, checkout_with_item, customer_user+):+ checkout = checkout_with_item+ checkout.email = "[email protected]"+ checkout.save()+ assert checkout.user is None++ query = """+ mutation checkoutCustomerAttach($token: UUID, $customerId: ID) {+ checkoutCustomerAttach(token: $token, customerId: $customerId) {+ checkout {+ token+ }+ errors {+ field+ message+ }+ }+ }+ """+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)+ variables = {"token": checkout.token, "customerId": customer_id}++ # Mutation should succeed for authenticated customer+ response = app_api_client.post_graphql(+ query,+ variables,+ )++ assert_no_permission(response)++def test_checkout_customer_attach_user_to_checkout_with_user(user_api_client, customer_user, user_checkout, address):@@ -1699,6 +1768,43 @@ def test_checkout_customer_detach(user_api_client, checkout_with_item, customer_assert_no_permission(response)+def test_checkout_customer_detach_by_app(+ app_api_client, checkout_with_item, customer_user, permission_impersonate_user+):+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.save(update_fields=["user"])++ variables = {"token": checkout.token}++ # Mutation should succeed if the user owns this checkout.+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_CUSTOMER_DETACH,+ variables,+ permissions=[permission_impersonate_user],+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutCustomerDetach"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.user is None+++def test_checkout_customer_detach_by_app_without_permissions(+ app_api_client, checkout_with_item, customer_user+):+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.save(update_fields=["user"])++ variables = {"token": checkout.token}++ # Mutation should succeed if the user owns this checkout.+ response = app_api_client.post_graphql(MUTATION_CHECKOUT_CUSTOMER_DETACH, variables)++ assert_no_permission(response)++MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE = """mutation checkoutShippingAddressUpdate($token: UUID, $shippingAddress: AddressInput!) {diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex 5af047176c..e83b51b81a 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -4,6 +4,7 @@ from unittest.mock import ANY, patchimport grapheneimport pytest+from django.contrib.auth.models import AnonymousUserfrom django.db.models.aggregates import Sumfrom ....checkout import calculations@@ -273,6 +274,134 @@ def test_checkout_complete(order_confirmed_mock.assert_called_once_with(order)+@patch("saleor.graphql.checkout.mutations.complete_checkout")+def test_checkout_complete_by_app(+ mocked_complete_checkout,+ app_api_client,+ checkout_with_item,+ customer_user,+ permission_impersonate_user,+ payment_dummy,+ address,+ shipping_method,+):+ mocked_complete_checkout.return_value = (None, True, {})+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ redirect_url = "https://www.example.com"+ variables = {"token": checkout.token, "redirectUrl": redirect_url}++ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_COMPLETE,+ variables,+ permissions=[permission_impersonate_user],+ check_no_permissions=False,+ )++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert not data["errors"]++ mocked_complete_checkout.assert_called_once_with(+ manager=ANY,+ checkout_info=ANY,+ lines=ANY,+ payment_data=ANY,+ store_source=ANY,+ discounts=ANY,+ user=checkout.user,+ app=ANY,+ site_settings=ANY,+ tracking_code=ANY,+ redirect_url=ANY,+ )+++@patch("saleor.graphql.checkout.mutations.complete_checkout")+def test_checkout_complete_by_app_with_missing_permission(+ mocked_complete_checkout,+ app_api_client,+ checkout_with_item,+ customer_user,+ permission_manage_users,+ payment_dummy,+ address,+ shipping_method,+):+ mocked_complete_checkout.return_value = (None, True, {})+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ redirect_url = "https://www.example.com"+ variables = {"token": checkout.token, "redirectUrl": redirect_url}++ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_COMPLETE,+ variables,+ permissions=[permission_manage_users],+ check_no_permissions=False,+ )++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert not data["errors"]++ mocked_complete_checkout.assert_called_once_with(+ manager=ANY,+ checkout_info=ANY,+ lines=ANY,+ payment_data=ANY,+ store_source=ANY,+ discounts=ANY,+ user=AnonymousUser(),+ app=ANY,+ site_settings=ANY,+ tracking_code=ANY,+ redirect_url=ANY,+ )++def test_checkout_complete_with_variant_without_price(site_settings,user_api_client,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 9392e2fbd3..72be86ea5c 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3783,7 +3783,7 @@ type Mutation {checkoutBillingAddressUpdate(billingAddress: AddressInput!, checkoutId: ID, token: UUID): CheckoutBillingAddressUpdatecheckoutComplete(checkoutId: ID, paymentData: JSONString, redirectUrl: String, storeSource: Boolean = false, token: UUID): CheckoutCompletecheckoutCreate(input: CheckoutCreateInput!): CheckoutCreate- checkoutCustomerAttach(checkoutId: ID, token: UUID): CheckoutCustomerAttach+ checkoutCustomerAttach(checkoutId: ID, customerId: ID, token: UUID): CheckoutCustomerAttachcheckoutCustomerDetach(checkoutId: ID, token: UUID): CheckoutCustomerDetachcheckoutEmailUpdate(checkoutId: ID, email: String!, token: UUID): CheckoutEmailUpdatecheckoutLineDelete(checkoutId: ID, lineId: ID, token: UUID): CheckoutLineDelete@@ -4833,6 +4833,7 @@ type Permission {enum PermissionEnum {MANAGE_USERSMANAGE_STAFF+ IMPERSONATE_USERMANAGE_APPSMANAGE_CHANNELSMANAGE_DISCOUNTSdiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex c6f7550a85..36c63aa304 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -3432,6 +3432,11 @@ def permission_manage_users():return Permission.objects.get(codename="manage_users")+def permission_impersonate_user():+ return Permission.objects.get(codename="impersonate_user")++@pytest.fixturedef permission_manage_settings():return Permission.objects.get(codename="manage_settings")