Skip to content

Instantly share code, notes, and snippets.

@imuneer
Created May 20, 2015 08:45
Show Gist options
  • Save imuneer/bc89b86e82e71851cefa to your computer and use it in GitHub Desktop.
Save imuneer/bc89b86e82e71851cefa to your computer and use it in GitHub Desktop.
BjyAuthorize's UnauthorizedStrategy to redirect guest to login page and other user not having permission to specific route to home
<?php
namespace Application\View;
use BjyAuthorize\Service\Authorize;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\Http\Response as HttpResponse;
use Zend\Mvc\MvcEvent;
use Zend\Stdlib\ResponseInterface as Response;
class UnauthorizedStrategy implements ListenerAggregateInterface
{
/**
* @var \Zend\Stdlib\CallbackHandler[]
*/
protected $listeners = array();
public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'onDispatchError'), -5000);
}
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $index => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$index]);
}
}
}
public function onDispatchError(MvcEvent $e)
{
// Do nothing if the result is a response object
$result = $e->getResult();
if ($result instanceof Response) {
return;
}
$router = $e->getRouter();
$match = $e->getRouteMatch();
// get url to the zfcuser/login route
$options['name'] = 'zfcuser/login';
$url = $router->assemble(array(), $options);
// Work out where were we trying to get to
$options['name'] = $match->getMatchedRouteName();
$redirect = $router->assemble($match->getParams(), $options);
// set up response to redirect to login page
$response = $e->getResponse();
if (!$response) {
$response = new HttpResponse();
$e->setResponse($response);
}
$app = $e->getParam('application');
$sm = $app->getServiceManager();
/* @var \BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider */
$identity = $sm->get('BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider');
$roles = $identity->getIdentityRoles();
$has_roles = false;
if (is_array($roles)) {
if (count($roles) > 0 && $roles[0] != 'guest')
$has_roles = true;
}
if ($has_roles) {
$response->getHeaders()->addHeaderLine('Location', '/');
$response->setStatusCode(302);
$flash = $sm->get('ControllerPluginManager')->get('flashMessenger');
$flash->addErrorMessage('You are not authorized to access this route');
}
else {
$response->getHeaders()->addHeaderLine('Location', $url . '?redirect=' . $redirect);
$response->setStatusCode(302);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment