3

I want to login customer via phone number in magento 2.2.2. I had seen earlier questions about this but answer is not found. Anyone please help me to achieve this.

this is my LoginPost .php

<?php

namespace Magento\Customer\Controller\Account;

use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\State\UserLockedException;
use Magento\Framework\App\Config\ScopeConfigInterface;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class LoginPost extends \Magento\Customer\Controller\AbstractAccount
{
/**
 * @var \Magento\Customer\Api\AccountManagementInterface
 */
protected $customerAccountManagement;

/**
 * @var \Magento\Framework\Data\Form\FormKey\Validator
 */
protected $formKeyValidator;

/**
 * @var AccountRedirect
 */
protected $accountRedirect;

/**
 * @var Session
 */
protected $session;

/**
 * @var ScopeConfigInterface
 */
private $scopeConfig;

/**
 * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
 */
private $cookieMetadataFactory;

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

/**
 * @param Context $context
 * @param Session $customerSession
 * @param AccountManagementInterface $customerAccountManagement
 * @param CustomerUrl $customerHelperData
 * @param Validator $formKeyValidator
 * @param AccountRedirect $accountRedirect
 */
public function __construct(
    Context $context,
    Session $customerSession,
    AccountManagementInterface $customerAccountManagement,
    CustomerUrl $customerHelperData,
    Validator $formKeyValidator,
    AccountRedirect $accountRedirect
) {
    $this->session = $customerSession;
    $this->customerAccountManagement = $customerAccountManagement;
    $this->customerUrl = $customerHelperData;
    $this->formKeyValidator = $formKeyValidator;
    $this->accountRedirect = $accountRedirect;
    parent::__construct($context);
}

/**
 * Get scope config
 *
 * @return ScopeConfigInterface
 * @deprecated 100.0.10
 */
private function getScopeConfig()
{
    if (!($this->scopeConfig instanceof \Magento\Framework\App\Config\ScopeConfigInterface)) {
        return \Magento\Framework\App\ObjectManager::getInstance()->get(
            \Magento\Framework\App\Config\ScopeConfigInterface::class
        );
    } else {
        return $this->scopeConfig;
    }
}

/**
 * Retrieve cookie manager
 *
 * @deprecated 100.1.0
 * @return \Magento\Framework\Stdlib\Cookie\PhpCookieManager
 */
private function getCookieManager()
{
    if (!$this->cookieMetadataManager) {
        $this->cookieMetadataManager = \Magento\Framework\App\ObjectManager::getInstance()->get(
            \Magento\Framework\Stdlib\Cookie\PhpCookieManager::class
        );
    }
    return $this->cookieMetadataManager;
}

/**
 * Retrieve cookie metadata factory
 *
 * @deprecated 100.1.0
 * @return \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
 */
private function getCookieMetadataFactory()
{
    if (!$this->cookieMetadataFactory) {
        $this->cookieMetadataFactory = \Magento\Framework\App\ObjectManager::getInstance()->get(
            \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class
        );
    }
    return $this->cookieMetadataFactory;
}

/**
 * Login post action
 *
 * @return \Magento\Framework\Controller\Result\Redirect
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 */
public function execute()
{
    if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('*/*/');
        return $resultRedirect;
    }

    if ($this->getRequest()->isPost()) {
        $login = $this->getRequest()->getPost('login');
        if (!empty($login['username']) && !empty($login['password'])) {
            try {
                $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                $this->session->setCustomerDataAsLoggedIn($customer);
                $this->session->regenerateId();
                if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
                    $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
                    $metadata->setPath('/');
                    $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
                }
                $redirectUrl = $this->accountRedirect->getRedirectCookie();
                if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {
                    $this->accountRedirect->clearRedirectCookie();
                    $resultRedirect = $this->resultRedirectFactory->create();
                    // URL is checked to be internal in $this->_redirect->success()
                    $resultRedirect->setUrl($this->_redirect->success($redirectUrl));
                    return $resultRedirect;
                }
            } catch (EmailNotConfirmedException $e) {
                $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
                $message = __(
                    'This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.',
                    $value
                );
                $this->messageManager->addError($message);
                $this->session->setUsername($login['username']);
            } catch (UserLockedException $e) {
                $message = __(
                    'You did not sign in correctly or your account is temporarily disabled.'
                );
                $this->messageManager->addError($message);
                $this->session->setUsername($login['username']);
            } catch (AuthenticationException $e) {
                $message = __('You did not sign in correctly or your account is temporarily disabled.');
                $this->messageManager->addError($message);
                $this->session->setUsername($login['username']);
            } catch (LocalizedException $e) {
                $message = $e->getMessage();
                $this->messageManager->addError($message);
                $this->session->setUsername($login['username']);
            } catch (\Exception $e) {
                // PA DSS violation: throwing or logging an exception here can disclose customer password
                $this->messageManager->addError(
                    __('An unspecified error occurred. Please contact us for assistance.')
                );
            }
        } else {
            $this->messageManager->addError(__('A login and a password are required.'));
        }
    }

    return $this->accountRedirect->getRedirect();
}

}

