I found solutions for redirecting non logged in users to the login page for all CMS pages, but I only want to restrict a few CMS pages. How can I specify which pages to restrict?
My code right now:
...\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>\<plugin>\Observer\RestrictCmsPage"/>
</event>
</config>
...\observer\RestrictCmsPage.php
<?php
namespace <vendor>\<plugin>\Observer;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class RestrictCmsPage implements ObserverInterface
{
/**
* @var \Magento\Framework\App\ActionFlag
*/
protected $_actionFlag;
/**
* @var \Magento\Customer\Model\Session
*/
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;
}
}