Question

I am trying to overriding the below class in my custom module:

vendor\magento\module-customer\Controller\Account\LoginPost.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="Magento\Customer\Controller\Account\LoginPost">
        <plugin name="MyCucomtLoginAccountLoginPost" type="Vendor\MyModule\Plugin\Customer\LoginPost" sortOrder="10" disabled="false"/>
    </type>
</config>

Now, I have written the below is aroundExecute method to achieve my customization:

app\code\Vendor\MyModule\Plugin\Customer

<?php

namespace Vendor\MyModule\Plugin\Customer;

class LoginPost
{
    public function aroundExecute(\Magento\Customer\Controller\Account\LoginPost $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:

vendor\magento\module-customer\Controller\Account

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Customer\Controller\Account;

use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\State\UserLockedException;
use Magento\Framework\App\Config\ScopeConfigInterface;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class LoginPost extends \Magento\Customer\Controller\AbstractAccount
{   
    /** @var AccountManagementInterface */
    protected $customerAccountManagement;

    /** @var Validator */
    protected $formKeyValidator;

    /**
     * @var AccountRedirect
     */
    protected $accountRedirect;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
     */
    private $cookieMetadataFactory;

    /**
     * @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager
     */
    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 \Magento\Framework\Controller\Result\Redirect
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {
        if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            /** @var \Magento\Framework\Controller\Result\Redirect $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:

enter image description here

Please see below is second image to written logic for redirect user to again if they enter wrong username or password:enter image description here

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: app\code\Vendor\MyModule\view\frontend\templates\mycustomlogin.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!

Was it helpful?

Solution

You need to rewrite the customer loginPost plugin file as per the below

<?php

namespace VENDOR\MYMODULENAME\Plugin\Customer;

class LoginPost
{
    public function __construct(
        \Magento\Framework\App\Action\Context $context
    ) {
        $this->_request = $context->getRequest();
        $this->_response = $context->getResponse();
        $this->resultRedirectFactory = $context->getResultRedirectFactory();
        $this->resultFactory = $context->getResultFactory();
    }

    public function aroundExecute(\Magento\Customer\Controller\Account\LoginPost $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;
    }
}

OTHER TIPS

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="Magento\Customer\Controller\Account\LoginPost">
        <plugin name="CustomerLoginRedirectPlugin" type="Vendor\Module\Plugin\LoginPost" disabled="false" sortOrder="1" />
    </type>
</config>

app/code/Vendor/Module/Plugin/LoginPost.php

<?php
namespace Vendor\Module\Plugin;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\UrlInterface;

class LoginPost
{
    protected $resultFactory;
    protected $url;
    protected $_request;
    protected $_response;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        UrlInterface $url,
        ResultFactory $resultFactory

    )
    {
        $this->_request = $context->getRequest();
        $this->_response = $context->getResponse();
        $this->url = $url;
        $this->resultFactory = $resultFactory;
    }

    public function aroundExecute(\Magento\Customer\Controller\Account\LoginPost $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.

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 Vendor\MyModule\Plugin\Customer;

class LoginPost
{
    public function afterExecute(\Magento\Customer\Controller\Account\LoginPost $subject,$result)
    {   
       $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
       $customerSession = $objectManager->get('Magento\Customer\Model\Session');
       if(!$customerSession->isLoggedIn()) {
          // redirect to press page
       }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top