I need to implement a custom requirement on a site I'm updating. This site has multi-store setup with 4 store views and each Store View has a designated Customer Group, therefore when registering in that Store View, customers are automatically added to that Group. I'm now required to ensure that customers can only login to the store view they originally registered in. I already have Account Sharing Options
set to Per Website
.
URLs represented as an example as follows:
www.mysite.com/agency-abc/customer/account/login/
www.mysite.com/agency-xyz/customer/account/login/
So my idea is to tap into the controller_action_predispatch_customer_account_loginPost
event and check for the customer's GroupId against the settings for the store. I wired up the observer (which I know is being triggered) as a test as follows:
config.xml
<frontend>
<events>
<controller_action_predispatch_customer_account_loginPost>
<observers>
<logincheck>
<class>logincheck/observer</class>
<method>loginCheck</method>
</logincheck>
</observers>
</controller_action_predispatch_customer_account_loginPost>
</events>
</frontend>
Model/Observer.php (disclaimer: code borrowed from another post here on stackexchange)
class Kalldis_LoginCheck_Model_Observer
{
public function loginCheck(Varien_Event_Observer $observer)
{
$customer = $observer->getEvent()->getCustomer();
$session = Mage::getSingleton('customer/session');
// **** hard-coding groupid as a test
if ($customer->getGroupId() == 8)
{
$session->setId(null)
->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID)
->getCookie()->delete('customer');
Mage::throwException('You are not allowed to login to this store.');
return;
}
//die("observed");
}
}
Unfortunately, I get the following error:
Fatal error: Call to a member function getGroupId() on a non-object in ...Model/Observer.php on line 16
I'm unsure whether this is the correct event to use and/or whether I am attempting to access the customer data incorrectly.
Would sincerely appreciate any help!
*EDIT BASED ON QAISAR'S ANSWER BELOW
Model/Observer.php
class Kalldis_LoginCheck_Model_Observer
{
public function loginCheck(Varien_Event_Observer $observer)
{
$customer = $observer->getEvent()->getCustomer();
$session = Mage::getSingleton('customer/session');
$storeId = Mage::app()->getStore()->getId();
if ($customer->getStoreId() !== $storeId)
{
$session->setId(null)
->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID)
->getCookie()->delete('customer');
Mage::throwException('You are not allowed to login to this store.');
return;
}
}
}