WhitelistController::replaceWhitelist()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupMiddleware\ManagementBundle\Controller;
20
21
use DateTime;
22
use Ramsey\Uuid\Uuid;
23
use Surfnet\Stepup\Helper\JsonHelper;
24
use Surfnet\StepupMiddleware\ApiBundle\Identity\Service\WhitelistService;
25
use Surfnet\StepupMiddleware\CommandHandlingBundle\Command\AbstractCommand;
26
use Surfnet\StepupMiddleware\CommandHandlingBundle\Exception\ForbiddenException;
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\AddToWhitelistCommand;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\RemoveFromWhitelistCommand;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ReplaceWhitelistCommand;
30
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\TransactionAwarePipeline;
31
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
32
use Symfony\Component\HttpFoundation\JsonResponse;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
35
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
36
37
/**
38
 * @SuppressWarnings("PHPMD.CouplingBetweenObjects")
39
 */
40
class WhitelistController extends AbstractController
41
{
42
    public function __construct(
43
        /**
44
         * @return TransactionAwarePipeline
45
         */
46
        private readonly TransactionAwarePipeline $pipeline,
47
        private readonly WhitelistService $whitelistService,
48
    ) {
49
    }
50
51
    public function replaceWhitelist(Request $request): JsonResponse
52
    {
53
        $this->denyAccessUnlessGranted('ROLE_MANAGEMENT');
54
55
        $command = new ReplaceWhitelistCommand();
56
        $command->UUID = (string)Uuid::uuid4();
57
        $command->institutions = $this->getInstitutionsFromBody($request);
58
59
        return $this->handleCommand($request, $command);
60
    }
61
62
    public function addToWhitelist(Request $request): JsonResponse
63
    {
64
        $this->denyAccessUnlessGranted('ROLE_MANAGEMENT');
65
66
        $command = new AddToWhitelistCommand();
67
        $command->UUID = (string)Uuid::uuid4();
68
        $command->institutionsToBeAdded = $this->getInstitutionsFromBody($request);
69
70
        return $this->handleCommand($request, $command);
71
    }
72
73
    public function removeFromWhitelist(Request $request): JsonResponse
74
    {
75
        $this->denyAccessUnlessGranted('ROLE_MANAGEMENT');
76
77
        $command = new RemoveFromWhitelistCommand();
78
        $command->UUID = (string)Uuid::uuid4();
79
        $command->institutionsToBeRemoved = $this->getInstitutionsFromBody($request);
80
81
        return $this->handleCommand($request, $command);
82
    }
83
84
    public function showWhitelist(): JsonResponse
85
    {
86
        $entries = $this->whitelistService->getAllEntries();
87
88
        return new JsonResponse(['institutions' => $entries->getValues()]);
89
    }
90
91
    private function handleCommand(Request $request, AbstractCommand $command): JsonResponse
92
    {
93
        try {
94
            $this->pipeline->process($command);
95
        } catch (ForbiddenException $e) {
96
            throw new AccessDeniedHttpException(
97
                sprintf('Processing of command "%s" is forbidden for this client', $command),
98
                $e,
99
            );
100
        }
101
102
        $serverName = $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR');
103
104
        return new JsonResponse([
105
            'status' => 'OK',
106
            'processed_by' => $serverName,
107
            'applied_at' => (new DateTime())->format(DateTime::ISO8601),
108
        ]);
109
    }
110
111
    /**
112
     * @return array
113
     */
114
    private function getInstitutionsFromBody(Request $request): array
115
    {
116
        $decoded = JsonHelper::decode($request->getContent());
117
118
        if (!isset($decoded['institutions']) || !is_array($decoded['institutions'])) {
119
            throw new BadRequestHttpException(
120
                'Request must contain json object with property "institutions" containing an array of institutions',
121
            );
122
        }
123
124
        return $decoded['institutions'];
125
    }
126
}
127