1

I'm trying to redirect guest users to the login page when they click on the Add to Cart button and they are not registered. But I can't do it. I am using an Observer with the following event

<event name="controller_action_predispatch_checkout_cart_add">

Below code is for /app/code/vendor/module/etc/frontend/event.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_checkout_cart_add">
        <observer name="restrict_sales_model_cart_add_before" instance="vendor\module\Observer\ForceLogin" />
    </event>
</config>

And below code is for Observer /app/code/vendor/module/Observer/ForceLogin.php

<?php

namespace vendor\module\Observer;

use Magento\Framework\Event\ObserverInterface;

class ForceLogin implements ObserverInterface
{
    protected $_responseFactory;
    protected $_url;
    private $scopeConfig;
    private $customerSession;
    private $customerUrl;
    private $context;
    private $contextHttp;
    protected $redirect;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\App\Http\Context $contextHttp,
        \Magento\Customer\Model\Url $customerUrl,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\App\Response\RedirectInterface $redirect,
        \Magento\Framework\UrlInterface $url
    ) {
        $this->scopeConfig     = $scopeConfig;
        $this->context         = $context;
        $this->customerSession = $customerSession;
        $this->customerUrl     = $customerUrl;
        $this->contextHttp     = $contextHttp;
        $this->messageManager = $context->getMessageManager();
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
        $this->redirect = $redirect;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $isLoggedIn = $this->contextHttp->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);

        if (!$isLoggedIn ) {
            $this->messageManager->addError(__('Loggin First.'));
            $customRedirectionUrl = $this->_url->getUrl('customer/account/login');
            $this->_responseFactory->create()->setRedirect($customRedirectionUrl)->sendResponse('200');
            exit();
        }
        return $this;
    }
}

Any idea why guest users are not redirecting to the login page?

2 Answers 2

1

You have to return the result redirect. Try this:

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        //session is: \Magento\Customer\Model\Session
        if (!$this->session->isLoggedIn()) {
            $resultRedirect->setUrl($this->_url->getUrl('customer/account/login'));
            return $resultRedirect;
        }
    }
0
0

Please check your addtocart is using ajax or not

Please refer to my solution

Create a plugin for `Magento\Checkout\Controller\Cart\Add::execute()

File etc/frontend/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">
    <type name="Magento\Checkout\Controller\Cart\Add">
        <plugin name="Vendor_Module::disable_guest_add_to_cart"
                type="Vendor\Module\Plugin\Magento\Checkout\Controller\Cart\AddPlugin"
                sortOrder="10"
                />
    </type>
</config>

File Vendor/Module/Plugin/Magento/Controller/Cart/AddPlugin.php

<?php
namespace Vendor\Module\Plugin\Magento\Checkout\Controller\Cart;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Response\RedirectInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\UrlInterface;
use Magento\Framework\Json\Helper\Data as JsonHelper;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;

class AddPlguin
{
    /**
     * @var UrlInterface
     */
    protected $url;

    /**
     * @var Session
     */
    private $customerSession;

    /**
     * @var RedirectFactory
     */
    protected $resultRedirectFactory;

    /**
     * @var RedirectInterface
     */
    private $redirect;

    /**
     * @var JsonHelper
     */
    private $jsonHelper;

    /**
     * @var AccountRedirect
     */
    private $accountRedirect;

    public function __construct(
        UrlInterface $url,
        Session $customerSession,
        RedirectFactory $resultRedirectFactory,
        RedirectInterface $redirect,
        JsonHelper $jsonHelper,
        AccountRedirect $accountRedirect,
    ) {
        $this->url = $url;
        $this->customerSession = $customerSession;
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->redirect = $redirect;
        $this->jsonHelper = $jsonHelper;
        $this->accountRedirect = $accountRedirect;
    }

    public function aroundExecute(
        \Magento\Checkout\Controller\Cart\Add $subject,
        \Closure $proceed
    ) {
        if(!$this->customerSession->isLoggedIn()) {
            $refererUrl =  $this->redirect->getRefererUrl();
            $route = 'customer/account/login';

            //Redirect after login success
            $this->accountRedirect->setRedirectCookie($refererUrl);
            
            //In case add to cart by submit form
            if(!$subject->getRequest()->isAjax()) {
                return $this->resultRedirectFactory->create()->setPath($route);
            }
           
            //In case add to cart by ajax
            $subject->getResponse()->representJson(
                $this->jsonHelper->jsonEncode([
                    'backUrl' => $this->url->getUrl($route)
                ])
            );
            return $subject->getResponse();
        }
        $proceed();
    }
}


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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