5

Im experiencing an issue with Magento 2.1.7

I want to login users programmatically by only their email.

But after setCustomerAsLoggedIn it still shows sign in or create an account in the header.

This issue is the same as Show customer name after setCustomerAsLoggedIn()

which still hasn't been resolved.

/* Magento\Customer\Model\Customer $this->customer */
$Customer = $this->customer->loadByEmail('[email protected]');
/* Magento\Customer\Model\Session $this->customerSession */
$this->customerSession->setCustomerAsLoggedIn($customer);

2 Answers 2

5

I faced the same issue. The only way I found to update the customer info in the header was by reloading the "customer" section of the localStorage via JavaScript. AFAIK there is no way to do that only in PHP, server side.

Calling customerData.reload(['customer'], true); will trigger an AJAX call to http://www.yoursite.com/customer/section/load/?sections=customer&update_section_id=true&_=some_token. That call returns an object containing the customer data and will trigger the update that replaces the welcome message by the name of the customer.

define([
    'jquery',
    'Magento_Customer/js/customer-data'
], function ($, customerData) {
    'use strict';

    customerData.reload(['customer'], true);
});
0

Not sure if this is the best method but you can force Magento 2 to reload the Customer Data by adding below code to your controller (or wherever your setCustomerAsLoggedIn method calling sit in):

...
/**
 * @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager
 */
private $cookieMetadataManager;

/**
 * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
 */
private $cookieMetadataFactory;
...
public function __construct(
    ...
    \Magento\Framework\Stdlib\Cookie\PhpCookieManager $cookieManager,
    \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
)
{
    ...
    $this->cookieMetadataManager = $cookieManager;
    $this->cookieMetadataFactory = $cookieMetadataFactory;
}

...
$this->customerSession->setCustomerAsLoggedIn($customer);
$this->_customerSession->regenerateId();

//force Magento 2 to reload Customer Data in frontend
if ($this->cookieMetadataManager->getCookie('mage-cache-sessid')) {
    $metadata = $this->cookieMetadataFactory->createCookieMetadata();
    $metadata->setPath('/');
    $this->cookieMetadataManager->deleteCookie('mage-cache-sessid', $metadata);
}

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.