Customer Authentication using Magento 2 to check customer types like its a guest user or login user.
There are many occasions when you need to check customer authentic status and based on the login customer only you need to show a specific page otherwise redirect it to the login page.
Verify the customer has valid authentication using \Magento\Customer\Model\Session Class. add the Customer Session class to the __construct() method of your Controller.
<?php
namespace Jesadiya\FavoriteList\Controller\Index;
use Magento\Framework\App\Action;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Result\Page;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class Index extends Action
{
/**
* @var Session
*/
protected $customerSession;
public function __construct(
Context $context,
Session $customerSession
) {
$this->customerSession = $customerSession;
parent::__construct($context);
}
/**
* Prepare wishlist for share
*
* @return ResultInterface
*/
public function execute()
{
if (!$this->customerSession->authenticate()) {
/** @var Page $resultPage */
$result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$result->setPath('customer/account/login');
return $result;
}
// do your logic here
}
}
Using this approach, validate the customer authenticate status for the login user.
