Question

I have used below code to write plugin method for loginPost controller.

this is the code of etc/di.xml

<type name="Magento\Customer\Controller\Account\LoginPost">
    <plugin name="MyCucomtLoginAccountLoginPost" type="Vendor\Module\Plugin\Customer\LoginPost" sortOrder="10" disabled="false"/>
</type>

And i used below code in LoginPost.php

<?php

   namespace Vendor\Module\Plugin\Customer;

    use Magento\Customer\Model\Session;
    use Magento\Framework\Data\Form\FormKey\Validator;
    use Magento\Customer\Api\CustomerRepositoryInterface;
    use Magento\Framework\Message\ManagerInterface;
    use Magento\Framework\App\Response\Http as ResponseHttp;
    use Magento\Framework\App\Config\ScopeConfigInterface as ScopeConfig;
    use Magento\Framework\UrlInterface;
    use Magento\Customer\Model\Account\Redirect as AccountRedirect;
class LoginPost
   {
protected $session;
/** @var Validator */
protected $formKeyValidator;
/** @var CustomerRepositoryInterface */
protected $customerRepositoryInterface;
/** @var ManagerInterface **/
protected $messageManager;
protected $_objectManager;
/** @var Http **/
protected $responseHttp;
protected $currentCustomer;
protected $_customer; 
protected $_storeManager;    
protected $resultFactory;
protected $redirect;
protected $accountRedirect;
protected $resultRedirectFactory;

public function __construct(
    Session $customerSession,
    Validator $formKeyValidator,
    CustomerRepositoryInterface $customerRepositoryInterface,
    ManagerInterface $messageManager,
    ResponseHttp $responseHttp,
    ScopeConfig $scopeConfig,
    \Magento\Customer\Model\CustomerFactory $customer,
    UrlInterface $url,
    \Magento\Framework\ObjectManagerInterface $objectmanager,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\Controller\ResultFactory $resultFactory,
    \Magento\Framework\App\Response\RedirectInterface $redirect,
    AccountRedirect $accountRedirect,
    \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
)
{
    $this->scopeConfig = $scopeConfig;
    $this->session = $customerSession;
    $this->formKeyValidator = $formKeyValidator;
    $this->customerRepositoryInterface = $customerRepositoryInterface;
    $this->messageManager = $messageManager;
    $this->responseHttp = $responseHttp;
    $this->_customer = $customer; 
    $this->_url = $url;
    $this->_objectManager = $objectmanager;
    $this->_storeManager = $storeManager; 
    $this->resultFactory = $resultFactory;
    $this->redirect = $redirect;
    $this->accountRedirect = $accountRedirect;
    $this->resultRedirectFactory       = $resultRedirectFactory;
}
public function afterExecute(\Magento\Customer\Controller\Account\LoginPost $subject, $result) 
{       
    $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;        
    if ($subject->getRequest()->isPost()) {
        $login = $subject->getRequest()->getPost('login');

        if (!empty($login['username']) && !empty($login['password'])) {

            $customerId = $this->getCustomer(trim($login['username']));

            $currentCustomer = $this->getcurrentcustomer($customerId);
            $status = $currentCustomer->getCustomerActivated(); 
            try {
                if($status == 0){                       
                     $message = "This account is awaiting activation.";                      
                     $this->messageManager->addError($message);                     
                     $result->setPath('customer/account/login');
                     return $result;                         
                }else{                                          
                    $configValue = $this->scopeConfig->getValue('customer/startup/redirect_dashboard', $storeScope);

                     if ($configValue == 1) {
                        /* $url = $this->_url->getUrl('customer/account');                      
                        $this->responseHttp->setRedirect($url);      */ 
                        $result->setPath('customer/account');   
                    } else {
                        $redirectUrl = $this->session->getBeforeLoginUrl();
                        $this->session->unsBeforeLoginUrl();
                        $result->setPath($redirectUrl);                                                 
                    }

                    return $result;
                }
            }
            catch (\Exception $e)
            {
                $message = "Invalid user Credentials.";
                $this->messageManager->addError($e->getMessage());
                $this->session->setUsername($login['username']);
                $this->responseHttp->setRedirect('customer/account/login');

            }
        }            
    }

}

/**
 * @param $email
 * @return \Magento\Customer\Api\Data\CustomerInterface
 */
public function getCustomer($email)
{
    try{
        $websiteID = $this->_storeManager->getStore()->getWebsiteId();
        $customer = $this->_customer->create()->setWebsiteId($websiteID)->loadByEmail($email);
        $userId = $customer->getId();           
        return $userId;
    }catch (\Exception $e){
        return false;
    }
}

public function getcurrentcustomer($id){
    $customerObj = $this->_customer->create();
    $customer = $customerObj->load($id);
    return $customer; 
}

public function getStoreId()
{
    return $this->_storeManager->getStore()->getId();
}
 public function getWebsiteId(){
   return $this->_storeManager->getStore()->getWebsiteId();
  }

}

Problem here i am facing is It is always redirect to customer Dashboard once the customer is logged in.

I have set Option as "No" in backend for this setting under Login Options

Redirect customer to Account dashboard after logging in => NO, If that is set "YES", that time only it should redirect to dashboard, but its not working properly.

