Skip to content

Fixed 'Delete operation is forbidden for current area' error. #31318

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

vovayatsyuk
Copy link
Member

@vovayatsyuk vovayatsyuk commented Dec 17, 2020

Description

This error happens if the customer address doesn't pass validation during account creation.

Fixed Issues (if relevant)

  1. Fixes Delete operation is forbidden for current area when creating account from checkout success page. #9736
  2. Fixes Delete operation is forbidden for current area #8631
  3. Fixes Create Account not working properly for Guest User : Delete operation is forbidden for current area (Enterprise Magento ver. 2.1.0) #5699

Manual testing scenarios

  1. Open Magento/Customer/Model/AccountManagement.php and find the following lines:
        try {
            foreach ($customerAddresses as $address) {
                if (!$this->isAddressAllowedForWebsite($address, $customer->getStoreId())) {
                    continue;
                }
                if ($address->getId()) {
                    $newAddress = clone $address;
                    $newAddress->setId(null);
                    $newAddress->setCustomerId($customer->getId());
                    $this->addressRepository->save($newAddress);
                } else {
                    $address->setCustomerId($customer->getId());
                    $this->addressRepository->save($address);
                }
            }
            $this->customerRegistry->remove($customer->getId());
        } catch (InputException $e) {
            $this->customerRepository->delete($customer);
            throw $e;
        }
  1. Change them as shown below (Emulate InputException from addressRepository->save method):
        try {
            throw new InputException(__("Test"));                     // <-- this line was added
            foreach ($customerAddresses as $address) {
                if (!$this->isAddressAllowedForWebsite($address, $customer->getStoreId())) {
                    continue;
                }
                if ($address->getId()) {
                    $newAddress = clone $address;
                    $newAddress->setId(null);
                    $newAddress->setCustomerId($customer->getId());
                    $this->addressRepository->save($newAddress);
                } else {
                    $address->setCustomerId($customer->getId());
                    $this->addressRepository->save($address);
                }
            }
            $this->customerRegistry->remove($customer->getId());
        } catch (InputException $e) {
            $this->customerRepository->delete($customer);
            throw $e;
        }
  1. Add product to cart as a guest and navigate to multishipping checkout.
  2. Press "Create account"
  3. Fill the form and submit it.
  4. An error "Test" will be shown.
  5. If you will try to register one more time, you'll be informed that this email is already taken.
  6. You can also check the customer's grid in the magento backend and see that your customer was just created.

Expected Behavior

The client should see the "Test" error message every time he submits the form.

Actual Behavior

The client sees the "Delete operation is forbidden for current area" error message for first time. Next submits tells that his email is already in use.

Contribution checklist (*)

  • Pull request has a meaningful description of its purpose
  • All commits are accompanied by meaningful commit messages
  • All new or changed code is covered with unit/integration tests (if applicable)
  • All automated tests passed successfully (all builds are green)

Resolved issues:

  1. resolves [Issue] Fixed 'Delete operation is forbidden for current area' error. #31540: Fixed 'Delete operation is forbidden for current area' error.

This error happens if customer address doesn't pass validation during account creation.
@m2-assistant
Copy link

m2-assistant bot commented Dec 17, 2020

Hi @vovayatsyuk. Thank you for your contribution
Here is some useful tips how you can test your changes using Magento test environment.
Add the comment under your pull request to deploy test or vanilla Magento instance:

  • @magento give me test instance - deploy test instance based on PR changes
  • @magento give me 2.4-develop instance - deploy vanilla Magento instance

❗ Automated tests can be triggered manually with an appropriate comment:

  • @magento run all tests - run or re-run all required tests against the PR changes
  • @magento run <test-build(s)> - run or re-run specific test build(s)
    For example: @magento run Unit Tests

<test-build(s)> is a comma-separated list of build names. Allowed build names are:

  1. Database Compare
  2. Functional Tests CE
  3. Functional Tests EE,
  4. Functional Tests B2B
  5. Integration Tests
  6. Magento Health Index
  7. Sample Data Tests CE
  8. Sample Data Tests EE
  9. Sample Data Tests B2B
  10. Static Tests
  11. Unit Tests
  12. WebAPI Tests

You can find more information about the builds here

ℹ️ Please run only needed test builds instead of all when developing. Please run all test builds before sending your PR for review.

For more details, please, review the Magento Contributor Guide documentation.

