Created
October 31, 2012 13:43
-
-
Save tentacode/3987103 to your computer and use it in GitHub Desktop.
Twig Extension to grant access based on path
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
services: | |
tentacode_foobar_user.twig.user_extension: | |
class: Tentacode\Foobar\UserBundle\Twig\UserExtension | |
tags: | |
- { name: twig.extension } | |
arguments: | |
- @security.access_map | |
- @security.context | |
- @security.access.decision_manager |
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 Tentacode\Foobar\UserBundle\Twig; | |
use Twig_Extension; | |
use Twig_Function_Method; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\Security\Http\AccessMap; | |
use Symfony\Component\Security\Core\SecurityContext; | |
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager; | |
class UserExtension extends Twig_Extension | |
{ | |
protected $map; | |
protected $securityContext; | |
protected $adm; | |
public function __construct(AccessMap $map, SecurityContext $securityContext, AccessDecisionManager $adm) | |
{ | |
$this->map = $map; | |
$this->securityContext = $securityContext; | |
$this->adm = $adm; | |
} | |
public function getFunctions() | |
{ | |
return array( | |
'access_granted' => new Twig_Function_Method($this, 'isAccessGranted'), | |
); | |
} | |
public function isAccessGranted($path) | |
{ | |
if (null === $token = $this->securityContext->getToken()) { | |
return true; | |
} | |
if(preg_match('/^\/[a-z_]+\.php(.*)$/', $path, $result)) { | |
$path = $result[1]; | |
} | |
$request = Request::create($path); | |
list($attributes, $channel) = $this->map->getPatterns($request); | |
if (null === $attributes) { | |
return true; | |
} | |
if (!$token->isAuthenticated()) { | |
return false; | |
} | |
return $this->adm->decide($token, $attributes, $request); | |
} | |
public function getName() | |
{ | |
return 'user'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment