Question

I have programmatically logged into the customer accounts from my custom controller. In this case the customer name is not loading in the header. https://prnt.sc/nzucg9

How can I do it?

Here is the code

    public function __construct(
               .....
            \Magento\Customer\Api\Data\CustomerInterfaceFactory $customerInterfaceFactory,
            \Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
            \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
            \Magento\Customer\Model\CustomerFactory $customerFactory,
            \Magento\Customer\Model\Session $customerSession,
             ....
        ) {
            $this->customerInterfaceFactory = $customerInterfaceFactory;
            $this->customerRepositoryInterface = $customerRepositoryInterface;
            $this->storeManagerInterface = $storeManagerInterface;
            $this->customerFactory = $customerFactory;
            $this->customerSession = $customerSession;
                 .....

        }

 public function execute() {
    $email = 'test@test.com';
        $storeId = $this->storeManagerInterface->getStore()->getId();             
        $websiteId = $this->storeManagerInterface->getStore($storeId)->getWebsiteId();      
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId)->loadByEmail($email);
        $this->customerSession->setCustomerAsLoggedIn($customer);
        $this->customerSession->regenerateId();
}
Was it helpful?

Solution

That value comes from localstorage (stored in the browser), you should check that your code actually places/reloads the customer data in the localstorage, that can hardly be done from the backend, try to use js to interact with the local storage, take this answer: How to force reloading of a customer data section?

There is no easy way to invalidate data from backend. On frontend you can use app/code/Magento/Customer/view/frontend/web/js/customer-data.js library to invalidate the local storage. Just call customerData.reload(['section_name']);

In crhome console it will look like: require('Magento_Customer/js/customer-data').reload('customer');

Also you can use this module as an example on how they implement the localstorage reload: https://github.com/magefan/module-login-as-customer

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top