How to restrict access to specific Magento 2 categories based on category name when a user is not logged in?

To restrict access to certain categories in Magento 2 based on category names when the user is not logged in, you can implement an observer that listens to the controller_action_predispatch_catalog_category_view event. Here’s a step-by-step guide to achieve this:

Create an Observer Class (RestrictCategoryAccess.php):

This observer checks if the accessed category matches a specific name (Hot sale) and redirects non-logged-in users to the login page.

<?php
namespace JJAccountObserver;


use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoFrameworkAppResponseRedirectInterface;
use MagentoCustomerModelSession as CustomerSession;
use MagentoCatalogModelCategoryRepository;


class RestrictCategoryAccess implements ObserverInterface
{
    protected $customerSession;
    protected $redirect;
    protected $response;
    protected $categoryRepository;


    public function __construct(
        CustomerSession $customerSession,
        RedirectInterface $redirect,
        MagentoFrameworkAppResponseInterface $response,
        CategoryRepository $categoryRepository
    ) {
        $this->customerSession = $customerSession;
        $this->redirect = $redirect;
        $this->response = $response;
        $this->categoryRepository = $categoryRepository;
    }


    public function execute(MagentoFrameworkEventObserver $observer)
    {
        // Check if the customer is not logged in
        if (!$this->customerSession->isLoggedIn()) {
            // List of category names to restrict access to
            $categoryNamesToRestrict = ['Hot sale']; // Replace with your category names


            // Get the current request and retrieve the category ID from the request parameters
            $request = $observer->getEvent()->getRequest();
            $categoryId = (int) $request->getParam('id');


            try {
                // Load the category using the category ID
                $category = $this->categoryRepository->get($categoryId);
                // Get the category name
                $categoryName = $category->getName();


                // Check if the category name is in the list of restricted category names
                if (in_array($categoryName, $categoryNamesToRestrict)) {
                    // Redirect to the login page if the category is restricted
                    $this->redirect->redirect($this->response, 'customer/account/login');
                }
            } catch (Exception $e) {
                // Handle exception if category not found
            }
        }
    }
}

Configure the Observer:

Declare your observer in the events.xml file of your module to listen to the controller_action_predispatch_catalog_category_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_catalog_category_view">
        <observer name="restrict_category_access"
                  instance="JJAccountObserverRestrictCategoryAccess"/>
    </event>
</config>


Leave a comment

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