From ab44fbc187fe6f57690298467216c56beaef3027 Mon Sep 17 00:00:00 2001
From: wubinworks <127310257+wubinworks@users.noreply.github.com>
Date: Fri, 18 Oct 2024 13:27:55 +0900
Subject: [PATCH] [Feature] Add WebAPI support
---
Helper/Data.php | 44 ----
Helper/System.php | 207 ++++++++++++++++++
Observer/EditPostObserver.php | 62 ++----
Plugin/Customer/Api/CustomerRepository.php | 64 ++++++
README.md | 37 +++-
composer.json | 10 +-
etc/adminhtml/system.xml | 2 +-
etc/di.xml | 12 +
i18n/ja_JP.csv | 4 +-
.../templates/form/disable-change-email.phtml | 4 +-
10 files changed, 342 insertions(+), 104 deletions(-)
delete mode 100644 Helper/Data.php
create mode 100644 Helper/System.php
create mode 100644 Plugin/Customer/Api/CustomerRepository.php
create mode 100644 etc/di.xml
diff --git a/Helper/Data.php b/Helper/Data.php
deleted file mode 100644
index d7d8f7d..0000000
--- a/Helper/Data.php
+++ /dev/null
@@ -1,44 +0,0 @@
-scopeConfig->getValue(
- $path,
- $scopeType,
- $scopeCode
- );
- }
-
- /**
- * Is disable change email
- *
- * @return bool
- */
- public function isDisableChangeEmail(): bool
- {
- return (bool)$this->getConfig(self::XML_PATH_CUSTOMER_ACCOUNT_INFORMATION_DISABLE_CHANGE_EMAIL);
- }
-}
diff --git a/Helper/System.php b/Helper/System.php
new file mode 100644
index 0000000..ec3ffb4
--- /dev/null
+++ b/Helper/System.php
@@ -0,0 +1,207 @@
+appState = $appState;
+ $this->userContext= $userContext;
+ $this->messageManager = $messageManager;
+ $this->eventManager = $eventManager;
+ }
+
+ /**
+ * Get current store system configuration value
+ *
+ * @param string $path
+ * @param string $scopeType
+ * @param null|int|string $scopeCode
+ * @return mixed
+ */
+ public function getConfig($path, $scopeType = \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $scopeCode = null)
+ {
+ return $this->scopeConfig->getValue(
+ $path,
+ $scopeType,
+ $scopeCode
+ );
+ }
+
+ /**
+ * Get current area code.
+ *
+ * @return string
+ */
+ public function getArea(): string
+ {
+ try {
+ $areaCode = $this->appState->getAreaCode();
+ } catch (LocalizedException $e) {
+ $areaCode = 'unknown';
+ }
+
+ return $areaCode;
+ }
+
+ /**
+ * Is admin or integration context
+ *
+ * @return bool
+ */
+ public function isAdminOrIntegration(): bool
+ {
+ return in_array(
+ $this->userContext->getUserType(),
+ [UserContextInterface::USER_TYPE_INTEGRATION, UserContextInterface::USER_TYPE_ADMIN]
+ );
+ }
+
+ /**
+ * Is in webapi area
+ *
+ * @return bool
+ */
+ public function isWebapi(): bool
+ {
+ return in_array(
+ $this->getArea(),
+ [Area::AREA_WEBAPI_REST, Area::AREA_WEBAPI_SOAP, Area::AREA_GRAPHQL]
+ );
+ }
+
+ /**
+ * Get current full action name
+ *
+ * @param string $delimiter
+ * @return string|null
+ */
+ public function getFullActionName(string $delimiter = '/')
+ {
+ if ($this->getArea() === Area::AREA_FRONTEND
+ || $this->getArea() === Area::AREA_ADMINHTML) {
+ return $this->_request->getFullActionName($delimiter);
+ }
+
+ return null;
+ }
+
+ /**
+ * Get message manager
+ *
+ * @return MessageManagerInterface
+ */
+ public function getMessageManager(): MessageManagerInterface
+ {
+ return $this->messageManager;
+ }
+
+ /**
+ * Get user context object
+ *
+ * @return UserContextInterface
+ */
+ public function getUserContextObject(): UserContextInterface
+ {
+ return $this->userContext;
+ }
+
+ /**
+ * Get event manager
+ *
+ * @return EventManagerInterface
+ */
+ public function getEventManager(): EventManagerInterface
+ {
+ return $this->eventManager;
+ }
+
+ /**
+ * Build url
+ *
+ * @param string $route
+ * @param array $params
+ * @return string
+ */
+ public function getUrl(string $route, $params = [])
+ {
+ return $this->_getUrl($route, $params);
+ }
+
+ /**
+ * Is change email disabled
+ *
+ * @return bool
+ */
+ public function isChangeEmailDisabled(): bool
+ {
+ return (bool)$this->getConfig(self::XML_PATH_CUSTOMER_ACCOUNT_INFORMATION_DISABLE_CHANGE_EMAIL);
+ }
+
+ /**
+ * Get change email ertor phrase
+ *
+ * @return Phrase
+ */
+ public function getChangeEmailErrorPhrase(): Phrase
+ {
+ return new Phrase('You cannot change email address.');
+ }
+}
diff --git a/Observer/EditPostObserver.php b/Observer/EditPostObserver.php
index adb0296..566afab 100644
--- a/Observer/EditPostObserver.php
+++ b/Observer/EditPostObserver.php
@@ -10,93 +10,69 @@
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\ActionFlag;
-use Magento\Framework\UrlInterface;
-use Magento\Framework\Message\ManagerInterface as MessageManagerInterface;
-use Wubinworks\DisableChangeEmail\Helper\Data as Helper;
+use Wubinworks\DisableChangeEmail\Helper\System as SystemHelper;
/**
* Prevent customer from changing account email address
*/
class EditPostObserver implements \Magento\Framework\Event\ObserverInterface
{
- /**
- * @var RequestInterface
- */
- private $request;
-
/**
* @var ResponseInterface
*/
- private $response;
+ protected $response;
/**
* @var ActionFlag
*/
- private $actionFlag;
-
- /**
- * @var UrlInterface
- */
- private $urlBuilder;
+ protected $actionFlag;
/**
- * @var MessageManagerInterface
+ * @var SystemHelper
*/
- private $messageManager;
-
- /**
- * @var Helper
- */
- private $helper;
+ protected $systemHelper;
/**
* Constructor
*
- * @param RequestInterface $request
* @param ResponseInterface $response
* @param ActionFlag $actionFlag
- * @param UrlInterface $urlBuilder
- * @param MessageManagerInterface $messageManager
- * @param Helper $helper
+ * @param SystemHelper $systemHelper
*/
public function __construct(
- RequestInterface $request,
ResponseInterface $response,
ActionFlag $actionFlag,
- UrlInterface $urlBuilder,
- MessageManagerInterface $messageManager,
- Helper $helper
+ SystemHelper $systemHelper
) {
- $this->request = $request;
$this->response = $response;
$this->actionFlag = $actionFlag;
- $this->urlBuilder = $urlBuilder;
- $this->messageManager = $messageManager;
- $this->helper = $helper;
+ $this->systemHelper = $systemHelper;
}
/**
- * Check change_email parameter
+ * Prevent logout and sending notification email if 'change_email' parameter is set
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
-
- * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function execute(\Magento\Framework\Event\Observer $observer): void
{
- if (!$this->request->isPost()
- || !$this->request->getPost('change_email', false)
- || !$this->helper->isDisableChangeEmail()) {
+ /** $request RequestInterface */
+ $request = $observer->getRequest();
+ if (!$request->isPost()
+ || !$request->getPost('change_email', false)
+ || !$this->systemHelper->isChangeEmailDisabled()) {
return;
}
$this->response->setRedirect(
- $this->urlBuilder->getUrl('customer/account/edit'),
+ $this->systemHelper->getUrl('customer/account/edit'),
301
);
- $this->messageManager->addErrorMessage(__('You cannot change email address.'));
- /* Stop further response processing */
+ $this->systemHelper->getMessageManager()->addErrorMessage(
+ $this->systemHelper->getChangeEmailErrorPhrase()
+ );
+ /** Stop further response processing */
$this->actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
}
}
diff --git a/Plugin/Customer/Api/CustomerRepository.php b/Plugin/Customer/Api/CustomerRepository.php
new file mode 100644
index 0000000..1b4f86b
--- /dev/null
+++ b/Plugin/Customer/Api/CustomerRepository.php
@@ -0,0 +1,64 @@
+systemHelper = $systemHelper;
+ }
+
+ /**
+ * Prevent changing email in `Customer User Context`
+ *
+ * @param CustomerRepositoryInterface $subject
+ * @param CustomerDataInterface $customer
+ * @return null
+ */
+ public function beforeSave(
+ CustomerRepositoryInterface $subject,
+ CustomerDataInterface $customer
+ ) {
+ if ($this->systemHelper->isChangeEmailDisabled()
+ && !$this->systemHelper->isAdminOrIntegration()) {
+ try {
+ $origCustomer = $subject->getById((int)$customer->getId());
+ } catch (\Exception $e) {
+ // Create account case
+ return null;
+ }
+
+ if ($origCustomer->getEmail() !== $customer->getEmail()) {
+ throw new InvalidEmailOrPasswordException($this->systemHelper->getChangeEmailErrorPhrase());
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/README.md b/README.md
index e53d2cd..b71644b 100644
--- a/README.md
+++ b/README.md
@@ -1,18 +1,33 @@
-# A simple Magento 2 module that prevents customer from changing account email address
-**Suitable for many business environments.**
+# Disable Change Email Extension for Magento 2
+
-# Description
-This extension prevents changing email at **Controller** level.
-
+## Introduction
+A simple Magento 2 extension that prevents customer from changing account email address. Suitable for many business environments such as B2B. It is also useful when you have an integration that the account email is used as an identifier in the other systems.
-### Universal Compatible
-This extension does not use `preference` and does not have `template override`.
+## Features
+ - Disables/Enables customer's ability to change account email
+ - Prevents a hack that can resulting in sending "Email Change Notification" email even the account email is not changed and unintentional logout
+ - Works for both Frontend and WebAPI area
-# Requirements
+## Compatibility
+This extension does not use `preference` and `template override`.
+
+\*Note: this extension disables the `change email checkbox` in frontend customer account editing page. If you are looking for a better UI experience such as removing the `change email checkbox` or the email input box, you may need to do a theme customization for `Magento_Customer::form/edit.phtml` template.
+
+## Requirements
**Magento 2.4**
-# Installation
+## Installation
**`composer require wubinworks/module-disable-change-email`**
-# How to use
-Enable at Admin Panel `Stores > Configuration > Customers > Customer Configuration > Account Information Options > Disable Change Email`.
+## Configuration
+Admin Panel `Stores > Configuration > Customers > Customer Configuration > Account Information Options`.
+ - `Disable Change Email`: Yes/No
+
+## For Developers
+If you want to change customer email programmatically in `Customer User Context`(e.g., in your frontend controller), use `\Magento\Customer\Model\Customer` instead of `\Magento\Customer\Api\CustomerRepositoryInterface`. See [example](https://github.com/wubinworks/magento2-disable-customer/blob/d8e473f79c4afe54007b3370d7012cde9882e7cb/Helper/Customer.php#L225).
+
+## ♥
+If you like this extension please star this repository.
+
+You may also like: [Disable Customer for Magento 2](https://github.com/wubinworks/magento2-disable-customer)
diff --git a/composer.json b/composer.json
index 716740d..8fe5992 100644
--- a/composer.json
+++ b/composer.json
@@ -1,13 +1,19 @@
{
"name": "wubinworks/module-disable-change-email",
- "description": "Prevent customer from changing account email address. Suitable for many business environments.",
+ "description": "A simple Magento 2 extension that prevents customer from changing account email address. Works for both Frontend and WebAPI area.",
+ "keywords": [
+ "disable change email",
+ "email notification",
+ "webapi",
+ "magento 2 extension"
+ ],
"require": {
"php": ">=7.3",
"magento/module-customer": "*",
"magento/magento2-base": "~2.4.0"
},
"type": "magento2-module",
- "version": "1.0.0",
+ "version": "1.1.0",
"license": "OSL-3.0",
"authors": [
{
diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml
index f68e566..cba9dce 100644
--- a/etc/adminhtml/system.xml
+++ b/etc/adminhtml/system.xml
@@ -11,7 +11,7 @@
- When changed, please clear cache
+ Help]]>
Magento\Config\Model\Config\Source\Yesno
diff --git a/etc/di.xml b/etc/di.xml
new file mode 100644
index 0000000..cb43c27
--- /dev/null
+++ b/etc/di.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
diff --git a/i18n/ja_JP.csv b/i18n/ja_JP.csv
index f2b224a..47118d5 100644
--- a/i18n/ja_JP.csv
+++ b/i18n/ja_JP.csv
@@ -1,3 +1,3 @@
"You cannot change email address.","アカウントのメールアドレス変更禁止。"
-"Disable Change Email","メールアドレス変更禁止"
-"When changed, please clear cache","設定変更後、キャッシュをクリアしてください"
+"Disable Change Email","メールアドレス変更不可"
+"Help","ヘルプ"
diff --git a/view/frontend/templates/form/disable-change-email.phtml b/view/frontend/templates/form/disable-change-email.phtml
index 8cfde9a..89697bf 100644
--- a/view/frontend/templates/form/disable-change-email.phtml
+++ b/view/frontend/templates/form/disable-change-email.phtml
@@ -10,8 +10,10 @@
// phpcs:disable Magento2.Templates.ThisInTemplate.FoundThis
// phpcs:disable Magento2.Templates.ThisInTemplate.FoundHelper
+
+use Wubinworks\DisableChangeEmail\Helper\System as SystemHelper;
?>
-helper(\Wubinworks\DisableChangeEmail\Helper\Data::class)->isDisableChangeEmail()): ?>
+helper(SystemHelper::class)->isChangeEmailDisabled()): ?>