Search code examples
eventsmagentoauthenticationobserver-pattern

Magento: Fire event before the login process


After reading some posts, I'm trying to implement an observer to fire an event before the user login. I'll explain: I have a forum and a blog, using another framework, and I want the visitor to log only once: blog, forum or eshop. After that, he will be logged for other areas. For example, I am browsing the forum and I login into the forum. Then, when I open the shop, I am already logged in. And same thing for the opposite way.

It works, but just one problem: when I logged into the forum/blog and if I open the shop, I need to refresh the page to see that I am logged.

Actually, it's the same behavior as the standard Magento logout process: if you click on the link "logout" of your Magento shop, you will still see that you are logged in. There's a redirection/refresh to the homepage and then you see the message that you are logged out. Here is my code:

app/code/community/Fanxiang/UC/etc/config.xml:

[...]
<events>
<http_response_send_before>
 <observers>
  <UC>
   <type>model</type>
   <class>Fanxiang_UC_Helper_Data</class>
   <method>ucSynlog</method>
  </UC>
 </observers>
</http_response_send_before>
</events>
[...]

and: app/code/community/Fanxiang/UC/Helper/Data.php

class Fanxiang_UC_Helper_Data extends Mage_Core_Helper_Abstract
{
     public function ucSynlog($observer){
         if(!empty($_COOKIE['Example_auth'])){
             list($Example_uid, $Example_username) = explode("\t", uc_authcode($_COOKIE['Example_auth'], 'DECODE'));
             list($Example_uid, $Example_username,$email)        =uc_get_user($Example_username);
             $customer = Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($email);
             Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
         } else {
             Mage::getSingleton('customer/session')->logout();
         }
         Mage::log(time(), null, "logfile.log"); 
     }
}

PB: I'd like to avoid to refresh the page to see that I am logged in. Any idea or help is welcomed!

Yoong


Solution

  • As you've seen http_response_send_before occurs after the HTML is generated but before it is sent by the server, so the logged in status is not visible. You need to use an event that occurs before any HTML is put together, say, controller_action_predispatch.

    Here is a reference of several other possibilities