Trying to prevent registered users from logging in based on their customer group id. I have this working in magento 1, however I haven't been successful in replicating it on magento2. Any help is appreciated.
Magento 1
public function customerlogin($observer)
{
$customer = $observer->getEvent()->getCustomer();
$session = Mage::getSingleton('customer/session');
if ($customer->getData('group_id') == 2)
{
$session->setId(null)
->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID)
->getCookie()->delete('customer');
Mage::throwException(__('Login not allowed'));
return;
}
}
Magento 2 – unfinished
public function execute(\Magento\Framework\Event\Observer $observer)
{
$event = $observer->getEvent();
$customer = $event->getCustomer();
if($customer->getGroupId() == '2'){
$this->messageManager->addNotice(__('Login not allowed'));
//prevent login
}
}
Best Answer
Look into:
Magento will use
\Magento\Customer\Model\AccountManagement::authenticate()
to authenticate a customer by username and password. We should try Plugin with this method.app/code/Vendor/Customer/etc/frontend/di.xml
app/code/Vendor/Customer/Plugin/AccountManagement.php
Remember to create
module.xml
andregistration.php
file.