|
1
|
|
|
<?php |
|
2
|
|
|
namespace AppBundle\Security; |
|
3
|
|
|
|
|
4
|
|
|
use AppBundle\Entity\Node; |
|
5
|
|
|
use AppBundle\Entity\User; |
|
6
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
|
7
|
|
|
use Symfony\Component\Security\Core\Authorization\Voter\Voter; |
|
8
|
|
|
|
|
9
|
|
|
class NodeVoter extends Voter |
|
10
|
|
|
{ |
|
11
|
|
|
const EDIT = 'edit'; |
|
12
|
|
|
const VIEW = 'r'; |
|
13
|
|
|
const WRITE = 'w'; |
|
14
|
|
|
|
|
15
|
|
|
/** @inheritdoc */ |
|
16
|
|
|
protected function supports($attribute, $subject) |
|
17
|
|
|
{ |
|
18
|
|
|
if (!in_array($attribute, [static::VIEW, static::WRITE])) { |
|
19
|
|
|
return false; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
if (!$subject instanceof Node) { |
|
23
|
|
|
return false; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
return true; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @param string $attribute |
|
31
|
|
|
* @param mixed $subject |
|
32
|
|
|
* @param TokenInterface $token |
|
33
|
|
|
* |
|
34
|
|
|
* @return bool |
|
35
|
|
|
*/ |
|
36
|
|
|
protected function voteOnAttribute($attribute, $subject, TokenInterface $token) |
|
37
|
|
|
{ |
|
38
|
|
|
/** |
|
39
|
|
|
* @var Node $node |
|
40
|
|
|
* @var User $user |
|
41
|
|
|
*/ |
|
42
|
|
|
$node = $subject; |
|
43
|
|
|
$user = $token->getUser(); |
|
44
|
|
|
|
|
45
|
|
|
// User must be logged in if node does not have external access |
|
46
|
|
|
if (!$node->hasExternalAccess() && !$user instanceof User) { |
|
47
|
|
|
return false; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
switch ($attribute) { |
|
51
|
|
|
case self::VIEW: |
|
52
|
|
|
return $this->canView($node, $user); |
|
53
|
|
|
case self::EDIT: |
|
54
|
|
|
return $this->canEdit($node, $user); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
throw new \LogicException(sprintf('Invalid voter attribute "%s"', $attribute)); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
private function canView(Node $node, User $user = null) |
|
61
|
|
|
{ |
|
62
|
|
|
// Unauthenticated users can view nodes with enabled external access |
|
63
|
|
|
if ($user === null && $node->hasExternalAccess()) { |
|
64
|
|
|
return true; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
// check ban |
|
68
|
|
|
|
|
69
|
|
|
if ($node->isPrivate()) { |
|
70
|
|
|
// check node access; |
|
71
|
|
|
return false; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
if ($node->isPublic() || $node->isModerated()) { |
|
75
|
|
|
return true; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
return false; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
private function canEdit(Node $node, User $user) |
|
82
|
|
|
{ |
|
83
|
|
|
if ($node->getCreatedBy() === $user->getId()) { |
|
84
|
|
|
return true; |
|
85
|
|
|
} |
|
86
|
|
|
|
|
87
|
|
|
return false; |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|