Skip to content

Instantly share code, notes, and snippets.

@guilhermewop
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guilhermewop/9515173 to your computer and use it in GitHub Desktop.
Save guilhermewop/9515173 to your computer and use it in GitHub Desktop.
Zend Framework 2. Restringe o acesso às páginas fora da white list. Útil para controlar login. Use no Module::onBootstrap
<?php
/**
* Restringe o acesso às páginas fora da white list. útil para controlar login.
*
* @param Zend\Mvc\MvcEvent $e Instância
* @param Mixed $authService Instância do serviço de autenticação
* @param Array $whiteListRoutes Lista de rotas na white list (Sem precisar de login)
* @param String $loginRoute Nome da rota para o login
* @link http://stackoverflow.com/questions/14137868/zend-framework-2-global-check-for-authentication-with-zfcuser
* @return void
*/
private function restrictLogin(MvcEvent $e, $authService, array $whiteListRoutes = array('login'), $loginRoute = 'login')
{
// Aplicação
$app = $e->getApplication();
// Event manager
$em = $app->getEventManager();
// Service Manager
$sm = $app->getServiceManager();
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($authService, $whiteListRoutes, $loginRoute) {
$match = $e->getRouteMatch();
// A rota não existe 404
if (!$match instanceof \Zend\Mvc\Router\Http\RouteMatch) {
return;
}
// A rota acessada está na white list. O usuário pode continuar o acesso
$name = $match->getMatchedRouteName();
if (in_array($name, $whiteListRoutes)) {
return;
}
// Usuário está autenticado. O usuário pode continuar o acesso
if ($authService->getDefaultAuthService()->hasIdentity()) {
return;
}
// Troca a rota para a qual o usuário será redirecionado
$router = $e->getRouter();
$url = $router->assemble(array(), array(
'name' => $loginRoute
));
// Redireciona o usuário
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, -100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment