|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony CMF package. |
| 5 | + * |
| 6 | + * (c) 2011-2017 Symfony CMF |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Cmf\Bundle\ResourceRestBundle\Security; |
| 13 | + |
| 14 | +use Symfony\Cmf\Bundle\ResourceRestBundle\Controller\ResourceController; |
| 15 | +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
| 16 | +use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; |
| 17 | +use Symfony\Component\Security\Core\Authorization\Voter\Voter; |
| 18 | + |
| 19 | +/** |
| 20 | + * @author Wouter de Jong <[email protected]> |
| 21 | + */ |
| 22 | +class ResourcePathVoter extends Voter |
| 23 | +{ |
| 24 | + private $accessDecisionManager; |
| 25 | + private $accessMap; |
| 26 | + |
| 27 | + public function __construct(AccessDecisionManagerInterface $accessDecisionManager, array $accessMap) |
| 28 | + { |
| 29 | + $this->accessDecisionManager = $accessDecisionManager; |
| 30 | + $this->accessMap = $accessMap; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * {@inheritdoc} |
| 35 | + */ |
| 36 | + protected function supports($attribute, $subject) |
| 37 | + { |
| 38 | + return in_array($attribute, [ResourceController::ROLE_RESOURCE_READ, ResourceController::ROLE_RESOURCE_WRITE]) |
| 39 | + && is_array($subject) && isset($subject['repository_name']) && isset($subject['path']); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * {@inheritdoc} |
| 44 | + */ |
| 45 | + protected function voteOnAttribute($attribute, $subject, TokenInterface $token) |
| 46 | + { |
| 47 | + foreach ($this->accessMap as $rule) { |
| 48 | + if (!$this->ruleMatches($rule, $attribute, $subject)) { |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + if ($this->accessDecisionManager->decide($token, $rule['require'])) { |
| 53 | + return true; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + private function ruleMatches($rule, $attribute, $subject) |
| 61 | + { |
| 62 | + if (!in_array($attribute, $rule['attributes'])) { |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + if (null !== $rule['repository'] && $rule['repository'] !== $subject['repository_name']) { |
| 67 | + return false; |
| 68 | + } |
| 69 | + |
| 70 | + if (!preg_match('{'.$rule['pattern'].'}', $subject['path'])) { |
| 71 | + return false; |
| 72 | + } |
| 73 | + |
| 74 | + return true; |
| 75 | + } |
| 76 | +} |
0 commit comments