Hello Magento Friends ?,
Welcome to MageComp’s Technical Blog series. Today we are going to dig out How to Restrict Customer to Access CMS Page and Redirect to Login Page in Magento 2. Our previous blog was Solved: Export File gets “Message is added to queue, wait to get your file soon” in Magento 2.3.X.
Introduction:
You might have visited some sites that won’t allow you access to some page if you are not logged in. Magento 2 also facilitates to restrict users who are not registered. When the user seeks access to the CMS page of your Magento 2 store, you can redirect them to the login page. After the user login, it will be again redirected to the previous page.
Let’s see, How to Redirect Customer to Access CMS Page and Redirect to Login Page in Magento 2 ?
Steps to Restrict Customer to Access CMS Page and Redirect to Login Page in Magento 2:
Step 1: First, we need to create an “events.xml” file inside the following path:
app\code\Vendor\Extension\etc\frontend\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_cms_page_view"> <observer name="add_login_checker" instance="Vendor\Extension\Observer\Restrictcmspage" /> </event> </config>
Step 2: Lastly, create the “Restrictcmspage.php” file inside the following path:
app\code\Vendor\Extension\Observer\Restrictcmspage.php
<?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Event\Observer; use Magento\Customer\Model\Session as CustomerSession; class Restrictcmspage implements ObserverInterface { protected $_actionFlag; public function __construct( CustomerSession $customerSession, \Magento\Framework\App\ActionFlag $actionFlag, \Magento\Framework\App\Response\RedirectInterface $redirect ) { $this->customerSession = $customerSession; $this->_actionFlag = $actionFlag; $this->redirect = $redirect; } public function execute(Observer $observer) { if (!$this->customerSession->authenticate()) { $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); if (!$this->customerSession->getBeforeUrl()) { $this->customerSession->setBeforeUrl($this->redirect->getRefererUrl()); } } return $this; } }
That’s it.
Conclusion:
You have successfully implemented Restrict Customer to Access CMS Page and Redirect to Login Page in Magento 2 and you are free to customize this code according to your need for fetching data. If you have any queries write down in the comment section below. Help your Magento friends with this by sharing the article with them.
Happy Restricting ?