10

I'm looking in Magento the Class that login a Customer and I do not find where is located.

I need to be able to login a user externally a Magento.

Any idea?

2 Answers 2

12
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
// Load customer
$customer = $objectManager->create('Magento\Customer\Model\Customer')->load(2); //2 is Customer ID

// Load customer session
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
$customerSession->setCustomerAsLoggedIn($customer);

if($customerSession->isLoggedIn()) {
    echo "Customer Logged in";
}else{
    echo "customer is Not Logged in";
}

A better way nowadays with Magento 2 is:


protected $_customerFactory;
protected $_sessionFactory;

public function __construct(
    ...
    \Magento\Customer\Model\CustomerFactory $customerFactory,
    \Magento\Customer\Model\SessionFactory $sessionFactory,
    ...
)
{
    ...
    $this->_customerFactory = $customerFactory;
    $this->_sessionFactory = $sessionFactory;
    ...
}

Now lets say this is on a Magento 2 Controller, then we have the below:

public function execute()
{
    ...
    $customer = $this->_customerFactory->create()->load($id) //$id is the 
    customer id you want to load
    $sessionManager = $this->_sessionFactory->create();
    $sessionManager->setCustomerAsLoggedIn($customer);
    ...
}

It is always best practice to use dependency injection to retrieve either model factories or interfaces for the tool you want to use instead of getting object manager instances.

7

Take a look at app/code/Magento/Customer/Controller/Account/LoginPost.php

class LoginPost extends \Magento\Customer\Controller\AbstractAccount
{

  ....

  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();
  ....
1
  • You're a wizard. How do you even find this stuff? Trying to do anything remotely "off the beaten path" with Magento and it's posts like this which provide the solutions to my problems. Thanks.
    – WackGet
    Feb 19, 2020 at 4:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.