To restrict access to a specific CMS page in Magento 2 based on whether the customer is logged in or not, you can implement an observer that listens to the controller_action_predispatch_cms_page_view event. Here’s how you can achieve this:
Create an Observer Class (RestrictPage.php): This observer checks if the accessed CMS page matches a specific identifier (hot-sale) and redirects non-logged-in customers to the login page.
<?php
namespace JJRestrictPageObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkEventObserver;
use MagentoCustomerModelSession as CustomerSession;
use MagentoFrameworkAppActionFlag;
use MagentoFrameworkAppResponseRedirectInterface;
use MagentoCmsApiPageRepositoryInterface;
use MagentoFrameworkAppRequestHttp;
use MagentoFrameworkAppResponseHttp as Response;
class RestrictPage implements ObserverInterface
{
protected $customerSession;
protected $actionFlag;
protected $redirect;
protected $pageRepository;
protected $request;
protected $response;
public function __construct(
CustomerSession $customerSession,
ActionFlag $actionFlag,
RedirectInterface $redirect,
PageRepositoryInterface $pageRepository,
Http $request,
Response $response
) {
$this->customerSession = $customerSession;
$this->actionFlag = $actionFlag;
$this->redirect = $redirect;
$this->pageRepository = $pageRepository;
$this->request = $request;
$this->response = $response;
}
public function execute(Observer $observer)
{
$pageId = $this->request->getParam('page_id', $this->request->getParam('id', false));
if ($pageId) {
try {
$page = $this->pageRepository->getById($pageId);
if ($page->getIdentifier() == 'hot-sale' && !$this->customerSession->isLoggedIn()) {
$this->actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
if (!$this->customerSession->getBeforeUrl()) {
$this->customerSession->setBeforeUrl($this->request->getUriString());
}
$this->redirect->redirect($this->response, 'customer/account/login');
}
} catch (Exception $e) {
// Handle the exception if the page does not exist or other errors
}
}
return $this;
}
}
Configure the Observer: Declare your observer in the events.xml file of your module to listen to the controller_action_predispatch_cms_page_view event.
<?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="restrict_page_observer" instance="JJRestrictPageObserverRestrictPage"/> </event> </config>