Skip to content

Instantly share code, notes, and snippets.

@mickaelandrieu
Last active February 23, 2017 10:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mickaelandrieu/15f2cd3fd7ca465fbb6b to your computer and use it in GitHub Desktop.
Save mickaelandrieu/15f2cd3fd7ca465fbb6b to your computer and use it in GitHub Desktop.
Redirect to another action, regarding to the role (Symfony)
<?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* Defines the method that 'listens' to the 'kernel.request' event, which is
* triggered whenever a request is handled by the application.
* See http://symfony.com/doc/current/book/internals.html#kernel-request-event
*
* Tip: listeners are common in Symfony applications, but this particular listener
* is too advanced and too specific for the demo application needs. For more common
* examples see http://symfony.com/doc/current/cookbook/service_container/event_listener.html
*
* @author Mickaël Andrieu <andrieu.travail@gmail.com>
*/
class RedirectToAdminZoneListener
{
private $authorizationChecker;
private $router;
public function __construct(AuthorizationCheckerInterface $authorizationChecker, Router $router)
{
$this->authorizationChecker = $authorizationChecker;
$this->router = $router;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$route = $event->getRequest()->get('_route');
if ($this->authorizationChecker->isGranted('ROLE_ADMIN') && $route == 'homepage') {
$response = new RedirectResponse($this->router->generate('homepage_admin'));
$event->setResponse($response);
}
}
}
}
/**
* # app/config/config.yml (or inside your services.yml)
* services:
* demo.redirect.admin.action_listener:
* class: Acme\AppBundle\EventListener\RedirectToAdminZoneListener
* arguments: [ @security.authorization_checker, @router ]
* tags:
* - { name: kernel.event_listener, event: kernel.request method: onKernelRequest }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment