|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace App\Security\Voter; |
|
6
|
|
|
|
|
7
|
|
|
use App\Entity\Property; |
|
8
|
|
|
use LogicException; |
|
9
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
|
10
|
|
|
use Symfony\Component\Security\Core\Authorization\Voter\Voter; |
|
11
|
|
|
use Symfony\Component\Security\Core\Security; |
|
12
|
|
|
use Symfony\Component\Security\Core\User\UserInterface; |
|
13
|
|
|
|
|
14
|
|
|
final class PropertyVoter extends Voter |
|
15
|
|
|
{ |
|
16
|
|
|
private Security $security; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct(Security $security) |
|
19
|
|
|
{ |
|
20
|
|
|
$this->security = $security; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param string $attribute |
|
25
|
|
|
*/ |
|
26
|
|
|
protected function supports($attribute, $subject): bool |
|
27
|
|
|
{ |
|
28
|
|
|
return \in_array($attribute, ['PROPERTY_EDIT', 'PROPERTY_VIEW'], true) |
|
29
|
|
|
&& $subject instanceof Property; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool |
|
33
|
|
|
{ |
|
34
|
|
|
/** @var Property $property */ |
|
35
|
|
|
$property = $subject; |
|
36
|
|
|
|
|
37
|
|
|
return match ($attribute) { |
|
38
|
|
|
'PROPERTY_VIEW' => $this->canView($property, $token), |
|
39
|
|
|
'PROPERTY_EDIT' => $this->canEdit($property, $token), |
|
40
|
|
|
default => throw new LogicException('This code should not be reached!'), |
|
41
|
|
|
}; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
private function canView(Property $property, TokenInterface $token): bool |
|
45
|
|
|
{ |
|
46
|
|
|
// if they can edit, they can view |
|
47
|
|
|
if ($this->canEdit($property, $token)) { |
|
48
|
|
|
return true; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
return $property->isPublished(); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
private function canEdit(Property $property, TokenInterface $token): bool |
|
55
|
|
|
{ |
|
56
|
|
|
$user = $token->getUser(); |
|
57
|
|
|
// if the user is anonymous, do not grant access |
|
58
|
|
|
if (!$user instanceof UserInterface) { |
|
59
|
|
|
return false; |
|
60
|
|
|
} elseif ($this->security->isGranted('ROLE_ADMIN')) { |
|
61
|
|
|
return true; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return $user === $property->getAuthor() && $user->isVerified(); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|