6
  • Before , answering this question, have some query,? Is the phone is an customer custom attribute or it customer address attribute?
    – Amit Bera
    May 10, 2018 at 16:57
  • phone is a customer address attribute
    – Ask Xah
    May 10, 2018 at 16:58
  • please give me a answer to my question.. I'm new to magento
    – Ask Xah
    May 10, 2018 at 17:05
  • What would your input for login customer phone no and password?
    – Amit Bera
    May 10, 2018 at 17:16
  • yes phone number and password
    – Ask Xah
    May 10, 2018 at 17:18

3 Answers 3

6

As you want to logged in a customer with there default billing address telephone and its password.

So, you have to create a custom module where you have check

  • Your entered phone number exists in the system,
  • If this phone number exits then, Get Email id of that user from this phone number
  • After that you using fetch email and password, you can log in easily and follow rest of Magento default logic.

To achieve it, you should REWRITE of the Action class Magento\Customer\Controller\Account\LoginPost fully.


First, create a model class where we will check the phone number exists in the system and get the email from that phone number no.

<?php
/**
 * Created by Amit Bera.
 * User: Amit Kumar Bera
 * Email: [email protected]
 * Date: 10-05-2018
 * Time: 22:44
 */

namespace {Vendorname}\{ModuleName}\Model;


class LoginByTelephone
{
    /**
     * @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory
     */
    protected $customerCollecctionFactory;

    /**
     * LoginByTelephone constructor.
     * @param \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollecctionFactory
     */
    public function __construct(
        \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollecctionFactory
    )
    {
        $this->customerCollecctionFactory = $customerCollecctionFactory;
    }

    public function authenticateByTelephone($telephone, $password)
    {
        $collection = $this->customerCollecctionFactory->create();
        $collection->joinAttribute(
            'billing_telephone',
            'customer_address/telephone',
            'default_billing',
            null,
            'left'
        )
            ->addAttributeToSelect(['email', 'billing_telephone','entity_id'])
            ->setPageSize(1)
            ->setCurPage(1)   ;
        if($collection->count() >= 1 ){
            return $collection->getFirstItem()->getData('email');
        }
        return false;
    }

}

REWRITE CLASS

<?php
/**
 * Created by Amit Bera.
 * User: Amit Kumar Bera
 * Email: [email protected]
 * Date: 10-05-2018
 * Time: 22:56
 */

namespace {Vendorname}\{ModuleName}\Rewrite\Customer;


