Passed
Push — master ( 3ec415...9f2f47 )
by Daniel
16:25
created

DenyAccessListener::onPreDeserialize()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 12
nc 6
nop 1
dl 0
loc 22
ccs 0
cts 13
cp 0
crap 42
rs 9.2222
c 1
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[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
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\Security\EventListener;
15
16
use ApiPlatform\Core\Api\IriConverterInterface;
17
use ApiPlatform\Core\Util\RequestAttributesExtractor;
18
use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent;
19
use Silverback\ApiComponentsBundle\Entity\Core\AbstractPageData;
20
use Silverback\ApiComponentsBundle\Repository\Core\AbstractPageDataRepository;
21
use Silverback\ApiComponentsBundle\Repository\Core\RouteRepository;
22
use Symfony\Component\HttpFoundation\Request;
23
use Symfony\Component\HttpFoundation\Response;
24
use Symfony\Component\HttpKernel\Event\RequestEvent;
25
use Symfony\Component\HttpKernel\HttpKernelInterface;
26
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
27
use Symfony\Component\Security\Core\Security;
28
29
/**
30
 * This will NOT restrict access to components fetched as a collection. As recomended by API Platform best practices, that should
31
 * be implemented in a Doctrine extension by the application developer.
32
 *
33
 * @author Daniel West <[email protected]>
34
 */
35
final class DenyAccessListener
36
{
37
    private RouteRepository $routeRepository;
38
    private AbstractPageDataRepository $pageDataRepository;
39
    private Security $security;
40
    private IriConverterInterface $iriConverter;
41
    private HttpKernelInterface $httpKernel;
42
43
    public function __construct(RouteRepository $routeRepository, AbstractPageDataRepository $pageDataRepository, Security $security, IriConverterInterface $iriConverter, HttpKernelInterface $httpKernel)
44
    {
45
        $this->routeRepository = $routeRepository;
46
        $this->pageDataRepository = $pageDataRepository;
47
        $this->security = $security;
48
        $this->iriConverter = $iriConverter;
49
        $this->httpKernel = $httpKernel;
50
    }
51
52
    public function onPreDeserialize(RequestEvent $event)
53
    {
54
        $request = $event->getRequest();
55
56
        if (!$attributes = RequestAttributesExtractor::extractAttributes($request)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $attributes is dead and can be removed.
Loading history...
57
            return;
58
        }
59
60
        $resource = $request->attributes->get('data');
61
62
        if ($resource instanceof AbstractComponent) {
63
            if ($this->isComponentAccessible($resource, $request)) {
64
                return;
65
            }
66
            throw new AccessDeniedException('Component access denied.');
67
        }
68
69
        if ($resource instanceof AbstractPageData) {
70
            if (false !== $this->isPageDataAllowedByRoute($resource)) {
71
                return;
72
            }
73
            throw new AccessDeniedException('Page data access denied.');
74
        }
75
    }
76
77
    private function isComponentAccessible(AbstractComponent $component, Request $request): bool
78
    {
79
        return true === ($isRouteAllowed = $this->isComponentAllowedByRoute($component)) ||
80
            true === ($isPageDataAllowed = $this->isComponentAllowedByPageDataSecurityPolicy($component, $request)) ||
81
            (null === $isRouteAllowed && null === $isPageDataAllowed);
82
    }
83
84
    private function isComponentAllowedByPageDataSecurityPolicy(AbstractComponent $component, Request $request): ?bool
85
    {
86
        // abstain - we need request
87
        if (!$attributes = RequestAttributesExtractor::extractAttributes($request)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $attributes is dead and can be removed.
Loading history...
88
            return null;
89
        }
90
91
        $pageDataResources = $this->pageDataRepository->findByComponent($component);
92
93
        // abstain - no results to say yay or nay
94
        if (!\count($pageDataResources)) {
95
            return null;
96
        }
97
98
        foreach ($pageDataResources as $pageDataResource) {
99
            $path = $this->iriConverter->getIriFromItem($pageDataResource);
100
101
            $subRequest = Request::create(
102
                $path,
103
                Request::METHOD_GET,
104
                [],
105
                $request->cookies->all(),
106
                [],
107
                $request->server->all(),
108
                null
109
            );
110
111
            try {
112
                $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
113
114
                return true;
115
            } catch (\Exception $e) {
116
                if (\in_array($e->getCode(), [Response::HTTP_UNAUTHORIZED, Response::HTTP_FORBIDDEN], true)) {
117
                    continue;
118
                }
119
                throw $e;
120
            }
121
        }
122
123
        return false;
124
    }
125
126
    private function isComponentAllowedByRoute(AbstractComponent $component): ?bool
127
    {
128
        $routes = $this->routeRepository->findByComponent($component);
129
130
        if (!\count($routes)) {
131
            return null;
132
        }
133
134
        foreach ($routes as $route) {
135
            if ($this->security->isGranted($route)) {
136
                return true;
137
            }
138
        }
139
140
        return false;
141
    }
142
143
    private function isPageDataAllowedByRoute(AbstractPageData $pageData): ?bool
144
    {
145
        $route = $this->routeRepository->findByPageData($pageData);
146
147
        // abstain - no route to check
148
        if (!$route) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $route of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
149
            return null;
150
        }
151
152
        return $this->security->isGranted($route);
153
    }
154
}
155