|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Symfony package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Fabien Potencier <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace App\Security; |
|
13
|
|
|
|
|
14
|
|
|
use App\Entity\Post; |
|
15
|
|
|
use App\Entity\User; |
|
16
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
|
17
|
|
|
use Symfony\Component\Security\Core\Authorization\Voter\Voter; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* It grants or denies permissions for actions related to blog posts (such as |
|
21
|
|
|
* showing, editing and deleting posts). |
|
22
|
|
|
* |
|
23
|
|
|
* See https://symfony.com/doc/current/security/voters.html |
|
24
|
|
|
* |
|
25
|
|
|
* @author Yonel Ceruto <[email protected]> |
|
26
|
|
|
*/ |
|
27
|
|
|
class PostVoter extends Voter |
|
28
|
|
|
{ |
|
29
|
|
|
// Defining these constants is overkill for this simple application, but for real |
|
30
|
|
|
// applications, it's a recommended practice to avoid relying on "magic strings" |
|
31
|
|
|
const SHOW = 'show'; |
|
32
|
|
|
const EDIT = 'edit'; |
|
33
|
|
|
const DELETE = 'delete'; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* {@inheritdoc} |
|
37
|
|
|
*/ |
|
38
|
16 |
|
protected function supports($attribute, $subject): bool |
|
39
|
|
|
{ |
|
40
|
|
|
// this voter is only executed for three specific permissions on Post objects |
|
41
|
16 |
|
return $subject instanceof Post && in_array($attribute, [self::SHOW, self::EDIT, self::DELETE], true); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* {@inheritdoc} |
|
46
|
|
|
*/ |
|
47
|
5 |
|
protected function voteOnAttribute($attribute, $post, TokenInterface $token): bool |
|
48
|
|
|
{ |
|
49
|
5 |
|
$user = $token->getUser(); |
|
50
|
|
|
|
|
51
|
|
|
// the user must be logged in; if not, deny permission |
|
52
|
5 |
|
if (!$user instanceof User) { |
|
53
|
1 |
|
return false; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
// the logic of this voter is pretty simple: if the logged user is the |
|
57
|
|
|
// author of the given blog post, grant permission; otherwise, deny it. |
|
58
|
|
|
// (the supports() method guarantees that $post is a Post object) |
|
59
|
4 |
|
return $user === $post->getAuthor(); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|