5

Which class I should override in order to redirect a customer to a specific page after login?

I have tried to set Redirect Customer to Account Dashboard after Logging in in the store configuration but it is not working.

  • You enable or disable Guest Checkout? – Khoa TruongDinh Sep 5 '16 at 15:53
  • I have disabled guest checkout. – Paul Sep 5 '16 at 15:54
  • How about your current issue? – Khoa TruongDinh Sep 10 '16 at 7:32
  • The code you provided is a bit different from my magento. Maybe it from different versions. And I don't understand why it is related to cookie. I finally resolved it by overriding the LoginPost class. I posted my answer below. Thanks! – Paul Sep 11 '16 at 4:34
  • 1
    My magento version is v2.0.8 – Paul Sep 11 '16 at 4:37
13

A plugin is a better solution in this case because your extended class might need to be updated when Magento 2 updates.

Here is a solution using a after-plugin on LoginPost->execute() as suggested by Xenocide8998.

/Vendor/Module/etc/frontend/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="vendor_module_loginpostplugin" type="\Vendor\Module\Plugin\LoginPostPlugin" sortOrder="1" />
  </type>
</config>

/Vendor/Module/Plugin/LoginPostPlugin.php:

<?php

/**
 *
 */
namespace Vendor\Module\Plugin;

/**
 *
 */
class LoginPostPlugin
{

    /**
     * Change redirect after login to home instead of dashboard.
     *
     * @param \Magento\Customer\Controller\Account\LoginPost $subject
     * @param \Magento\Framework\Controller\Result\Redirect $result
     */
    public function afterExecute(
        \Magento\Customer\Controller\Account\LoginPost $subject,
        $result)
    {
        $result->setPath('/'); // Change this to what you want
        return $result;
    }

}
  • It's work well. One thing is when you need to $result->setPath('/'); to your custom path don't use "/" before URL, for example. $result->setPath('customer/dashboard/'); – Shuvankar Paul Dec 17 '18 at 8:50
4

I resolved it by overriding the LoginPost class

etc/di.xml

<preference for="Magento\Customer\Controller\Account\LoginPost" type="Vendor\Module\Controller\Account\LoginPost" />

Vendor/Module/Controller/Account/LoginPost.php

<?php

namespace Vendor\Module\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;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {

    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('home');
            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();
                } 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 (AuthenticationException $e) {
                    $message = __('Invalid login or password.');
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (\Exception $e) {
                    $this->messageManager->addError(__('Invalid login or password.'));
                }
            } else {
                $this->messageManager->addError(__('A login and a password are required.'));
            }
        }

        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('home');
        return $resultRedirect;
    }

}
  • 7
    I think using a plugin with the afterExecute() would be a cleaner option – Xenocide8998 Nov 4 '16 at 4:31
  • This not a good approach and will only cause problems in the future. Plugin is the way to go. – phagento Dec 13 '18 at 9:05
0

That the current local storage caused our issue.
If we enable or disable Redirect Customer to Account Dashboard after Logging in and Guest Checkout in Configuration, this feature will work well. However, we need to clear your local storage.

We can check the local storage localStorage.getItem('mage-cache-storage').

Take a look:

vendor/magento/module-checkout/view/frontend/web/js/sidebar.js

                var cart = customerData.get('cart'),
                    customer = customerData.get('customer');

                if (!customer().firstname && cart().isGuestCheckoutAllowed === false) {
                    // set URL for redirect on successful login/registration. It's postprocessed on backend.
                    $.cookie('login_redirect', this.options.url.checkout);
                    if (this.options.url.isRedirectRequired) {
                        location.href = this.options.url.loginUrl;
                    } else {
                        authenticationPopup.showModal();
                    }

                    return false;
                }

Magento will set the cookie $.cookie('login_redirect', this.options.url.checkout) based on customerData from local storage.

From the controller vendor/magento/module-customer/Controller/Account/LoginPost.php. It will check the redirect URL from cookie.

       $redirectUrl = $this->accountRedirect->getRedirectCookie();
       if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {
                    ......
                    return $resultRedirect;
        }

Magento version:

-Magento version 2.1.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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