Como realizar o login “autenticar um cliente” de um cliente programaticamente no Magento 2
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
// Load customer
$customer = $objectManager->create('Magento\Customer\Model\Customer')->load(2); //2 is Customer ID
// Load customer session
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
$customerSession->setCustomerAsLoggedIn($customer);
if($customerSession->isLoggedIn()) {
echo "Customer Logged in";
}else{
echo "customer is Not Logged in";
}
Como proceder, da forma correta em um Controller
protected $_customerFactory;
protected $_sessionFactory;
public function __construct(
...
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Model\SessionFactory $sessionFactory,
...
)
{
...
$this->_customerFactory = $customerFactory;
$this->_sessionFactory = $sessionFactory;
...
}
Na função Execute:
public function execute()
{
...
$customer = $this->_customerFactory->create()->load($id) //$id is the
customer id you want to load
$sessionManager = $this->_sessionFactory->create();
$sessionManager->setCustomerAsLoggedIn($customer);
...
}