cancel
Showing results for 
Search instead for 
Did you mean: 

How to assign a cookie to a user when using "Login as Customer" from the admin in Magento2?

How to assign a cookie to a user when using "Login as Customer" from the admin in Magento2?

My Magento2 (2.4.3-p2) installation has 3 store on it (abc.com, xyz.com, jkh.com), and the default store and admin are using abc.com

From the admin, when I use "Login as Customer" after selecting a user account for a specific store (xyz.com), I need to be able to assign a cookie to that user that I've logged in as from the admin (cookie name:is_admin, value:1, domain:xyz.com). This cookie needs to have the domain that the account is assigned to, so in this case it would be a cookie with the domain xyz.com.
And lastly, when I logout as the user, or close the browser window/tab, the cookie should be deleted.

I'm completely lost as to what I'm doing wrong.
Thanks for your help.

Here is what I've attempted to write, but I think I'm missing something here.

 

app/code/abc/LoginAsCustomerCookie/registration.php

<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Abc_LoginAsCustomerCookie', __DIR__);

 

app/code/abc/LoginAsCustomerCookie/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Abc_LoginAsCustomerCookie">
<sequence>
<module name="Magento_Customer"/>
</sequence>
</module>
</config>

 

app/code/abc/LoginAsCustomerCookie/etc/frontend/events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_data_object_login">
<observer name="abc_loginascustomercookie_observer_loginascustomercookie" instance="Abc\LoginAsCustomerCookie\Observer\LoginAsCustomerCookie"/>
</event>
</config>

app/code/abc/LoginAsCustomerCookie/Observer/LoginAsCustomerCookie.php

<?php
namespace Abc\LoginAsCustomerCookie\Observer;

use Magento\Customer\Model\Session;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class LoginAsCustomerCookie implements ObserverInterface
{
/**
* @var Session
*/
protected $customerSession;

/**
* LoginAsCustomerCookie constructor.
* @param Session $customerSession
*/
public function __construct(
Session $customerSession
) {
$this->customerSession = $customerSession;
}

/**
* Set a cookie when an admin logs in as a customer.
*
* @param Observer $observer
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$customer = $observer->getCustomer();
$store = $this->storeManager->getStore($customer->getStoreId());

$cookieMetadata = $this->cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration(0)
->setPath('/')
->setHttpOnly(false)
->setSameSite(CookieMetadataInterface::SAMESITE_LAX);

// Set the cookie domain to the current store's base URL
$baseUrl = $store->getBaseUrl();
$parsedUrl = parse_url($baseUrl);
if (isset($parsedUrl['host'])) {
$cookieMetadata->setDomain($parsedUrl['host']);
}

$this->cookieManager->setPublicCookie(
    'is_admin',
    '1',
    $cookieMetadata
);
}

}
1 REPLY 1

Re: How to assign a cookie to a user when using "Login as Customer" from the admin in Mage

 

It looks like you are missing some key components in your code. You need to include the CookieManagerInterface and CookieMetadataFactory in your observer to be able to set the cookie. Here's an updated version of your observer:

 

<?php
namespace Abc\LoginAsCustomerCookie\Observer;

use Magento\Customer\Model\Session;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata;

class LoginAsCustomerCookie implements ObserverInterface
{
    /**
     * @var Session
     */
    protected $customerSession;

    /**
     * @var CookieManagerInterface
     */
    protected $cookieManager;

    /**
     * @var CookieMetadataFactory
     */
    protected $cookieMetadataFactory;

    /**
     * LoginAsCustomerCookie constructor.
     * @param Session $customerSession
     * @param CookieManagerInterface $cookieManager
     * @param CookieMetadataFactory $cookieMetadataFactory
     */
    public function __construct(
        Session $customerSession,
        CookieManagerInterface $cookieManager,
        CookieMetadataFactory $cookieMetadataFactory
    ) {
        $this->customerSession = $customerSession;
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
    }

    /**
     * Set a cookie when an admin logs in as a customer.
     *
     * @param Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $customer = $observer->getCustomer();
        $store = $this->storeManager->getStore($customer->getStoreId());

        $cookieMetadata = $this->cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setDuration(0)
            ->setPath('/')
            ->setHttpOnly(false)
            ->setSameSite(PublicCookieMetadata::SAME_SITE_LAX);

        // Set the cookie domain to the current store's base URL
        $baseUrl = $store->getBaseUrl();
        $parsedUrl = parse_url($baseUrl);
        if (isset($parsedUrl['host'])) {
            $cookieMetadata->setDomain($parsedUrl['host']);
        }

        $this->cookieManager->setPublicCookie(
            'is_admin',
            '1',
            $cookieMetadata
        );
    }
}

Additionally, you also need to inject the CookieManagerInterface and CookieMetadataFactory in your module's di.xml file:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Abc\LoginAsCustomerCookie\Observer\LoginAsCustomerCookie"
                type="Abc\LoginAsCustomerCookie\Observer\LoginAsCustomerCookie" />
    <type name="Abc\LoginAsCustomerCookie\Observer\LoginAsCustomerCookie">
        <arguments>
            <argument name="cookieManager" xsi:type="object">Magento\Framework\Stdlib\Cookie\PhpCookieManager</argument>
            <argument name="cookieMetadataFactory" xsi:type="object">Magento\Framework\Stdlib\Cookie\CookieMetadataFactory</argument>
        </arguments>
    </type>
</config>

I hope this helps! Let me know if you have any questions. Also hit the KUDOS Button