Restricting Access to All Pages Using Zend 2 and ZfcUser

A new application that I’m working on needs to block all access to every page, except the login page, for unauthenticated users. After setting up Zend 2 with the ZfcUser module, this is a piece of cake. Just update your module/Application/Module.php file with the following code:


getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);

$e->getApplication()->getEventManager()->getSharedManager()->attach('ZendMvcControllerAbstractActionController', 'dispatch', function($e) {

$controller = $e->getTarget();
$sm = $e->getApplication()->getServiceManager();
$auth = $sm->get('zfcuser_auth_service');

if (!$auth->hasIdentity()) {

// If on login / registration page, let them pass
if(
!($e->getRouteMatch()->getParam('controller', 'index') == 'zfcuser' && $e->getRouteMatch()->getParam('action', 'index') == 'login')
&& !($e->getRouteMatch()->getParam('controller', 'index') == 'zfcuser' && $e->getRouteMatch()->getParam('action', 'index') == 'register'))
$controller->plugin('redirect')->toRoute('zfcuser/login');
}
}, 100);

}
}

Wala. All requests, that are not to the login or register pages, are now forwarded to http://yoursite/user/login if a user is not authenticated.

Leave a Reply

Your email address will not be published. Required fields are marked *