Last active
February 23, 2017 10:51
-
-
Save mickaelandrieu/15f2cd3fd7ca465fbb6b to your computer and use it in GitHub Desktop.
Redirect to another action, regarding to the role (Symfony)
This file contains hidden or 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 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 <[email protected]> | |
*/ | |
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