1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\Security\Authorization; |
6
|
|
|
|
7
|
|
|
use Chubbyphp\Security\UserInterface; |
8
|
|
|
|
9
|
|
|
final class RoleAuthorization implements AuthorizationInterface |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var array |
13
|
|
|
*/ |
14
|
|
|
private $roleHierarchyResolver; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param RoleHierarchyResolverInterface $roleHierarchyResolver |
18
|
|
|
*/ |
19
|
|
|
public function __construct(RoleHierarchyResolverInterface $roleHierarchyResolver) |
20
|
|
|
{ |
21
|
|
|
$this->roleHierarchyResolver = $roleHierarchyResolver; |
|
|
|
|
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param UserInterface $user |
26
|
|
|
* @param mixed $attributes |
27
|
|
|
* @param OwnedByUserModelInterface|null $model |
28
|
|
|
* |
29
|
|
|
* @return bool |
30
|
|
|
*/ |
31
|
|
|
public function isGranted(UserInterface $user, $attributes, OwnedByUserModelInterface $model = null): bool |
32
|
|
|
{ |
33
|
|
|
if (null !== $model && $user->getId() !== $model->getOwnedByUserId()) { |
34
|
|
|
return false; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$owningRoles = $this->getOwningRoles($user); |
38
|
|
|
$neededRoles = $this->getNeededRoles($attributes); |
39
|
|
|
|
40
|
|
|
return $this->checkRoles($owningRoles, $neededRoles); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param UserInterface $user |
45
|
|
|
* |
46
|
|
|
* @return array |
47
|
|
|
*/ |
48
|
|
|
private function getOwningRoles(UserInterface $user): array |
49
|
|
|
{ |
50
|
|
|
return $this->roleHierarchyResolver->resolve($user->getRoles()); |
|
|
|
|
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param mixed $attributes |
55
|
|
|
* |
56
|
|
|
* @return array |
57
|
|
|
*/ |
58
|
|
|
private function getNeededRoles($attributes): array |
59
|
|
|
{ |
60
|
|
|
return is_scalar($attributes) ? [$attributes] : $attributes; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param array $owningRoles |
65
|
|
|
* @param array $neededRoles |
66
|
|
|
* |
67
|
|
|
* @return bool |
68
|
|
|
*/ |
69
|
|
|
private function checkRoles(array $owningRoles, array $neededRoles): bool |
70
|
|
|
{ |
71
|
|
|
foreach ($neededRoles as $neededRole) { |
72
|
|
|
if (!in_array($neededRole, $owningRoles, true)) { |
73
|
|
|
return false; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return true; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..