2

I have found this module :

https://github.com/bitExpert/magento2-force-login

and this topic :

Force login to access catalog and product pages

but I still think there must be a simpler solution, to just limit access to product and catalog pages.

What would be the optimal point of departure for such a module?

Thanks guys!

4
  • are you mentioned product details page and catalog category page – Rajkumar .E Aug 7 '17 at 13:19
  • yes, siple solution, without any Admin functionality in the backend. – Supersonic Aug 7 '17 at 13:24
  • @Supersonic, try this module. You can impose login on any product, category,or CMS page with it. – Henry Roger Oct 22 '19 at 6:50
  • Thanks Henry Roger ! Very nice module ! – Supersonic Feb 11 '20 at 9:40
4

If you want to force customer to login:

Product Details Page:

You need to overwrite Controller in module-catalog/Controller/Product/View.php to force customer to login in product details page.

Catalog Category Page:

You need to overwrite Controller in module-catalog/Controller/Category/View.php to force customer to login in catalog category page.

Then, add customSession to Dependency injection check if customer is logged in or not. if logged in then redirect to product details page or catalog category page. Otherwise its redirect to customer login page.

Create a di.xml in vendor/module/etc/di.xml

  <?xml version="1.0" ?>
  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
      <preference for="Magento\Catalog\Controller\Product\View" type="Vendor\Module\Controller\Rewrite\Product\View" />  
  </config>

Use Product Details Page: Create View.php file Vendor\Module\Controller\Rewrite\Product in this path.

            <?php

    namespace Vendor\Module\Controller\Rewrite\Product;


    use Magento\Framework\App\Action\Context;
    use Magento\Framework\View\Result\PageFactory;


    class View extends \Magento\Catalog\Controller\Product\View
    {
        /**
         * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
         */

        Protected $customerSession;

        public function __construct(
            Context $context,
            \Magento\Catalog\Helper\Product\View $viewHelper,
            \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
            \Magento\Customer\Model\Session $customerSession,
            PageFactory $resultPageFactory
        ) {
            $this->viewHelper = $viewHelper;
            $this->resultForwardFactory = $resultForwardFactory;
            $this->resultPageFactory = $resultPageFactory;
            $this->customerSession=$customerSession;
            parent::__construct($context, $viewHelper, $resultForwardFactory,$resultPageFactory);
        }

        protected function noProductRedirect()
        {
            $store = $this->getRequest()->getQuery('store');
            if (isset($store) && !$this->getResponse()->isRedirect()) {
                $resultRedirect = $this->resultRedirectFactory->create();
                return $resultRedirect->setPath('');
            } elseif (!$this->getResponse()->isRedirect()) {
                $resultForward = $this->resultForwardFactory->create();
                $resultForward->forward('noroute');
                return $resultForward;
            }
        }

        public function execute()
        {
    // Do your stuff here
            try{

                if($this->customerSession->isLoggedin())
                {

                    echo "Customer Logged in";

                    // Get initial data from request
                    $categoryId = (int) $this->getRequest()->getParam('category', false);
                    $productId = (int) $this->getRequest()->getParam('id');
                    $specifyOptions = $this->getRequest()->getParam('options');

                    if ($this->getRequest()->isPost() && $this->getRequest()->getParam(self::PARAM_NAME_URL_ENCODED)) {
                        $product = $this->_initProduct();
                        if (!$product) {
                            return $this->noProductRedirect();
                        }
                        if ($specifyOptions) {
                            $notice = $product->getTypeInstance()->getSpecifyOptionMessage();
                            $this->messageManager->addNotice($notice);
                        }
                        if ($this->getRequest()->isAjax()) {
                            $this->getResponse()->representJson(
                                $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode([
                                    'backUrl' => $this->_redirect->getRedirectUrl()
                                ])
                            );
                            return;
                        }
                        $resultRedirect = $this->resultRedirectFactory->create();
                        $resultRedirect->setRefererOrBaseUrl();
                        return $resultRedirect;
                    }

                    // Prepare helper and params
                    $params = new \Magento\Framework\DataObject();
                    $params->setCategoryId($categoryId);
                    $params->setSpecifyOptions($specifyOptions);

                    // Render page
                    try {
                        $page = $this->resultPageFactory->create();
                        $this->viewHelper->prepareAndRender($page, $productId, $this, $params);
                        return $page;
                    } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
                        return $this->noProductRedirect();
                    } catch (\Exception $e) {
                        $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
                        $resultForward = $this->resultForwardFactory->create();
                        $resultForward->forward('noroute');
                        return $resultForward;
                    }

                }else{

                    $this->customerSession->setAfterAuthUrl($this->_url->getCurrentUrl());
                    $this->customerSession->authenticate();
                }
            }catch(Exception $e){

            }
            return parent::execute();
        }
    }

Same as overwrite catalog category page. Let me know if you have issue.

5
  • i updated my answer for product details page same as change catalog category page. – Rajkumar .E Aug 7 '17 at 14:01
  • Do I need to create a moodule.xml file? – Supersonic Aug 7 '17 at 14:40
  • If you want to do this via custom module, you need module.xml , other wise you use any other existing module, not core module. – Rajkumar .E Aug 8 '17 at 5:24
  • Hi Rajkumar! So far I have no issues. I have managed to make the same for Category pages. Thanks a lot! – Supersonic Aug 8 '17 at 9:09
  • but how to verify that your solution is just for a specific Category?? thanks in advance – Developper Magento Aug 28 '18 at 9:39
1

The better solution for this i am referring the one of the best extension that i have tried Force login on Mageants site

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.