Last active
January 1, 2016 07:39
-
-
Save danizord/8113307 to your computer and use it in GitHub Desktop.
Redirects unauthenticated users to login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace MyApp\Authentication; | |
use Zend\EventManager\AbstractListenerAggregate; | |
use Zend\EventManager\EventManagerInterface; | |
use Zend\Mvc\MvcEvent; | |
use Zend\Stdlib\ResponseInterface; | |
/** | |
* Redirects unauthenticated users to login | |
*/ | |
class AuthenticationListener extends AbstractListenerAggregate | |
{ | |
/** | |
* {@inheritDoc} | |
*/ | |
public function attach(EventManagerInterface $events) | |
{ | |
$this->listeners[] = $events->attach(MvcEvent::EVENT_ROUTE, [$this, 'onRoute'], 500); | |
} | |
/** | |
* @param MvcEvent $e | |
* @return void|ResponseInterface | |
*/ | |
public function onRoute(MvcEvent $e) | |
{ | |
$routeMatch = $e->getRouteMatch(); | |
if (!$routeMatch) { | |
return; | |
} | |
if ($routeMatch->getMatchedRouteName() === 'login') { | |
return; | |
} | |
$services = $e->getApplication()->getServiceManager(); | |
$authService = $services->get('Zend\Authentication\AuthenticationService'); | |
if ($authService->hasIdentity()) { | |
return; | |
}; | |
$response = $e->getResponse(); | |
$url = $e->getRouter()->assemble([], ['name' => 'login']); | |
$response->setStatusCode(302); | |
$response->getHeaders()->addHeaderLine('Location', $url); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment