1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ae\FeatureBundle\Security; |
4
|
|
|
|
5
|
|
|
use Ae\FeatureBundle\Entity\Feature; |
6
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
7
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; |
8
|
|
|
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; |
9
|
|
|
use Symfony\Component\Security\Core\User\UserInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Controls access to a Feature. |
13
|
|
|
* |
14
|
|
|
* @author Carlo Forghieri <[email protected]> |
15
|
|
|
*/ |
16
|
|
|
class FeatureSecurity |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @param AuthorizationCheckerInterface |
20
|
|
|
*/ |
21
|
|
|
protected $context; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param TokenStorageInterface |
25
|
|
|
*/ |
26
|
|
|
private $storage; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string |
30
|
|
|
*/ |
31
|
|
|
private $providerKey; |
32
|
|
|
|
33
|
8 |
|
public function __construct( |
34
|
|
|
AuthorizationCheckerInterface $context, |
35
|
|
|
TokenStorageInterface $storage, |
36
|
|
|
string $providerKey |
37
|
|
|
) { |
38
|
8 |
|
$this->context = $context; |
39
|
8 |
|
$this->storage = $storage; |
40
|
8 |
|
$this->providerKey = $providerKey; |
41
|
8 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @return bool |
45
|
|
|
*/ |
46
|
6 |
|
public function isGranted(Feature $feature) |
47
|
|
|
{ |
48
|
|
|
// feature is enabled without required roles |
49
|
|
|
// there's no need to check on user roles |
50
|
6 |
|
if (!$feature->requiresRoleCheck()) { |
51
|
2 |
|
return $feature->isEnabled(); |
52
|
|
|
} |
53
|
|
|
|
54
|
4 |
|
if (!$feature->isEnabled()) { |
55
|
1 |
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
3 |
|
if ($feature->getRole()) { |
59
|
2 |
|
if (!$this->context->isGranted($feature->getRole())) { |
60
|
|
|
return false; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
3 |
|
if ('' !== trim($feature->getParentRole())) { |
65
|
1 |
|
if (!$this->context->isGranted($feature->getParentRole())) { |
66
|
1 |
|
return false; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
2 |
|
return true; |
71
|
|
|
} |
72
|
|
|
|
73
|
2 |
|
public function isGrantedForUser(Feature $feature, UserInterface $user): bool |
74
|
|
|
{ |
75
|
2 |
|
$oldToken = $this->storage->getToken(); |
76
|
|
|
|
77
|
2 |
|
$this->storage->setToken(new UsernamePasswordToken( |
78
|
2 |
|
$user, |
79
|
2 |
|
null, |
80
|
2 |
|
$this->providerKey, |
81
|
2 |
|
$user->getRoles() |
82
|
|
|
)); |
83
|
|
|
|
84
|
2 |
|
$granted = $this->isGranted($feature); |
85
|
|
|
|
86
|
2 |
|
$this->storage->setToken($oldToken); |
87
|
|
|
|
88
|
2 |
|
return $granted; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|