What code i need to use to make it work? Thanks

Was it helpful?

Solution

Try to use aroundExecute() :

<?php

namespace Vendor\Module\Plugin\Customer;
use Magento\Customer\Model\Session;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\App\Response\Http as ResponseHttp;
use Magento\Framework\App\Config\ScopeConfigInterface as ScopeConfig;
use Magento\Framework\UrlInterface;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;

class LoginPost
{
    protected $session;
    protected $formKeyValidator;
    protected $customerRepositoryInterface;
    protected $messageManager;
    protected $_objectManager;
    protected $responseHttp;
    protected $currentCustomer;
    protected $_customer;
    protected $_storeManager;
    protected $accountRedirect;
    protected $resultRedirectFactory;

    public function __construct(Session $customerSession, Validator $formKeyValidator, CustomerRepositoryInterface $customerRepositoryInterface, ManagerInterface $messageManager, ResponseHttp $responseHttp, ScopeConfig $scopeConfig, \Magento\Customer\Model\CustomerFactory $customer, UrlInterface $url, \Magento\Framework\ObjectManagerInterface $objectmanager, \Magento\Store\Model\StoreManagerInterface $storeManager,AccountRedirect $accountRedirect,\Magento\Framework\Controller\ResultFactory $resultRedirectFactory)
    {
        $this->scopeConfig                 = $scopeConfig;
        $this->session                     = $customerSession;
        $this->formKeyValidator            = $formKeyValidator;
        $this->customerRepositoryInterface = $customerRepositoryInterface;
        $this->messageManager              = $messageManager;
        $this->responseHttp                = $responseHttp;
        $this->_customer                   = $customer;
        $this->_url                        = $url;
        $this->_connector                  = $connector;
        $this->_objectManager              = $objectmanager;
        $this->_storeManager               = $storeManager;
        $this->accountRedirect             = $accountRedirect;
        $this->resultRedirectFactory       = $resultRedirectFactory;
    }
    public function aroundExecute(\Magento\Customer\Controller\Account\LoginPost $loginPost, $result)
    {
        //your code logic
        $redirectUrl = $this->accountRedirect->getRedirectCookie();
        $resultRedirect = $this->resultRedirectFactory->create();// URL is checked to be internal in $this->_redirect->success()
        $resultRedirect->setUrl($this->_redirect->success($redirectUrl));
        return $resultRedirect;

    }
}

You can redirect by this code :

if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('*/*/');
            return $resultRedirect;
        }

This will redirect to home page if customer is login. If you want to redirect on customer/account/login page, still you can't able to redirect same page. Because, core magento also redirect on home page if logged in customer will access customer/account/login this page.

You can refer these both file :

vendor/magento/module-customer/Controller/Account/Login.php
vendor/magento/module-customer/Controller/Account/LoginPost.php

I hope it will helpful for you.

OTHER TIPS

use this:

public function aroundExecute(\Magento\Customer\Controller\Account\LoginPost $loginPost, $proceed)
{
    ...
    //if the config is not checked
    if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard')) {
      $currentUrl = $this->_storeManager->getStore()->getCurrentUrl(); 
      header("Location: ".$currentUrl);
      die();
    }
}

Update: We need to create 2 plugins, i.e. one for setting redirect URL (referrer URL) and other for redirection.

Step 1: Define the plugins in 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="conditional_redirect_after_login" type="Vendor\Module\Plugin\LoginPost" sortOrder="1" />
    </type>
    <type name="Magento\Customer\Controller\Account\Login">
        <plugin name="set_redirect_url" type="Vendor\Module\Plugin\Login" sortOrder="1" />
    </type>
</config>

Step 2: Plugin for setting up redirect URL in app/code/Vendor/Module/Plugin/Login.php

<?php

namespace Vendor\Module\Plugin;

class Login {
    protected $redirect;
    protected $customerSession;

    public function __construct(\Magento\Framework\App\Response\RedirectInterface $redirect, \Magento\Customer\Model\Session $customerSession) {
        $this->redirect = $redirect;
        $this->customerSession = $customerSession;
    }

    public function beforeExecute(
    \Magento\Customer\Controller\Account\Login $subject
    ) {
        $redirectUrl = $this->redirect->getRefererUrl();
        $this->customerSession->setBeforeLoginUrl($redirectUrl);
    }
}

Step 3: Redirect plugin file app/code/Vendor/Module/Plugin/LoginPost.php

<?php

namespace Vendor\Module\Plugin;

class LoginPost {

    protected $scopeConfig;
    protected $customerSession;

    public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Customer\Model\Session $customerSession) {
        $this->scopeConfig = $scopeConfig;
        $this->customerSession = $customerSession;
    }

    public function afterExecute(
    \Magento\Customer\Controller\Account\LoginPost $subject, $result
    ) {
        $configValue = $this->scopeConfig->getValue('guest_wishlist/general/enabled', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        if ($configValue == 1) {
            $result->setPath('customer/account'); // Change this to what you want
        } else {
            $redirectUrl = $this->customerSession->getBeforeLoginUrl();
            $this->customerSession->unsBeforeLoginUrl();
            $result->setPath($redirectUrl); // Change this to what you want
        }
        return $result;
    }

}

Note: This code is not complete. This is just for indication.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top