1

I have a store that has two websites running off the same code but different urls. User accounts are set to be shared between sites but should be redirected to the correct site (based on usergroup) on login.

So far I have a plugin setup on after login execute action

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_wholesale_loginpostplugin" type="Vendor\Wholesale\Plugin\LoginPostPlugin" sortOrder="1" />
  </type>
</config>

LoginPostPlugin.php

<?php

namespace Vendor\Wholesale\Plugin;

/**
 *
 */
class LoginPostPlugin
{

  protected $_customerSession;
  protected $_scopeConfig;
  protected $_messageManager;
  protected $_storeManager;

  public function __construct(
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Framework\Message\ManagerInterface $messageManager,
    \Magento\Store\Model\StoreManagerInterface $storeManager
  )
  {
    $this->_customerSession = $customerSession;
    $this->_scopeConfig = $scopeConfig;
    $this->_messageManager = $messageManager;
    $this->_storeManager = $storeManager;
  }


  /**
   * Change redirect after login
   *
   * @param \Magento\Customer\Controller\Account $subject
   * @param \Magento\Framework\Controller\Result\Redirect $result
   */
  public function afterExecute(
    \Magento\Customer\Controller\Account\LoginPost $subject,
    $result)
  {

    $cur_customer = $this->_customerSession->getCustomer();

    $current_customer_group = $cur_customer->getGroupId();

    $group_ids = $this->_scopeConfig->getValue('wholesale/permissions/allowed_groups', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

    $allowed_group_ids = explode(",", $group_ids);

    $store_id = $this->_storeManager->getStore()->getId();

    // If they are one of the allowed wholesale groups
    if(in_array($current_customer_group, $allowed_group_ids)){

      // If they are not on the wholesale store, redirect to the wholesale store
      if($store_id != 2){

        $wholesale_url = "***";

        $this->_customerSession->logout();
        $this->_messageManager->addError(__("You should login to the wholesale website, you have been redirected to it"));
        $result->setUrl($wholesale_url . '/customer/account/');
        // Login to wholesale store here

      }

    // If they are a regular customer
    } else {

      // If they are trying to login to the wholesale store
      if($store_id == 2){

        $main_store_url = "***";

        $this->_customerSession->logout();
        $this->_messageManager->addError(__("You do not have permission to log into the wholesale website, you will be redirected to the main website"));
        $result->setUrl($main_store_url . '/customer/account/');
        // Login to main store here

      }

    }

    return $result;
  }

}

This works.But, I want to be able login to the correct website after redirecting them.

I would have thought that the two would use different browser sessions entirely & it would not be possible.

However, I found when adding messages the messages carried across between sites.

Both sites are running on the same url with the wholesale website running in a folder.

2

This solution will only work if both websites run on the same url:

Both sites are running on the same url with the wholesale website running in a folder.

Observe the controller_action_predispatch by creating an events.xml file in the etc/frontend/ folder of a module (here: the module is named Vendor_WebsiteLock):

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch">
        <observer name="vendor_websitelock" instance="Vendor\WebsiteLock\Observer\RedirectToAssignedWebsiteObserver" />
    </event>
</config>

Then create an observer file RedirectToAssignedWebsiteObserver.php in the Observer directory of the module:

<?php
namespace Vendor\WebsiteLock\Observer;

use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Response\RedirectInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;

class RedirectToAssignedWebsiteObserver implements ObserverInterface
{
    /**
     * @var RedirectInterface
     */
    private $redirectResponse;
    /**
     * @var CustomerSession
     */
    private $customerSession;
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;
    /**
     * @var UrlInterface
     */
    private $url;
    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    public function __construct
    (
        RedirectInterface $redirectResponse,
        CustomerSession $customerSession,
        StoreManagerInterface $storeManager,
        UrlInterface $url,
        ScopeConfigInterface $scopeConfig
    ) {
        $this->redirectResponse = $redirectResponse;
        $this->customerSession = $customerSession;
        $this->storeManager = $storeManager;
        $this->url = $url;
        $this->scopeConfig = $scopeConfig;
    }

    public function execute(Observer $observer)
    {
        if (!$this->customerSession->isLoggedIn()) {
            return;
        }

        if ($this->getCustomerWebsiteId() == $this->getCurrentWebsiteId()) {
            return;
        }

        /** @var \Magento\Framework\App\Action\Action $action */
        $action = $observer->getData('controller_action');
        $this->redirectResponse->redirect(
            $action->getResponse(),
            $this->getRedirectUrl()
        );
    }

    private function getRedirectUrl(): string
    {
        $currentUrl = $this->url->getUrl('*/*/*', [
            '_current' => true,
            '_use_rewrite' => true
        ]);

        $customerWebsiteId = $this->getCustomerWebsiteId();
        $redirectUrl = str_replace(
            $this->scopeConfig->getValue('web/secure/base_url', 'websites'),
            $this->scopeConfig->getValue('web/secure/base_url', 'websites', $customerWebsiteId),
            $currentUrl
        );
        if ($redirectUrl == $currentUrl) {
            $redirectUrl = str_replace(
                $this->scopeConfig->getValue('web/unsecure/base_url', 'websites'),
                $this->scopeConfig->getValue('web/unsecure/base_url', 'websites', $customerWebsiteId),
                $currentUrl
            );
        }
        $redirectUrl .= '?SID=' . $this->customerSession->getSessionId();
        return $redirectUrl;
    }

    private function getCustomerWebsiteId(): int
    {
        return $this->customerSession->getCustomer()->getWebsiteId();
    }

    private function getCurrentWebsiteId(): int
    {
        return $this->storeManager->getWebsite()->getId();
    }
}

This will check if a customer is logged in and belongs to a different than the current website. It then redirects to the customer website by just exchanging the base url and appending the Session ID as a parameter.

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.