use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\State\UserLockedException;
use Magento\Framework\App\Config\ScopeConfigInterface;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class LoginPost extends \Magento\Customer\Controller\AbstractAccount
{
    /**
     * @var \Magento\Customer\Api\AccountManagementInterface
     */
    protected $customerAccountManagement;

    /**
     * @var \Magento\Framework\Data\Form\FormKey\Validator
     */
    protected $formKeyValidator;

    /**
     * @var AccountRedirect
     */
    protected $accountRedirect;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
     */
    private $cookieMetadataFactory;

    /**
     * @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager
     */
    private $cookieMetadataManager;
    /**
     * @var \StackExchange\Works\Model\LoginByTelephone
     */
    protected $loginByTelephone;

    /**
     * @param Context $context
     * @param Session $customerSession
     * @param AccountManagementInterface $customerAccountManagement
     * @param CustomerUrl $customerHelperData
     * @param Validator $formKeyValidator
     * @param AccountRedirect $accountRedirect
     */
    public function __construct(
        Context $context,
        Session $customerSession,
        AccountManagementInterface $customerAccountManagement,
        CustomerUrl $customerHelperData,
        Validator $formKeyValidator,
        AccountRedirect $accountRedirect,
        \StackExchange\Works\Model\LoginByTelephone $loginByTelephone
    ) {
        $this->session = $customerSession;
        $this->customerAccountManagement = $customerAccountManagement;
        $this->customerUrl = $customerHelperData;
        $this->formKeyValidator = $formKeyValidator;
        $this->accountRedirect = $accountRedirect;
        $this->loginByTelephone = $loginByTelephone;
        parent::__construct($context);

    }

    /**
     * Get scope config
     *
     * @return ScopeConfigInterface
     * @deprecated 100.0.10
     */
    private function getScopeConfig()
    {
        if (!($this->scopeConfig instanceof \Magento\Framework\App\Config\ScopeConfigInterface)) {
            return \Magento\Framework\App\ObjectManager::getInstance()->get(
                \Magento\Framework\App\Config\ScopeConfigInterface::class
            );
        } else {
            return $this->scopeConfig;
        }
    }

    /**
     * Retrieve cookie manager
     *
     * @deprecated 100.1.0
     * @return \Magento\Framework\Stdlib\Cookie\PhpCookieManager
     */
    private function getCookieManager()
    {
        if (!$this->cookieMetadataManager) {
            $this->cookieMetadataManager = \Magento\Framework\App\ObjectManager::getInstance()->get(
                \Magento\Framework\Stdlib\Cookie\PhpCookieManager::class
            );
        }
        return $this->cookieMetadataManager;
    }

    /**
     * Retrieve cookie metadata factory
     *
     * @deprecated 100.1.0
     * @return \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
     */
    private function getCookieMetadataFactory()
    {
        if (!$this->cookieMetadataFactory) {
            $this->cookieMetadataFactory = \Magento\Framework\App\ObjectManager::getInstance()->get(
                \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class
            );
        }
        return $this->cookieMetadataFactory;
    }

    /**
     * Login post action
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {
        if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('*/*/');
            return $resultRedirect;
        }

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                    $telePhone = $login['username'];
                    $emailId = $this->loginByTelephone->authenticateByTelephone($login['username'], $login['password']);
                    // If email id does exits then throw error
                    if(!$emailId)
                    {
                        $message = __(
                            'Invalid  is Telephone nO.'
                        );
                        $this->messageManager->addError($message);
                        $this->session->setUsername($login['username']);
                        return $this->accountRedirect->getRedirect();
                    }
                    $login['username'] =  $emailId;

                    $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                    $this->session->setCustomerDataAsLoggedIn($customer);
                    $this->session->regenerateId();
                    if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
                        $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
                        $metadata->setPath('/');
                        $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
                    }
                    $redirectUrl = $this->accountRedirect->getRedirectCookie();
                    if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {
                        $this->accountRedirect->clearRedirectCookie();
                        $resultRedirect = $this->resultRedirectFactory->create();
                        // URL is checked to be internal in $this->_redirect->success()
                        $resultRedirect->setUrl($this->_redirect->success($redirectUrl));
                        return $resultRedirect;
                    }
                } catch (EmailNotConfirmedException $e) {
                    $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
                    $message = __(
                        'This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.',
                        $value
                    );
                    $this->messageManager->addError($message);
                   //$this->session->setUsername($login['username']);
                    $this->session->setUsername($telePhone);
                } catch (UserLockedException $e) {
                    $message = __(
                        'You did not sign in correctly or your account is temporarily disabled.'
                    );
                    $this->messageManager->addError($message);
                    //$this->session->setUsername($login['username']);
                    $this->session->setUsername($telePhone);
                } catch (AuthenticationException $e) {
                    $message = __('You did not sign in correctly or your account is temporarily disabled.');
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (LocalizedException $e) {
                    $message = $e->getMessage();
                    $this->messageManager->addError($message);
                    //$this->session->setUsername($login['username']);
                    $this->session->setUsername($telePhone);
                } catch (\Exception $e) {
                    // PA DSS violation: throwing or logging an exception here can disclose customer password
                    $this->messageManager->addError(
                        __('An unspecified error occurred. Please contact us for assistance.')
                    );
                }
            } else {
                $this->messageManager->addError(__('A login and a password are required.'));
            }
        }

        return $this->accountRedirect->getRedirect();
    }
}
1
  • can i replace the full loginpost.php to your code.?
    – Ask Xah
    May 12, 2018 at 7:16
