Redirect customers to login page from home page in Magento 2
-
14-04-2021 - |
Вопрос
I want to redirect my store customers to custom login page when a customer visits my magento 2 store url. The customer could not access the site till he login to the store.
How could I do that in Magento 2.3.x?
Решение
Yes, you can achieve this. Create an observer on events controller_action_predispatch
and then using customer session \Magento\Customer\Model\Session
check every URL and redirect to Customer login page.
- Create first
events.xml
where we can defined observer for your work.File location:app/code/{Vendor}/{ModuleName}/etc/frontend/events.xml
- Create an observer class for checking customer login and redirect to
logo page.
app/code/{Vendor}/{ModuleName}/Observer/ControllerActionPredispatch.php
events.xml
<?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="check_customer_session_login"
instance="{Vendor}\{ModuleName}\Observer\ControllerActionPredispatch" />
</event>
</config>
ControllerActionPredispatch.php
<?php
namespace {Vendor}\{ModuleName}\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\Action\Action;
class ControllerActionPredispatch implements ObserverInterface
{
/**
* @var \Magento\Customer\Model\Url
*/
private $customerUrl;
/**
* @var \Magento\Customer\Model\Session
*/
private $customerSession;
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(
\Magento\Customer\Model\Url $customerUrl,
\Magento\Customer\Model\Session $customerSession,
LoggerInterface $logger
){
$this->customerUrl = $customerUrl;
$this->customerSession = $customerSession;
$this->logger = $logger;
}
/**
* @inheritDoc
*/
public function execute(Observer $observer)
{
/** @var Action $controller */
$action = $observer->getEvent()->getControllerAction();
$request = $observer->getEvent()->getRequest();
$request->getRouteName();
$this->logger->info($request->getRouteName());
$loginUrl = $this->customerUrl->getLoginUrl();
if (($request->getRouteName()!== 'customer') &&
(!$this->customerSession->authenticate($loginUrl))
) {
$action->getActionFlag()->set('', $action::FLAG_NO_DISPATCH, true);
}
}
}
Не связан с magento.stackexchange