⚠️ According to the Magento Contribution requirements, all Pull Requests must go through the Community Contributions Triage process. Community Contributions Triage is a public meeting.

🕙 You can find the schedule on the Magento Community Calendar page.

📞 The triage of Pull Requests happens in the queue order. If you want to speed up the delivery of your contribution, please join the Community Contributions Triage session to discuss the appropriate ticket.

🎥 You can find the recording of the previous Community Contributions Triage on the Magento Youtube Channel

✏️ Feel free to post questions/proposals/feedback related to the Community Contributions Triage process to the corresponding Slack Channel

Copy link
Contributor

@rogyar rogyar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @vovayatsyuk. The fix totally makes sense for me. Thank you.

Could I ask you to cover this case with an integration test that will trigger the InputException, please?

Thanks

@gabrieldagama gabrieldagama added Priority: P2 A defect with this priority could have functionality issues which are not to expectations. Severity: S2 Major restrictions or short-term circumventions are required until a fix is available. labels Dec 17, 2020
@engcom-Charlie
Copy link
Contributor

Hi @vovayatsyuk, could you please cover your changes by integration test?
Thank you.

@engcom-Charlie engcom-Charlie self-assigned this Dec 21, 2020
@vovayatsyuk
Copy link
Member Author

There is a test that already checks account creation with an exception during address save.

The only part that is missing in the test is to check if delete wasn't blocked in beforeDelete.

I don't know how to do that since $this->customerRepository is a mocked object and no validation is made for this mock.

My zero testing knowledge doesn't allow me to understand how to do this properly. Can you help?

@vovayatsyuk
Copy link
Member Author

I think I got it. I should add a test to dev/tests/integration/testsuite/Magento/Customer/Model/AccountManagementTest.php

The test checks if email is still available after failed try with incorrect address.
@engcom-Charlie
Copy link
Contributor

@magento run all tests

@engcom-Charlie
Copy link
Contributor

Hello, @vovayatsyuk looks like the introduced test falls.
Could you please take a look?
Thank you.

@vovayatsyuk
Copy link
Member Author

vovayatsyuk commented Dec 22, 2020

Can you please advise? When I'm running it as a single test is works fine:

../../../vendor/bin/phpunit --filter testCreateAccountWithInvalidAddress testsuite/Magento/Customer/Model/AccountManagementTest.php

But when I run whole class:

../../../vendor/bin/phpunit testsuite/Magento/Customer/Model/AccountManagementTest.php

It fails. Do you have any idea?

@engcom-Charlie
Copy link
Contributor

@vovayatsyuk you can check the previous test cases in the test class looks like they affect your test case.
Please let me know if you will have any questions.

@vovayatsyuk
Copy link
Member Author

Okay. When I run all tests my fix is not working and I still get a Delete operation is forbidden for current area exception.

I've updated the test. It still doesn't work, but at least it shows the real issue of why it's failed.

@engcom-Charlie
Copy link
Contributor

It is necessary to make that all tests passed successfully.
Could you do it?
Thank you.

@vovayatsyuk
Copy link
Member Author

