Skip to content

Instantly share code, notes, and snippets.

@danizord
Last active January 1, 2016 07:39
Show Gist options
  • Save danizord/8113307 to your computer and use it in GitHub Desktop.
Save danizord/8113307 to your computer and use it in GitHub Desktop.
Redirects unauthenticated users to login
<?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