1

I would recommend to use a plugin (instead of rewriting LoginPostClass)

/etc/di.xml

 <type name="Magento\Customer\Model\AccountManagement">
    <plugin name="stackexchange_works_plugin_accountmanagement_plugin"
            type="StackExchange\Works\Plugin\AccountManagementPlugin"
            sortOrder="10"
            disabled="false"/>
</type>

Plugin code, use Amit's LoginByTelephoneClass to get customer mail

<?php
namespace StackExchange\Works\Plugin;
class AccountManagementPlugin
{
 /**
 * @var \StackExchange\Works\Model\LoginByTelephone
 */
protected $loginByTelephone;

  /**
 * AccountManagementPlugin constructor.
 * @param \StackExchange\Works\Model\LoginByTelephone $loginByTelephone
 */
public function __construct(
    \StackExchange\Works\Model\LoginByTelephone $loginByTelephone
)
{
    $this->loginByTelephone = $loginByTelephone;
}

/**
 * Fetch customer mail by telephone
 * @param $subject
 * @param $username
 * @param $password
 * @return array
 */
public function beforeAuthenticate($subject, $username, $password)
{
        if ($email = $this->loginByTelephone->authenticateByTelephone($username)) {
            $username = $email;
        }

    return [$username, $password];
}
}
3
  • how can use this.? please specify with the file name and format. i'm new to magento
    – Ask Xah
    May 12, 2018 at 7:06
  • can you give me a full plugin, I don't known how to use this.. :(
    – Ask Xah
    May 12, 2018 at 7:16
  • At first you have to create a new module, see: devdocs.magento.com/videos/fundamentals/create-a-new-module after that include /etc/di.xml in your module's folder, add my Plugin code as "AccountManagementPlugin.php" to a new directory "Plugin" inside your module directory, add Amit's LoginByTelephone class to a new directory called Model in your module directory.
    – paddz
    May 14, 2018 at 11:21
1

Another approach you can take a look
Place plugin in your file etc/frontend/di.xml

<type name="Magento\Customer\Model\ResourceModel\CustomerRepository">
    <plugin name="customCustomerRepositoryPlugin" type="Vendor\ModuleName\Model\ResourceModel\CustomerRepositoryPlugin" disabled="false"/>
</type>

The main file put around in method get

public function aroundGet(
    \Magento\Customer\Api\CustomerRepositoryInterface $subject,
    \Closure $proceed,
    $email,
    $websiteId = null
) {
    //Main logic here
    $customer = $this->customerFactory->create();
    if ($websiteId === null) {
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer->setWebsiteId($websiteId);
    }

    $resource = $customer->getResource();
    $connection = $resource->getConnection();
    $bind = ['mobilenumber' => $email];
    //You will need filter email here but with your mobilenumber input
}

Better avoid rewrite class if possible

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.