0

I want to check when the user clicks on my custom link in my account section it should verify that the customer is logged in or not then it should open.the particular action.Otherwise, it will redirects to login page.

2
  • my account page only open if you logged in. – Ravi Soni Dec 19 '19 at 8:55
  • i have created one hyperlink in my account sidebar as my blog when user clicks on that link then all blogs of the customer will appear for it I need to check it should open when the user is logged only. – Vikas kalal Dec 19 '19 at 9:21
1

You can check Customer is Logged in Or Not ?

Using Object Manager :

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

In Controller :

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

I thnik It's not best way to use object manager so i found another why where we can check and redirect the customer to login page if it's not logged in.

<?php
namespace Vendor\ModuldName\Controller\ControllerName;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;

class ControllerFileName extends \Magento\Framework\App\Action\Action
{   
    private $customerSession;
    private $resultPageFactory;

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

    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
     /**
     * Retrieve customer session object
     *
     * @return \Magento\Customer\Model\Session
     */
    protected function _getSession()
    {
        return $this->customerSession;
    }

    /**
     * Check customer authentication
     *
     * @param RequestInterface $request
     * @return \Magento\Framework\App\ResponseInterface
     */
    public function dispatch(RequestInterface $request)
    {
        if (!$this->_getSession()->authenticate()) {
            $this->_actionFlag->set('', 'no-dispatch', true);
        }
        return parent::dispatch($request);
    }
}

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.