Daily Archives: December 18, 2013


Check if a customer is logged in on a magento controller 1

As Alan Storm wrote about here http://alanstorm.com/magento_create_customer_page, there are a variety of different ways to check if a customer has an active session in Magento.

I want to check if the user/customer is logged in before all action methods. This seems to be the most common solution suggested

if(Mage::getSingleton('customer/session')->isLoggedIn()){
}

but in a controller’s preDispatch() method it does not work. It does work inside a specific action method however.

This solution that Alan found actually works. It’ll redirect to the login page and then redirect back to the referring page after successful login.

public function preDispatch()
{
    parent::preDispatch();
    $action = $this->getRequest()->getActionName();
    $loginUrl = Mage::helper('customer')->getLoginUrl();
 
    if (!Mage::getSingleton('customer/session')->authenticate($this, $loginUrl)) {
        $this->setFlag('', self::FLAG_NO_DISPATCH, true);
    }
}