1

I have a custom module, I want to auto login a customer on it when the customer comes with an specific url like:

www.example.com/myModule/?k=2sadf23wasdfde3wefsd34ss43545sdgasdfg/

I have the email address stored in the database against the key that is in URL string.

How can I auto login that particular customer?

1 Answer 1

1

In your custom module, create following files.

etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="vendor_module" frontName="vendor_module">
            <module name="Vendor_Module" />
        </route>
    </router>
</config>

Vendor/Module/Controller/Index/Index.php

<?php

namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Action;

class Index extends Action
{
    protected $customerCollection;
    protected $customerModel;
    protected $customerSession;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollection,
        \Magento\Customer\Model\CustomerFactory $customerModel,
        \Magento\Customer\Model\Session $customerSession
    )
    {
        parent::__construct($context);

        $this->customerCollection = $customerCollection;
        $this->customerModel = $customerModel;
        $this->customerSession = $customerSession;
    }

    public function execute()
    {
        $k = $this->getRequest()->getParam('k');

        if(!$this->customerSession->isLoggedIn())
        {
            $collection = $this->customerCollection->create();
            $collection->addAttributeToFilter('custom_attribute', $k);
            if($collection->getSize())
            {
                $customer_id = $collection->getFirstItem()->getId();
                $customer = $this->customerModel->create()->load($customer_id);
                $this->customerSession->setCustomerAsLoggedIn($customer);
                $this->_redirect('customer/account/index');
                return;
            }
        }

        die('customer not found');
    }
}
1
  • The code $this->customerSession->setCustomerAsLoggedIn($customer); worked for me. Thanks :) Apr 22, 2019 at 11:37

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.