I found the reason for the failure (https://github.com/magento/magento2/blob/2.4-develop/dev/tests/integration/testsuite/Magento/Customer/_files/customer_rollback.php#L24):

$registry->register('isSecureArea', false);

p.s. There are 398 other test files that use this code too. I believe all of these lines should be removed if test doesn't change it back to unregistered state.

@engcom-Charlie
Copy link
Contributor

@magento run Integration Tests

@vovayatsyuk
Copy link
Member Author

I didn't fix it yet.

The easiest way to fix the test is to unregister 'isSecureArea' flag before setting it. But I think it's not correct because the real problem is registered flags from previous tests.

However, if you want me to add ->unregister I'll do that.

@engcom-Charlie
Copy link
Contributor

I found the reason for the failure (https://github.com/magento/magento2/blob/2.4-develop/dev/tests/integration/testsuite/Magento/Customer/_files/customer_rollback.php#L24):

$registry->register('isSecureArea', false);

p.s. There are 398 other test files that use this code too. I believe all of these lines should be removed if test doesn't change it back to unregistered state.

Could you try to fix it? Maybe create the right fixture and use it instead of the old one whenever it needs.

@ishakhsuvarov
Copy link
Contributor

@magento run all tests

@magento-automated-testing
Copy link

The requested builds are added to the queue. You should be able to see them here within a few minutes. Please re-request them if they don't show in a reasonable amount of time.

@ihor-sviziev
Copy link
Contributor

Hi @vovayatsyuk,
I see all linked issues are already closed as non-reproducible or already fixed. Could you please update us, does the problem still there?

@vovayatsyuk
Copy link
Member Author

Yes, the problem is still here.

@ihor-sviziev
Copy link
Contributor

@magento run all tests

@magento-automated-testing
Copy link

The requested builds are added to the queue. You should be able to see them here within a few minutes. Please re-request them if they don't show in a reasonable amount of time.

ihor-sviziev

This comment was marked as duplicate.

Copy link
Contributor

@ihor-sviziev ihor-sviziev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @vovayatsyuk,
Please provide more context on when this issue might happen. I see all linked issues already closed.

In the past, I had a similar issue on frontend when the customer was automatically created during the checkout process (using a custom checkout).
But then I I analyzed deeper and it seems like address validation can be simply skipped by adding the following flag ignore_validation_flag to the customer model:

/**
* Set ignore_validation_flag for reset password flow to skip unnecessary address and customer validation
*
* @param Customer $customer
* @return void
*/
private function setIgnoreValidationFlag($customer)
{
$customer->setData('ignore_validation_flag', true);
}

if (!$customer->getData('ignore_validation_flag')) {
/** @var \Magento\Customer\Model\Address $address */
foreach ($customer->getAddresses() as $address) {
if ($address->getData('_deleted')) {
if ($address->getId() == $defaultBillingId) {
$customer->setData('default_billing', null);
}
if ($address->getId() == $defaultShippingId) {
$customer->setData('default_shipping', null);
}
$removedAddressId = $address->getId();
$address->delete();
// Remove deleted address from customer address collection
$customer->getAddressesCollection()->removeItemByKey($removedAddressId);
} else {
$address->setParentId(
$customer->getId()
)->setStoreId(
$customer->getStoreId()
)->setIsCustomerSaveTransaction(
true
)->save();
if (($address->getIsPrimaryBilling() ||
$address->getIsDefaultBilling()) && $address->getId() != $defaultBillingId
) {
$customer->setData('default_billing', $address->getId());
}
if (($address->getIsPrimaryShipping() ||
$address->getIsDefaultShipping()) && $address->getId() != $defaultShippingId
) {
$customer->setData('default_shipping', $address->getId());
}
}
}
}

if ($customer->getAddresses() !== null && !$customerModel->getData('ignore_validation_flag')) {
if ($customer->getId()) {
$existingAddresses = $this->getById($customer->getId())->getAddresses();
$getIdFunc = function ($address) {
return $address->getId();
};
$existingAddressIds = array_map($getIdFunc, $existingAddresses);
} else {
$existingAddressIds = [];
}
$savedAddressIds = [];
foreach ($customer->getAddresses() as $address) {
$address->setCustomerId($customerId)
->setRegion($address->getRegion());
$this->addressRepository->save($address);
if ($address->getId()) {
$savedAddressIds[] = $address->getId();
}
}
$this->deleteAddressesByIds(array_diff($existingAddressIds, $savedAddressIds));
}

So having that in mind, it looks like we shouldn't fix this issue because we already have the mechanism for skipping address validation.

@vovayatsyuk
Copy link
Member Author

The problem appears when the exception is thrown which leads to the $this->customerRepository->delete($customer); method that is restricted on frontend.

So, yes, if we can guarantee that exception will not be thrown we will never see this error.

Unfortunately, I don't remember why it happened in the first place, maybe it was a custom theme that removed the address form from multishipping registration page.

@ihor-sviziev
Copy link
Contributor

@vovayatsyuk, so please double-check it from your side, if adding such a flag fixes the issue for you - I think we can close this Pull Request as fixed. If it's not - please provide some steps to reproduce.

@vovayatsyuk
Copy link
Member Author

Ok, let's close this PR

@ihor-sviziev
Copy link
Contributor

@vovayatsyuk, thank you so much for contributing and trying to improve Magento! I'm very sorry to not process your pull request for three years 🤦‍♂️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Auto-Tests: Covered All changes in Pull Request is covered by auto-tests Award: test coverage Component: Customer Priority: P2 A defect with this priority could have functionality issues which are not to expectations. QA: Added to Regression Scope Scenario was analysed and added to Regression Testing Scope Release Line: 2.4 Severity: S2 Major restrictions or short-term circumventions are required until a fix is available.
Projects
None yet
8 participants