/
CustomerVoter.php
124 lines (103 loc) · 3.13 KB
/
CustomerVoter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Voter;
use App\Entity\Customer;
use App\Entity\Team;
use App\Entity\User;
use App\Security\RolePermissionManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* A voter to check authorization on Customers.
*/
final class CustomerVoter extends Voter
{
/**
* supported attributes/rules based on the given customer
*/
private const ALLOWED_ATTRIBUTES = [
'view',
'create',
'edit',
'budget',
'delete',
'permissions',
'comments',
'comments_create',
'details',
'access',
];
private $permissionManager;
public function __construct(RolePermissionManager $permissionManager)
{
$this->permissionManager = $permissionManager;
}
/**
* @param string $attribute
* @param Customer $subject
* @return bool
*/
protected function supports($attribute, $subject)
{
if (!($subject instanceof Customer)) {
return false;
}
if (!\in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param Customer $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
// this is a virtual permission, only meant to be used by developer
// it checks if access to the given customer is potentially possible
if ($attribute === 'access') {
if ($subject->getTeams()->count() === 0) {
return true;
}
foreach ($subject->getTeams() as $team) {
if ($user->isInTeam($team)) {
return true;
}
}
return false;
}
if ($this->permissionManager->hasRolePermission($user, $attribute . '_customer')) {
return true;
}
// those cannot be assigned to teams
if (\in_array($attribute, ['create', 'delete'])) {
return false;
}
$hasTeamleadPermission = $this->permissionManager->hasRolePermission($user, $attribute . '_teamlead_customer');
$hasTeamPermission = $this->permissionManager->hasRolePermission($user, $attribute . '_team_customer');
if (!$hasTeamleadPermission && !$hasTeamPermission) {
return false;
}
/** @var Team $team */
foreach ($subject->getTeams() as $team) {
if ($hasTeamleadPermission && $user->isTeamleadOf($team)) {
return true;
}
if ($hasTeamPermission && $user->isInTeam($team)) {
return true;
}
}
return false;
}
}