Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' into feature/permission-groups
IKarbowiak597a83922751
diff --cc CHANGELOG.mdindex d3064798cc,7349f1616f..abb5b68be4--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -111,7 -95,9 +111,10 @@@ All notable, unreleased changes to thi- Add accountErrors to CreateToken as a required field - #5437 by @koradon- Raise GraphQLError if filter has not valid IDs - #5460 by @gabmartinez- Fix missing accountError when JSONWebTokenError is raised in CreateToken - #5465 by @koradon+- Remove service account access to staff related operations - #5485 by @IKarbowiak+ - Use AccountErrorCode.INVALID_CREDENTIALS instead of INVALID_PASSWORD - #5495 by @koradon+ - Add tests for pagination - #5468 by @koradon+ - Add job abstract model and interface - #5510 by @IKarbowiak## 2.9.0diff --cc saleor/account/migrations/0041_permissions_to_groups.pyindex b489adf363,0000000000..04711a18b0mode 100644,000000..100644--- a/saleor/account/migrations/0041_permissions_to_groups.py+++ b/saleor/account/migrations/0041_permissions_to_groups.py@@@ -1,79 -1,0 +1,79 @@@+from collections import namedtuple++from django.db import migrations+++def add_users_to_groups_based_on_users_permissions(apps, schema_editor):+ """Add every user to group with "user_permissions" if exists, else create new one.++ For each user, if the group with the exact scope of permissions exists,+ add the user to it, else create a new group with this scope of permissions+ and add the user to it.+ """+ User = apps.get_model("account", "User")+ Group = apps.get_model("auth", "Group")+ GroupData = namedtuple("GroupData", ["users", "group_name"])++ groups = Group.objects.all().prefetch_related("permissions")++ mapping = create_permissions_mapping(User, GroupData)+ for perms, group_data in mapping.items():+ group = get_group_with_given_permissions(perms, groups)+ users = group_data.users+ if group:+ group.user_set.add(*users)+ continue+ group = create_group_with_given_permissions(perms, group_data.group_name, Group)+ group.user_set.add(*users)+++def create_permissions_mapping(User, GroupData):+ """Create mapping permissions to users and potential new group name."""+ mapping = {}+ users = User.objects.filter(user_permissions__isnull=False).prefetch_related(+ "user_permissions"+ )+ for user in users:+ permissions = user.user_permissions.all()+ perm_pks = (perm.pk for perm in permissions)+ if perm_pks not in mapping:+ group_name = create_group_name(permissions)+ mapping[perm_pks] = GroupData({user.pk}, group_name)+ else:+ mapping[perm_pks].users.add(user.pk)+ user.user_permissions.clear()+ return mapping+++def create_group_name(permissions):+ """Create group name based on permissions."""+ formatted_names = [perm.name.rstrip(".").lower() for perm in permissions]+ group_name = ", ".join(formatted_names).capitalize()+ return group_name+++def get_group_with_given_permissions(permissions, groups):+ """Get group with given set of permissions."""+ for group in groups:+ group_perm_pks = {perm.pk for perm in group.permissions.all()}+ if group_perm_pks == set(permissions):+ return group+++def create_group_with_given_permissions(perm_pks, group_name, Group):+ """Create new group with given set of permissions."""+ group = Group.objects.create(name=group_name)+ group.permissions.add(*perm_pks)+ return group+++class Migration(migrations.Migration):++ dependencies = [- ("account", "0039_auto_20200221_0257"),++ ("account", "0040_auto_20200415_0443"),+ ]+ operations = [+ migrations.RunPython(+ add_users_to_groups_based_on_users_permissions, migrations.RunPython.noop+ ),+ ]diff --cc saleor/graphql/account/mutations/staff.pyindex 7eb8a69bae,0d8c1db04d..2c0384ac01--- a/saleor/graphql/account/mutations/staff.py+++ b/saleor/graphql/account/mutations/staff.py@@@ -11,9 -9,9 +11,9 @@@ from ....account import events as accoufrom ....account.emails import send_set_password_email_with_urlfrom ....account.error_codes import AccountErrorCodefrom ....account.thumbnails import create_user_avatar_thumbnails- from ....account.utils import get_random_avatar, remove_staff_member+ from ....account.utils import remove_staff_memberfrom ....checkout import AddressType-from ....core.permissions import AccountPermissions, get_permissions+from ....core.permissions import AccountPermissionsfrom ....core.utils.url import validate_storefront_urlfrom ...account.enums import AddressTypeEnumfrom ...account.types import Address, AddressInput, User@@@ -187,64 -167,22 +187,59 @@@ class StaffCreate(ModelMutation)try:validate_storefront_url(cleaned_input.get("redirect_url"))except ValidationError as error:- raise ValidationError(- {"redirect_url": error}, code=AccountErrorCode.INVALID- )+ error.code = AccountErrorCode.INVALID+ errors["redirect_url"].append(error)+ requestor = info.context.user# set is_staff to True to create a staff usercleaned_input["is_staff"] = True+ cls.clean_groups(requestor, cleaned_input, errors)+ cls.clean_is_active(cleaned_input, instance, info.context.user, errors)++ if errors:+ raise ValidationError(errors)- # clean and prepare permissions- if "permissions" in cleaned_input:- permissions = cleaned_input.pop("permissions")- cleaned_input["user_permissions"] = get_permissions(permissions)return cleaned_input+ @classmethod+ def clean_groups(cls, requestor: models.User, cleaned_input: dict, errors: dict):+ if cleaned_input.get("add_groups"):+ cls.ensure_requestor_can_manage_groups(+ requestor, cleaned_input, "add_groups", errors+ )++ @classmethod+ def ensure_requestor_can_manage_groups(+ cls, requestor: models.User, cleaned_input: dict, field: str, errors: dict+ ):+ """Check if requestor can manage group.++ Requestor cannot manage group with wider scope of permissions.+ """+ if requestor.is_superuser:+ return+ groups = cleaned_input[field]+ user_editable_groups = get_groups_which_user_can_manage(requestor)+ out_of_scope_groups = set(groups) - set(user_editable_groups)+ if out_of_scope_groups:+ # add error+ ids = [+ graphene.Node.to_global_id("Group", group.pk)+ for group in out_of_scope_groups+ ]+ error_msg = "You can't manage these groups."+ code = AccountErrorCode.OUT_OF_SCOPE_GROUP.value+ params = {"groups": ids}+ error = ValidationError(message=error_msg, code=code, params=params)+ errors[field].append(error)++ @classmethod+ def clean_is_active(cls, cleaned_input, instance, request, errors):+ pass+@classmethoddef save(cls, info, user, cleaned_input):- create_avatar = not user.avatar- if create_avatar:- user.avatar = get_random_avatar()user.save()- if create_avatar:- create_user_avatar_thumbnails.delay(user_id=user.pk)if cleaned_input.get("redirect_url"):send_set_password_email_with_url(redirect_url=cleaned_input.get("redirect_url"), user=user, staff=Truediff --cc saleor/graphql/schema.graphqlindex 601be39724,311d4b72ef..d3dae4910a--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@@ -3036,10 -3033,16 +3036,10 @@@ enum PermissionEnumMANAGE_CHECKOUTS}-type PermissionGroupAssignUsers {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- group: Group- accountErrors: [AccountError!]!-}-type PermissionGroupCreate {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes.")+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")group: Group- accountErrors: [AccountError!]!+ permissionGroupErrors: [PermissionGroupError!]!}input PermissionGroupCreateInput {@@@ -3049,8 -3050,9 +3049,8 @@@}type PermissionGroupDelete {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes.")+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- accountErrors: [AccountError!]!+ permissionGroupErrors: [PermissionGroupError!]!group: Group}@@@ -3086,18 -3074,16 +3086,18 @@@ input PermissionGroupSortingInputfield: PermissionGroupSortField!}-type PermissionGroupUnassignUsers {+type PermissionGroupUpdate {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes.")+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")group: Group- accountErrors: [AccountError!]!+ permissionGroupErrors: [PermissionGroupError!]!}-type PermissionGroupUpdate {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- group: Group- accountErrors: [AccountError!]!+input PermissionGroupUpdateInput {+ addPermissions: [PermissionEnum!]+ addUsers: [ID!]+ name: String+ removePermissions: [PermissionEnum!]+ removeUsers: [ID!]}type Plugin implements Node {@@@ -4342,14 -4328,14 +4342,14 @@@ input SiteDomainInput}type StaffBulkDelete {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes.")+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")count: Int!- accountErrors: [AccountError!]!+ staffErrors: [StaffError!]!}type StaffCreate {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes.")+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- accountErrors: [AccountError!]!+ staffErrors: [StaffError!]!user: User}@@@ -4364,8 -4350,8 +4364,8 @@@ input StaffCreateInput}type StaffDelete {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes.")+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- accountErrors: [AccountError!]!+ staffErrors: [StaffError!]!user: User}@@@ -4415,8 -4401,8 +4415,8 @@@ type StaffNotificationRecipientUpdate}type StaffUpdate {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes.")+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- accountErrors: [AccountError!]!+ staffErrors: [StaffError!]!user: User}diff --cc tests/api/test_account.pyindex 820f926955,c8634abf88..94f77b1d95--- a/tests/api/test_account.py+++ b/tests/api/test_account.py@@@ -18,9 -16,8 +18,9 @@@ from prices import Monefrom saleor.account import events as account_eventsfrom saleor.account.error_codes import AccountErrorCodefrom saleor.account.models import Address, User- from saleor.account.utils import create_jwt_token, get_random_avatar+ from saleor.account.utils import create_jwt_tokenfrom saleor.checkout import AddressType+from saleor.core.permissions import AccountPermissions, OrderPermissionsfrom saleor.graphql.account.mutations.base import INVALID_TOKENfrom saleor.graphql.account.mutations.staff import (CustomerDelete,@@@ -1583,134 -1385,12 +1583,126 @@@ def test_staff_create)content = get_graphql_content(response)data = content["data"]["staffCreate"]- assert data["errors"] == []+ assert data["staffErrors"] == []+ assert data["user"]["email"] == email+ assert data["user"]["isStaff"]+ assert data["user"]["isActive"]- assert re.match(- r"http://testserver/media/user-avatars/avatar\d+.*",- data["user"]["avatar"]["url"],- )++ expected_perms = {+ permission_manage_products.codename,+ permission_manage_users.codename,+ }+ permissions = data["user"]["userPermissions"]+ assert {perm["code"].lower() for perm in permissions} == expected_perms++ # deprecated, to remove in #5389+ permissions = data["user"]["permissions"]+ assert {perm["code"].lower() for perm in permissions} == expected_perms++ staff_user = User.objects.get(email=email)++ assert staff_user.is_staff++ groups = data["user"]["permissionGroups"]+ assert len(groups) == 1+ assert {perm["code"].lower() for perm in groups[0]["permissions"]} == expected_perms++ _send_set_password_email_mock.assert_called_once_with(+ staff_user.email, ANY, "dashboard/staff/set_password"+ )+++def test_staff_create_service_account_no_permission(+ service_account_api_client,+ staff_user,+ media_root,+ permission_group_manage_users,+ permission_manage_products,+ permission_manage_staff,+ permission_manage_users,+):+ group = permission_group_manage_users+ group.permissions.add(permission_manage_products)+ staff_user.user_permissions.add(permission_manage_products, permission_manage_users)+ email = "[email protected]"+ variables = {+ "email": email,+ "redirect_url": "https://www.example.com",+ "add_groups": [graphene.Node.to_global_id("Group", group.pk)],+ }++ response = service_account_api_client.post_graphql(+ STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ )++ assert_no_permission(response)+++@patch("saleor.account.emails._send_set_password_email")+def test_staff_create_out_of_scope_group(+ _send_set_password_email_mock,+ staff_api_client,+ superuser_api_client,+ media_root,+ permission_manage_staff,+ permission_manage_users,+ permission_group_manage_users,+):+ """Ensure user can't create staff with groups which are out of user scope.+ Ensure superuser pass restrictions.+ """+ group = permission_group_manage_users+ group2 = Group.objects.create(name="second group")+ group2.permissions.add(permission_manage_staff)+ email = "[email protected]"+ variables = {+ "email": email,+ "redirect_url": "https://www.example.com",+ "add_groups": [+ graphene.Node.to_global_id("Group", gr.pk) for gr in [group, group2]+ ],+ }++ # for staff user+ response = staff_api_client.post_graphql(+ STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffCreate"]+ errors = data["staffErrors"]+ assert not data["user"]+ assert len(errors) == 1++ expected_error = {+ "field": "addGroups",+ "code": AccountErrorCode.OUT_OF_SCOPE_GROUP.name,+ "permissions": None,+ "groups": [graphene.Node.to_global_id("Group", group.pk)],+ }++ assert errors[0] == expected_error++ _send_set_password_email_mock.assert_not_called()++ # for superuser+ response = superuser_api_client.post_graphql(STAFF_CREATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["staffCreate"]++ assert data["staffErrors"] == []assert data["user"]["email"] == emailassert data["user"]["isStaff"]assert data["user"]["isActive"]- assert re.match(- r"http://testserver/media/user-avatars/avatar\d+.*",- data["user"]["avatar"]["url"],- )+ expected_perms = {+ permission_manage_staff.codename,+ permission_manage_users.codename,+ }+ permissions = data["user"]["userPermissions"]+ assert {perm["code"].lower() for perm in permissions} == expected_perms++ # deprecated, to remove in #5389permissions = data["user"]["permissions"]- assert permissions[0]["code"] == "MANAGE_PRODUCTS"+ assert {perm["code"].lower() for perm in permissions} == expected_permsstaff_user = User.objects.get(email=email)@@@ -1736,446 -1401,106 +1728,433 @@@)-@patch("saleor.account.emails._send_set_user_password_email_with_url.delay")-def test_staff_create_send_password_with_url(- _send_set_user_password_email_with_url_mock,+@patch("saleor.account.emails._send_set_user_password_email_with_url.delay")+def test_staff_create_send_password_with_url(+ _send_set_user_password_email_with_url_mock,+ staff_api_client,+ media_root,+ permission_manage_staff,+):+ email = "[email protected]"+ variables = {"email": email, "redirect_url": "https://www.example.com"}++ response = staff_api_client.post_graphql(+ STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffCreate"]+ assert not data["staffErrors"]++ staff_user = User.objects.get(email=email)+ assert staff_user.is_staff++ token = default_token_generator.make_token(staff_user)+ _send_set_user_password_email_with_url_mock.assert_called_once_with(+ staff_user.email, ANY, token, "dashboard/staff/set_password"+ )+++def test_staff_create_without_send_password(+ staff_api_client, media_root, permission_manage_staff+):+ email = "[email protected]"+ variables = {"email": email}+ response = staff_api_client.post_graphql(+ STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffCreate"]+ assert not data["staffErrors"]+ User.objects.get(email=email)+++def test_staff_create_with_invalid_url(+ staff_api_client, media_root, permission_manage_staff+):+ email = "[email protected]"+ variables = {"email": email, "redirect_url": "invalid"}+ response = staff_api_client.post_graphql(+ STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffCreate"]+ assert data["staffErrors"][0] == {+ "field": "redirectUrl",+ "code": AccountErrorCode.INVALID.name,+ "permissions": None,+ "groups": None,+ }+ staff_user = User.objects.filter(email=email)+ assert not staff_user+++def test_staff_create_with_not_allowed_url(+ staff_api_client, media_root, permission_manage_staff+):+ email = "[email protected]"+ variables = {"email": email, "redirect_url": "https://www.fake.com"}+ response = staff_api_client.post_graphql(+ STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffCreate"]+ assert data["staffErrors"][0] == {+ "field": "redirectUrl",+ "code": AccountErrorCode.INVALID.name,+ "permissions": None,+ "groups": None,+ }+ staff_user = User.objects.filter(email=email)+ assert not staff_user+++STAFF_UPDATE_MUTATIONS = """+ mutation UpdateStaff(+ $id: ID!, $input: StaffUpdateInput!) {+ staffUpdate(+ id: $id,+ input: $input) {+ staffErrors {+ field+ code+ message+ permissions+ groups+ }+ user {+ userPermissions {+ code+ }+ permissions {+ code+ }+ permissionGroups {+ name+ }+ isActive+ }+ }+ }+"""+++def test_staff_update(staff_api_client, permission_manage_staff, media_root):+ query = STAFF_UPDATE_MUTATIONS+ staff_user = User.objects.create(email="[email protected]", is_staff=True)+ id = graphene.Node.to_global_id("User", staff_user.id)+ variables = {"id": id, "input": {"isActive": False}}++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffUpdate"]+ assert data["staffErrors"] == []+ assert data["user"]["userPermissions"] == []+ assert not data["user"]["isActive"]+ # deprecated, to remove in #5389+ assert data["user"]["permissions"] == []+++def test_staff_update_service_account_no_permission(+ service_account_api_client, permission_manage_staff, media_root+):+ query = STAFF_UPDATE_MUTATIONS+ staff_user = User.objects.create(email="[email protected]", is_staff=True)+ id = graphene.Node.to_global_id("User", staff_user.id)+ variables = {"id": id, "input": {"isActive": False}}++ response = service_account_api_client.post_graphql(+ query, variables, permissions=[permission_manage_staff]+ )++ assert_no_permission(response)+++def test_staff_update_groups_and_permissions(+ staff_api_client,+ media_root,+ permission_manage_staff,+ permission_manage_users,+ permission_manage_orders,+ permission_manage_products,+):+ query = STAFF_UPDATE_MUTATIONS+ groups = Group.objects.bulk_create(+ [Group(name="manage users"), Group(name="manage orders"), Group(name="empty")]+ )+ group1, group2, group3 = groups+ group1.permissions.add(permission_manage_users)+ group2.permissions.add(permission_manage_orders)++ staff_user = User.objects.create(email="[email protected]", is_staff=True)+ staff_user.groups.add(group1)++ id = graphene.Node.to_global_id("User", staff_user.id)+ variables = {+ "id": id,+ "input": {+ "addGroups": [+ graphene.Node.to_global_id("Group", gr.pk) for gr in [group2, group3]+ ],+ "removeGroups": [graphene.Node.to_global_id("Group", group1.pk)],+ },+ }++ staff_api_client.user.user_permissions.add(+ permission_manage_users, permission_manage_orders, permission_manage_products+ )++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffUpdate"]+ assert data["staffErrors"] == []+ assert {perm["code"].lower() for perm in data["user"]["userPermissions"]} == {+ permission_manage_orders.codename,+ }+ assert {group["name"] for group in data["user"]["permissionGroups"]} == {+ group2.name,+ group3.name,+ }+ # deprecated, to remove in #5389+ assert {perm["code"].lower() for perm in data["user"]["permissions"]} == {+ permission_manage_orders.codename,+ }+++def test_staff_update_out_of_scope_user(+ staff_api_client,+ superuser_api_client,+ permission_manage_staff,+ permission_manage_orders,+ media_root,+):+ """Ensure that staff user cannot update user with wider scope of permission.+ Ensure superuser pass restrictions.+ """+ query = STAFF_UPDATE_MUTATIONS+ staff_user = User.objects.create(email="[email protected]", is_staff=True)+ staff_user.user_permissions.add(permission_manage_orders)+ id = graphene.Node.to_global_id("User", staff_user.id)+ variables = {"id": id, "input": {"isActive": False}}++ # for staff user+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffUpdate"]+ assert not data["user"]+ assert len(data["staffErrors"]) == 1+ assert data["staffErrors"][0]["field"] == "id"+ assert data["staffErrors"][0]["code"] == AccountErrorCode.OUT_OF_SCOPE_USER.name++ # for superuser+ response = superuser_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["staffUpdate"]+ assert data["user"]["email"] == staff_user.email+ assert data["user"]["isActive"] is False+ assert not data["staffErrors"]+++def test_staff_update_out_of_scope_groups(+ staff_api_client,+ superuser_api_client,+ permission_manage_staff,+ media_root,+ permission_manage_users,+ permission_manage_orders,+ permission_manage_products,+):+ """Ensure that staff user cannot add to groups which permission scope is wider+ than user's scope.+ Ensure superuser pass restrictions.+ """+ query = STAFF_UPDATE_MUTATIONS++ groups = Group.objects.bulk_create(+ [+ Group(name="manage users"),+ Group(name="manage orders"),+ Group(name="manage products"),+ ]+ )+ group1, group2, group3 = groups++ group1.permissions.add(permission_manage_users)+ group2.permissions.add(permission_manage_orders)+ group3.permissions.add(permission_manage_products)++ staff_user = User.objects.create(email="[email protected]", is_staff=True)+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ id = graphene.Node.to_global_id("User", staff_user.id)+ variables = {+ "id": id,+ "input": {+ "isActive": False,+ "addGroups": [+ graphene.Node.to_global_id("Group", gr.pk) for gr in [group1, group2]+ ],+ "removeGroups": [graphene.Node.to_global_id("Group", group3.pk)],+ },+ }++ # for staff user+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_staff]+ )+ content = get_graphql_content(response)+ data = content["data"]["staffUpdate"]+ errors = data["staffErrors"]+ assert not data["user"]+ assert len(errors) == 2++ expected_errors = [+ {+ "field": "addGroups",+ "code": AccountErrorCode.OUT_OF_SCOPE_GROUP.name,+ "permissions": None,+ "groups": [graphene.Node.to_global_id("Group", group1.pk)],+ },+ {+ "field": "removeGroups",+ "code": AccountErrorCode.OUT_OF_SCOPE_GROUP.name,+ "permissions": None,+ "groups": [graphene.Node.to_global_id("Group", group3.pk)],+ },+ ]+ for error in errors:+ error.pop("message")+ assert error in expected_errors++ # for superuser+ response = superuser_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["staffUpdate"]+ errors = data["staffErrors"]+ assert not errors+ assert data["user"]["email"] == staff_user.email+ assert {group["name"] for group in data["user"]["permissionGroups"]} == {+ group1.name,+ group2.name,+ }+++def test_staff_update_cannot_add_and_remove(staff_api_client,- media_root,permission_manage_staff,+ media_root,+ permission_manage_orders,+ permission_manage_users,):- email = "[email protected]"- variables = {"email": email, "redirect_url": "https://www.example.com"}+ query = STAFF_UPDATE_MUTATIONS- response = staff_api_client.post_graphql(- STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ groups = Group.objects.bulk_create(+ [Group(name="manage users"), Group(name="manage orders"), Group(name="empty")])- content = get_graphql_content(response)- data = content["data"]["staffCreate"]- assert not data["errors"]+ group1, group2, group3 = groups- staff_user = User.objects.get(email=email)- assert staff_user.is_staff+ group1.permissions.add(permission_manage_users)+ group2.permissions.add(permission_manage_orders)- token = default_token_generator.make_token(staff_user)- _send_set_user_password_email_with_url_mock.assert_called_once_with(- staff_user.email, ANY, token, "dashboard/staff/set_password"+ staff_user = User.objects.create(email="[email protected]", is_staff=True)+ staff_api_client.user.user_permissions.add(+ permission_manage_orders, permission_manage_users)+ id = graphene.Node.to_global_id("User", staff_user.id)+ variables = {+ "id": id,+ "input": {+ "addGroups": [+ graphene.Node.to_global_id("Group", gr.pk) for gr in [group1, group2]+ ],+ "removeGroups": [+ graphene.Node.to_global_id("Group", gr.pk)+ for gr in [group1, group2, group3]+ ],+ },+ }--def test_staff_create_without_send_password(- staff_api_client, media_root, permission_manage_staff-):- email = "[email protected]"- variables = {"email": email}response = staff_api_client.post_graphql(- STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ query, variables, permissions=[permission_manage_staff])content = get_graphql_content(response)- data = content["data"]["staffCreate"]- assert not data["errors"]- User.objects.get(email=email)+ data = content["data"]["staffUpdate"]+ errors = data["staffErrors"]++ assert len(errors) == 1+ assert errors[0]["field"] is None+ assert errors[0]["code"] == AccountErrorCode.CANNOT_ADD_AND_REMOVE.name+ assert set(errors[0]["groups"]) == {+ graphene.Node.to_global_id("Group", gr.pk) for gr in [group1, group2]+ }+ assert errors[0]["permissions"] is None- @patch("saleor.graphql.account.mutations.staff.get_random_avatar")-def test_staff_create_with_invalid_url(- staff_api_client, media_root, permission_manage_staff+def test_staff_update_doesnt_change_existing_avatar(- mock_get_random_avatar,- staff_api_client,- permission_manage_staff,- media_root,- staff_users,++ staff_api_client, permission_manage_staff, media_root, staff_users,):- email = "[email protected]"- variables = {"email": email, "redirect_url": "invalid"}+ query = STAFF_UPDATE_MUTATIONS++ mock_file = MagicMock(spec=File)+ mock_file.name = "image.jpg"- mock_get_random_avatar.return_value = mock_file++ staff_user, staff_user1, _ = staff_users+- # Create random avatar- staff_user1.avatar = get_random_avatar()- staff_user1.save()- original_path = staff_user1.avatar.path-+ id = graphene.Node.to_global_id("User", staff_user1.id)+ variables = {"id": id, "input": {"isActive": False}}response = staff_api_client.post_graphql(- STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ query, variables, permissions=[permission_manage_staff])content = get_graphql_content(response)- data = content["data"]["staffCreate"]- assert data["accountErrors"][0] == {- "field": "redirectUrl",- "code": AccountErrorCode.INVALID.name,- }- staff_user = User.objects.filter(email=email)- assert not staff_user+ data = content["data"]["staffUpdate"]+ assert data["staffErrors"] == []+- # Make sure that random avatar isn't recreated when there is one already set.- mock_get_random_avatar.assert_not_called()+ staff_user.refresh_from_db()- assert staff_user1.avatar.path == original_path++ assert not staff_user.avatar-def test_staff_create_with_not_allowed_url(- staff_api_client, media_root, permission_manage_staff+def test_staff_update_deactivate_with_manage_staff_left_not_manageable_perms(+ staff_api_client,+ superuser_api_client,+ staff_users,+ permission_manage_users,+ permission_manage_staff,+ permission_manage_orders,+ media_root,):- email = "[email protected]"- variables = {"email": email, "redirect_url": "https://www.fake.com"}- response = staff_api_client.post_graphql(- STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ """Ensure that staff user can't and superuser can deactivate user where some+ permissions will be not manageable.+ """+ query = STAFF_UPDATE_MUTATIONS+ groups = Group.objects.bulk_create(+ [+ Group(name="manage users"),+ Group(name="manage staff"),+ Group(name="manage orders"),+ ])- content = get_graphql_content(response)- data = content["data"]["staffCreate"]- assert data["accountErrors"][0] == {- "field": "redirectUrl",- "code": AccountErrorCode.INVALID.name,- }- staff_user = User.objects.filter(email=email)- assert not staff_user+ group1, group2, group3 = groups+ group1.permissions.add(permission_manage_users)+ group2.permissions.add(permission_manage_staff)+ group3.permissions.add(permission_manage_orders)-def test_staff_update(staff_api_client, permission_manage_staff, media_root):- query = """- mutation UpdateStaff(- $id: ID!, $permissions: [PermissionEnum], $is_active: Boolean) {- staffUpdate(- id: $id,- input: {permissions: $permissions, isActive: $is_active}) {- errors {- field- message- }- user {- permissions {- code- }- isActive- }- }- }- """- staff_user = User.objects.create(email="[email protected]", is_staff=True)- id = graphene.Node.to_global_id("User", staff_user.id)- variables = {"id": id, "permissions": [], "is_active": False}+ staff_user, staff_user1, staff_user2 = staff_users+ group1.user_set.add(staff_user1)+ group2.user_set.add(staff_user2, staff_user1)+ group3.user_set.add(staff_user2)++ staff_user.user_permissions.add(permission_manage_users, permission_manage_orders)++ id = graphene.Node.to_global_id("User", staff_user1.id)+ variables = {"id": id, "input": {"isActive": False}}+ # for staff userresponse = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_staff])diff --cc tests/api/test_account_permission_group.pyindex 731c46cccd,c960245c04..779ea7e393--- a/tests/api/test_account_permission_group.py+++ b/tests/api/test_account_permission_group.py@@@ -108,19 -75,13 +108,19 @@@ def test_permission_group_create_servicvariables = {"input": {"name": "New permission group",-- "permissions": [++ "addPermissions": [AccountPermissions.MANAGE_USERS.name,AccountPermissions.MANAGE_SERVICE_ACCOUNTS.name,],- "users": [++ "addUsers": [+ graphene.Node.to_global_id("User", user.id) for user in staff_users+ ],}}- response = staff_api_client.post_graphql(query, variables)+ response = service_account_api_client.post_graphql(+ query, variables, permissions=(permission_manage_staff,)+ )+assert_no_permission(response)