Passed
Pull Request — master (#9)
by Pavel
12:36
created

SecurityListener::getVariables()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 2.0046

Importance

Changes 0
Metric Value
dl 0
loc 29
c 0
b 0
f 0
ccs 17
cts 19
cp 0.8947
rs 8.8571
cc 2
eloc 18
nc 2
nop 1
crap 2.0046
1
<?php
2
3
/*
4
 * Copyright (c) 2010-2017 Fabien Potencier
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is furnished
11
 * to do so, subject to t * *he following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in all
14
 * copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 *
24
 */
25
26
namespace Bankiru\Api\Rpc\Listener;
27
28
use Bankiru\Api\Rpc\Event\FilterControllerEvent;
29
use Bankiru\Api\Rpc\Http\RequestInterface;
30
use Bankiru\Api\Rpc\RpcEvents;
31
use Bankiru\Api\Rpc\RpcRequestInterface;
32
use Sensio\Bundle\FrameworkExtraBundle\Security\ExpressionLanguage;
33
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
34
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
35
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
36
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
37
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
38
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
39
40
/**
41
 * SecurityListener handles security restrictions on controllers.
42
 *
43
 * @author Fabien Potencier <[email protected]>
44
 */
45
final class SecurityListener implements EventSubscriberInterface
46
{
47
    private $tokenStorage;
48
    private $authChecker;
49
    private $language;
50
    private $trustResolver;
51
    private $roleHierarchy;
52
53 8
    public function __construct(
54
        TokenStorageInterface $tokenStorage,
55
        AuthorizationCheckerInterface $authChecker,
56
        ExpressionLanguage $language = null,
57
        AuthenticationTrustResolverInterface $trustResolver = null,
58
        RoleHierarchyInterface $roleHierarchy = null
59
    ) {
60 8
        $this->tokenStorage  = $tokenStorage;
61 8
        $this->authChecker   = $authChecker;
62 8
        $this->language      = $language;
63 8
        $this->trustResolver = $trustResolver;
64 8
        $this->roleHierarchy = $roleHierarchy;
65 8
    }
66
67 8
    public function onKernelController(FilterControllerEvent $event)
68
    {
69 8
        $request = $event->getRequest();
70 8
        if (!$configuration = $request->getAttributes()->get('_security')) {
71 6
            return;
72
        }
73
74 2
        if (null === $this->tokenStorage || null === $this->trustResolver) {
75
            throw new \LogicException('To use the @Security tag, you need to install the Symfony Security bundle.');
76
        }
77
78 2
        if (null === $this->tokenStorage->getToken()) {
79
            throw new \LogicException('To use the @Security tag, your controller needs to be behind a firewall.');
80
        }
81
82 2
        if (null === $this->language) {
83
            throw new \LogicException(
84
                'To use the @Security tag, you need to use the Security component 2.4 or newer and install the ExpressionLanguage component.'
85
            );
86
        }
87
88 2
        if (!$this->language->evaluate($configuration->getExpression(), $this->getVariables($request))) {
89 1
            throw new AccessDeniedException(sprintf('Expression "%s" denied access.', $configuration->getExpression()));
90
        }
91 1
    }
92
93
    // code should be sync with Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter
94
95 1
    public static function getSubscribedEvents()
96
    {
97 1
        return [RpcEvents::CONTROLLER => ['onKernelController', -255]];
98
    }
99
100 2
    private function getVariables(RpcRequestInterface $request)
101
    {
102 2
        $token = $this->tokenStorage->getToken();
103
104 2
        if (null !== $this->roleHierarchy) {
105 2
            $roles = $this->roleHierarchy->getReachableRoles($token->getRoles());
106 2
        } else {
107
            $roles = $token->getRoles();
108
        }
109
110
        $variables = [
111 2
            'token'          => $token,
112 2
            'user'           => $token->getUser(),
113 2
            'object'         => $request,
114 2
            'request'        => $request,
115 2
            'roles'          => array_map(
116 2
                function ($role) {
117
                    return $role->getRole();
118 2
                },
119
                $roles
120 2
            ),
121 2
            'trust_resolver' => $this->trustResolver,
122
            // needed for the is_granted expression function
123 2
            'auth_checker'   => $this->authChecker,
124 2
        ];
125
126
        // controller variables should also be accessible
127 2
        return array_merge($request->getAttributes()->all(), $variables);
128
    }
129
}
130