getApplication(); $eventManager = $app->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); // check for authentication on non white-listed routes $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'authPreDispatch')); } /** * Get the module's config * * @return mixed The module config */ public function getConfig() { $config = include __DIR__ . '/config/module.config.php'; $routeLoader = new RouteLoader(); return $routeLoader->registerRoutes($config); } public function getAutoloaderConfig() { return [ 'Zend\Loader\StandardAutoloader' => [ 'namespaces' => [ __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ], ], ]; } /** * Authorisation, make sure users are logged in before allowing them to see anything * * @param MvcEvent $e * @return \Zend\Stdlib\ResponseInterface */ public function authPreDispatch(MvcEvent $e) { $app = $e->getApplication(); $serviceManager = $app->getServiceManager(); $authService = $serviceManager->get('auth-service'); // get the matched route name $match = $e->getRouteMatch(); $routeName = $match->getMatchedRouteName(); // the allowed routes, defined in global.php $config = $serviceManager->get("config"); $whitelist = $config["whitelist"]; if (!in_array($routeName, $whitelist) && !$authService->isLoggedIn()) { return $this->redirect($e, 'login'); } } /** * @param MvcEvent $e * @param $url * @return \Zend\Stdlib\ResponseInterface * @author fawle */ public function redirect(MvcEvent $e, $url) { $router = $e->getRouter(); $request = $e->getRequest(); $url = $router->assemble(array(), array('name' => $url)); /** @var \Zend\Http\Response $response */ $response = $e->getResponse(); if ($request->isXmlHttpRequest()) { $response->setContent(json_encode(array('redirect' => $url))); $response->setStatusCode(401); } else { $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); } return $response; } }