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); | |
} | |
} | |
} |
It's probably a bit of a micro-optimisation, but you don't really need to retrieve the $route
unless you enter that if
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is preferable for fine-grain control over route security, since maintaining a set of patterns in the security config often meant we had to keep paths in multiple places in sync with each other. I think it'd also be great to allow role restrictions to be inherited when routes are imported, by allowing
_role
to be specified on theimport
. In the case of importing a routing file that defined/backend/products
and related routes, we could require the product-editor role once.