2

In Magento 1 if we create custom customer navigation link in that when we load page that time we check that customer is login or not if not than we redirect that page to login page using this code in controller

public function preDispatch()
{
    parent::preDispatch();

    if (!Mage::getSingleton('customer/session')->authenticate($this)) {
        $this->setFlag('', 'no-dispatch', true);
    }
}

In Magento 2 How can i check this if customer is not login than redirect to login page???

2 Answers 2

3

In Your Controller

namespace Company\Module\Controller\Index;
use Magento\Framework\App\RequestInterface; //use this
class .....{
     public function __construct(
        .....
        \Magento\Customer\Model\Session $customerSession,
        .....
     ){
         ....
         $this->customerSession = $customerSession;
         ....

     }
     public function dispatch(RequestInterface $request)
     {
          if (!$this->customerSession->authenticate()) {
              $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
          }
          return parent::dispatch($request);
     }
         ....

}

In Magento 2 We can do that using this code

2
  • This is i m looking for
    – Newbie
    Commented Dec 30, 2015 at 12:44
  • I also getting this issue, can you please let me know in which controller i am adding this code? Commented Sep 1, 2017 at 11:25
0

Following code you can check customer login or not anywhere

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}

From controller

$this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}

I hope this will help you.

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.