Categories
Magento 1

Redirecting to the Login Page for a Given Route

The following code sample will redirect from any routename that isn’t ‘customer’. More exceptions could be added as needed to add a white or black list for pages.

config.xml

<events>
	<controller_action_predispatch>
		<observers>
			<rayware_check_logged_in>
				<type>singleton</type>
				<class>rayware/loginobserver</class>
				<method>checkLoggedIn</method>
			</rayware_check_logged_in>
		</observers>
	</controller_action_predispatch>
</events>

The Observer

<?php
class Rayware_Core_Model_Loginobserver{
	
	// Prevent the user from going to any route that doesn't start with customer
	public function checkLoggedIn($observer){
		 $controllerAction = $observer->getEvent()->getControllerAction();
		 $request = $controllerAction->getRequest();
		 $session = Mage::getSingleton('customer/session');
     
		 $route = $request->getRouteName();
		 $action = $request->getControllerName();

		 
		 if ($session->isLoggedIn() || $route == 'customer') {
			 return;
		 }
	 
         $session->setAfterAuthUrl( Mage::helper('core/url')->getCurrentUrl() );
         $session->setBeforeAuthUrl( Mage::helper('core/url')->getCurrentUrl() );
    
         $request->setDispatched(false)
			->setModuleName('customer')
			->setControllerName('account')
			->setActionName('login');
	 }
}