I'm developing a custom module. How to check if a user is logged in or not? If not logged in, redirect the user to login page.
1 Answer
We should take a look at the Account Create controller: vendor/magento/module-customer/Controller/Account/Create.php, we can see how to check the session customer.
So, we can follow this way, example controller:
<?php
namespace Vendor\Module\Controller\Account;
class Check extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Customer\Model\Session
*/
protected $session;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Customer\Model\Session $customerSession
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Customer\Model\Session $customerSession
) {
$this->session = $customerSession;
parent::__construct($context);
}
public function execute()
{
if (!$this->session->isLoggedIn()) {
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('customer/account/login');
return $resultRedirect;
}
}
}