Completed
Push — Recipes ( c0466a...7632b6 )
by Laurent
04:22
created

EasyAdminSecurityEventSubscriber   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 38
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 8 1
A isAuthorized() 0 16 4
1
<?php
2
namespace App\Security;
3
4
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\EventDispatcher\GenericEvent;
7
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
8
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
9
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
10
11
class EasyAdminSecurityEventSubscriber implements EventSubscriberInterface
12
{
13
    private $decisionManager;
14
    private $token;
15
16
    public function __construct(AccessDecisionManagerInterface $decisionManager, TokenStorageInterface $token)
17
    {
18
        $this->decisionManager = $decisionManager;
19
        $this->token = $token;
20
    }
21
22
    public static function getSubscribedEvents()
23
    {
24
        return [
25
            EasyAdminEvents::PRE_LIST => ['isAuthorized'],
26
            EasyAdminEvents::PRE_EDIT => ['isAuthorized'],
27
            EasyAdminEvents::PRE_DELETE => ['isAuthorized'],
28
            EasyAdminEvents::PRE_NEW => ['isAuthorized'],
29
            EasyAdminEvents::PRE_SHOW => ['isAuthorized'],
30
        ];
31
    }
32
33
    public function isAuthorized(GenericEvent $event)
34
    {
35
        $entityConfig = $event['entity'];
36
37
        $action = $event->getArgument('request')->query->get('action');
38
39
        if (!array_key_exists('permissions', $entityConfig) ||
40
            !array_key_exists($action, $entityConfig['permissions'])
41
        ) {
42
            return;
43
        }
44
45
        $authorizedRoles = $entityConfig['permissions']['action'];
46
47
        if (!$this->decisionManager->decide($this->token->getToken(), $authorizedRoles)) {
0 ignored issues
show
Bug introduced by
It seems like $this->token->getToken() can also be of type null; however, parameter $token of Symfony\Component\Securi...agerInterface::decide() does only seem to accept Symfony\Component\Securi...on\Token\TokenInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

47
        if (!$this->decisionManager->decide(/** @scrutinizer ignore-type */ $this->token->getToken(), $authorizedRoles)) {
Loading history...
48
            throw new AccessDeniedException();
49
        }
50
    }
51
}
52