Magento2: How to create password protected cms page?

To make the cms pages, you have to use event/observer

controller_action_predispatch_cms_page_view

ON this event,fire an observer which will check current user is loggedin or not. If user is not loggedin this redirect to login page.

events.xml define at app/code/{vendorname}/{ModuleName}/etc/frontend/ at code is like:

<?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="{VendorName}{Modulename}ObserverRestrictCmsPage" />
    </event>       
</config>

Observer file RestrictCmsPage.php located at app/code/{vendorname}/{ModuleName}/Observer/ Observer code like

<?php
namespace {VendorName}{Modulename}Observer;

use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkEventObserver;
use MagentoCustomerModelSession as CustomerSession;

class RestrictCmsPage implements ObserverInterface
{
    /**
     * @var MagentoFrameworkAppActionFlag
     */
    protected $_actionFlag;
    /**
     * @var MagentoCustomerModelSession
     */

    public function __construct(
        CustomerSession $customerSession,
        MagentoFrameworkAppActionFlag $actionFlag,
        MagentoFrameworkAppResponseRedirectInterface $redirect
        )
    {
        $this->customerSession = $customerSession;
        $this->_actionFlag = $actionFlag;
        $this->redirect = $redirect;
    }
    public function execute(Observer $observer)
    {
        if (!$this->customerSession->authenticate()) {

            $this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
            if (!$this->customerSession->getBeforeUrl()) {
                $this->customerSession->setBeforeUrl($this->redirect->getRefererUrl());
            }
        }
        return  $this;
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *