0

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

7
  • Is it working ? Oct 24, 2018 at 9:39
  • Let me check now, I seen now Oct 24, 2018 at 9:42
  • Notice: Undefined property: Vendor\Customer\Plugin\Customer\LoginPost::$resultRedirectFactory in this line, getting this error Oct 24, 2018 at 9:53
  • check my update and remove var/ generated/ Oct 24, 2018 at 9:59
  • Warning: Missing argument 1 for Magento\Framework\Controller\ResultFactory::create(), called in now this error i am facing Oct 24, 2018 at 10:03

3 Answers 3

1

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.

16
  • hi, @Rohan, not understood clearly, will all my custom logic works if i use your code, because everything is working now, only redirect is the issue Oct 24, 2018 at 7:40
  • I don't want to set custom path, if setting is Yes in admin panel, it should go to dashboard else it should be in same page, Please read my issue once Oct 24, 2018 at 7:42
  • Magento also by default provide like that, if setting is no then it will redirect to home page. If you want to redirect in same page then you should add controller path in my answer. Oct 24, 2018 at 8:32
  • In my case its not working, i do not know why, but i overrided only this file, @rohan Oct 24, 2018 at 8:33
  • check my updated answer. Oct 24, 2018 at 9:01
0

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();
    }
}
10
  • This always redirect to home page is it? Oct 24, 2018 at 7:44
  • @jafarpinjar yes it always redirect to home page
    – blue
    Oct 24, 2018 at 7:46
  • That is not my question, please read it once Oct 24, 2018 at 7:47
  • @jafarpinjar check my updated question
    – blue
    Oct 24, 2018 at 7:54
  • hi, @blue, i do not want to redirect to home page, if setting is NO in admin, it should stay in same page, else it has to redirect to dashboard. I don't want to redirect anywhere like homepage or other pages, it should work like default magento, your code is to redirect to home page, that is not at all required Oct 24, 2018 at 7:57
0

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.

16
  • hi @mohit, I am looking for code to stay in same page or referer page if setting is yes Oct 24, 2018 at 11:32
  • Referer page for login post action will be login action. Which is not possible to redirect after login. Oct 24, 2018 at 12:05
  • so, it is not possible to stay in same page after login, if the setting is yes in admin? Oct 24, 2018 at 12:09
  • Are you trying to login using ajax popup? Oct 24, 2018 at 12:15
  • no, default login not using ajax pop up Oct 24, 2018 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.