The question:
I am trying to overriding the below class in my custom module:
vendormagentomodule-customerControllerAccountLoginPost.php
For overriding this I have created the Plugin file as per the below Magento 2 official reference:
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
I have created the app/code/Vendor/MyModule/etc/di.xml file:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="MagentoCustomerControllerAccountLoginPost">
<plugin name="MyCucomtLoginAccountLoginPost" type="VendorMyModulePluginCustomerLoginPost" sortOrder="10" disabled="false"/>
</type>
</config>
Now, I have written the below is aroundExecute method to achieve my customization:
appcodeVendorMyModulePluginCustomer
<?php
namespace VendorMyModulePluginCustomer;
class LoginPost
{
public function aroundExecute(MagentoCustomerControllerAccountLoginPost $subject, Closure $proceed)
{
//echo 'here'; die;
if (isset($login['press_room_page'])) {
$custom_redirect=true;
}
if (isset($login['press_room_page']) && $custom_redirect) {
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('mycustomlogin/index');
return $resultRedirect;
}
}
}
?>
The above code is working fine when I am print something “here” it means the file is override successfully.
Now I am adding my logic in the execute method below is original file of vendor which I have edited for testing purpose to check the logic work or not:
vendormagentomodule-customerControllerAccount
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace MagentoCustomerControllerAccount;
use MagentoCustomerModelAccountRedirect as AccountRedirect;
use MagentoFrameworkAppActionContext;
use MagentoCustomerModelSession;
use MagentoCustomerApiAccountManagementInterface;
use MagentoCustomerModelUrl as CustomerUrl;
use MagentoFrameworkExceptionEmailNotConfirmedException;
use MagentoFrameworkExceptionAuthenticationException;
use MagentoFrameworkDataFormFormKeyValidator;
use MagentoFrameworkExceptionLocalizedException;
use MagentoFrameworkExceptionStateUserLockedException;
use MagentoFrameworkAppConfigScopeConfigInterface;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class LoginPost extends MagentoCustomerControllerAbstractAccount
{
/** @var AccountManagementInterface */
protected $customerAccountManagement;
/** @var Validator */
protected $formKeyValidator;
/**
* @var AccountRedirect
*/
protected $accountRedirect;
/**
* @var Session
*/
protected $session;
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var MagentoFrameworkStdlibCookieCookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* @var MagentoFrameworkStdlibCookiePhpCookieManager
*/
private $cookieMetadataManager;
/**
* @param Context $context
* @param Session $customerSession
* @param AccountManagementInterface $customerAccountManagement
* @param CustomerUrl $customerHelperData
* @param Validator $formKeyValidator
* @param AccountRedirect $accountRedirect
*/
public function __construct(
Context $context,
Session $customerSession,
AccountManagementInterface $customerAccountManagement,
CustomerUrl $customerHelperData,
Validator $formKeyValidator,
AccountRedirect $accountRedirect
) {
$this->session = $customerSession;
$this->customerAccountManagement = $customerAccountManagement;
$this->customerUrl = $customerHelperData;
$this->formKeyValidator = $formKeyValidator;
$this->accountRedirect = $accountRedirect;
parent::__construct($context);
}
/**
* Login post action
*
* @return MagentoFrameworkControllerResultRedirect
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
/** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/');
return $resultRedirect;
}
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
$this->session->setCustomerDataAsLoggedIn($customer);
$this->session->regenerateId();
if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
}
$redirectUrl = $this->accountRedirect->getRedirectCookie();
if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {
$this->accountRedirect->clearRedirectCookie();
$resultRedirect = $this->resultRedirectFactory->create();
// URL is checked to be internal in $this->_redirect->success()
$resultRedirect->setUrl($this->_redirect->success($redirectUrl));
return $resultRedirect;
}
} catch (EmailNotConfirmedException $e) {
$value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
$message = __(
'This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.',
$value
);
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (UserLockedException $e) {
$message = __(
'The account is locked. Please wait and try again or contact %1.',
$this->getScopeConfig()->getValue('contact/email/recipient_email')
);
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (AuthenticationException $e) {
if (isset($login['my_custom_page'])) {
$custom_redirect=true;
}
$message = __('Invalid login or password.');
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (LocalizedException $e) {
$message = $e->getMessage();
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (Exception $e) {
// PA DSS violation: throwing or logging an exception here can disclose customer password
$this->messageManager->addError(
__('An unspecified error occurred. Please contact us for assistance.')
);
}
} else {
$this->messageManager->addError(__('A login and a password are required.'));
}
}
if (isset($login['my_custom_page']) && $custom_redirect) {
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('mycustomlogin/index');
return $resultRedirect;
}
return $this->accountRedirect->getRedirect();
}
}
Please see the below image to better understand what I have added my logic:
Please see below is second image to written logic for redirect user to again if they enter wrong username or password:
Below is the main moto for override the controller:
I have created the custom login page for specific customer group, they will login from the custom design page, so I have created the mycustomlogin.phtml in my module like: appcodeVendorMyModuleviewfrontendtemplatesmycustomlogin.phtml
and passed the hidden input field value in the form for check where user had posted the form. I have get the hidden input value in AuthenticationException $e
to check. if user have posted the form from custom design.
Anyone can suggest me how I can add my logic into the Plugin file?
Thanks!
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
You need to rewrite the customer loginPost plugin file as per the below
<?php
namespace VENDORMYMODULENAMEPluginCustomer;
class LoginPost
{
public function __construct(
MagentoFrameworkAppActionContext $context
) {
$this->_request = $context->getRequest();
$this->_response = $context->getResponse();
$this->resultRedirectFactory = $context->getResultRedirectFactory();
$this->resultFactory = $context->getResultFactory();
}
public function aroundExecute(MagentoCustomerControllerAccountLoginPost $subject, $proceed)
{
$login = $this->_request->getPost('login');
$custom_redirect= false;
$returnValue = $proceed();
if (isset($login['press_room_page'])) {
$custom_redirect=true;
}
if (isset($login['press_room_page']) && $custom_redirect) {
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('mycustomlogin/index');
return $resultRedirect;
}
return $returnValue;
}
}
Method 2
According to @lavanya answer, the best way indeed is to use the plugin interceptor, I wanted to add a full answer and in more clean.
app/code/Vendor/Module/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="MagentoCustomerControllerAccountLoginPost">
<plugin name="CustomerLoginRedirectPlugin" type="VendorModulePluginLoginPost" disabled="false" sortOrder="1" />
</type>
</config>
app/code/Vendor/Module/Plugin/LoginPost.php
<?php
namespace VendorModulePlugin;
use MagentoFrameworkControllerResultFactory;
use MagentoFrameworkUrlInterface;
class LoginPost
{
protected $resultFactory;
protected $url;
protected $_request;
protected $_response;
public function __construct(
MagentoFrameworkAppActionContext $context,
UrlInterface $url,
ResultFactory $resultFactory
)
{
$this->_request = $context->getRequest();
$this->_response = $context->getResponse();
$this->url = $url;
$this->resultFactory = $resultFactory;
}
public function aroundExecute(MagentoCustomerControllerAccountLoginPost $subject, Closure $proceed) {
/*Execute code before the original function*/
$login = $this->_request->getPost('login');
//$username = $login['username']; to retrieve the user name for exemple.
$custom_redirect= false;
if (isset($login['press_room_page'])) {
$custom_redirect=true;
}
$resultProceed = $proceed(); // Original function
/*Execute code after the original function*/
if ($custom_redirect) {
$result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$result->setUrl($this->url->getUrl('router/controllerfolder/controllername/'));
return $result;
}
return $resultProceed;
}
}
it could help someone.
Method 3
You can use after execute plugin and after that you can check either customer is login or not if not than you can redirect to your press page url
namespace VendorMyModulePluginCustomer;
class LoginPost
{
public function afterExecute(MagentoCustomerControllerAccountLoginPost $subject,$result)
{
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$customerSession = $objectManager->get('MagentoCustomerModelSession');
if(!$customerSession->isLoggedIn()) {
// redirect to press page
}
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0