Created
March 2, 2012 21:10
-
-
Save kriswallsmith/1961437 to your computer and use it in GitHub Desktop.
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 OpenSky\Bundle\MainBundle\Listener; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\Security\Core\Exception\AccessDeniedException; | |
use Symfony\Component\Security\Core\SecurityContextInterface; | |
/** | |
* Listens to kernel.request after the router and checks required role. | |
*/ | |
class RouteSecurityListener | |
{ | |
private $security; | |
public function __construct(SecurityContextInterface $security) | |
{ | |
$this->security = $security; | |
} | |
public function onKernelRequest(GetResponseEvent $event) | |
{ | |
$request = $event->getRequest(); | |
$route = $request->attributes->get('_route'); | |
$role = $request->attributes->get('_role'); | |
if ($role && !$this->security->isGranted($role)) { | |
$message = $route | |
? sprintf('The "%s" route requires the "%s" role.', $route, $role) | |
: sprintf('This route requires the "%s" role.', $role); | |
throw new AccessDeniedException($message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's probably a bit of a micro-optimisation, but you don't really need to retrieve the
$route
unless you enter thatif
.