Completed
Push — feature/implement-is-gssf-depr... ( 7e4593 )
by
unknown
10:41
created

VettingController   C

Complexity

Total Complexity 29

Size/Duplication

Total Lines 281
Duplicated Lines 4.98 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 29
c 6
b 0
f 0
lcom 1
cbo 19
dl 14
loc 281
rs 6.875

9 Methods

Rating   Name   Duplication   Size   Complexity  
C startProcedureAction() 0 116 12
A cancelProcedureAction() 4 14 2
C verifyIdentityAction() 10 84 9
A vettingCompletedAction() 0 4 1
A getSecondFactorService() 0 4 1
A getSecondFactorTypeService() 0 4 1
A getVettingService() 0 4 1
A getIdentity() 0 4 1
A getTranslator() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\StepupRa\RaBundle\Controller;
20
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
22
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
23
use Surfnet\StepupBundle\Value\SecondFactorType;
24
use Surfnet\StepupRa\RaBundle\Command\StartVettingProcedureCommand;
25
use Surfnet\StepupRa\RaBundle\Command\VerifyIdentityCommand;
26
use Surfnet\StepupRa\RaBundle\Exception\DomainException;
27
use Surfnet\StepupRa\RaBundle\Exception\RuntimeException;
28
use Surfnet\StepupRa\RaBundle\Security\Authentication\Token\SamlToken;
29
use Surfnet\StepupRa\RaBundle\Service\SecondFactorService;
30
use Surfnet\StepupRa\RaBundle\Service\VettingService;
31
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
32
use Symfony\Component\Form\FormError;
33
use Symfony\Component\Form\SubmitButton;
34
use Symfony\Component\HttpFoundation\Request;
35
use Symfony\Component\HttpFoundation\Response;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
use Symfony\Component\Translation\TranslatorInterface;
38
39
/**
40
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
41
 * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
42
 */
43
class VettingController extends Controller
44
{
45
    /**
46
     * @Template
47
     * @param Request $request
48
     * @return array|Response
49
     *
50
     * @SuppressWarnings(PHPMD.CyclomaticComplexity) https://www.pivotaltracker.com/story/show/135045063
51
     * @SuppressWarnings(PHPMD.NPathComplexity)      https://www.pivotaltracker.com/story/show/135045063
52
     */
53
    public function startProcedureAction(Request $request)
54
    {
55
        $this->denyAccessUnlessGranted(['ROLE_RA']);
56
        $logger = $this->get('logger');
57
58
        $logger->notice('Vetting Procedure Search started');
59
60
        $command = new StartVettingProcedureCommand();
61
62
        $form = $this->createForm('ra_start_vetting_procedure', $command)->handleRequest($request);
63
64
        if (!$form->isValid()) {
65
            $logger->notice('No search submitted, displaying search by registration code form');
66
67
            return ['form' => $form->createView()];
68
        }
69
70
        $secondFactor = $this->getSecondFactorService()
71
            ->findVerifiedSecondFactorByRegistrationCode($command->registrationCode);
72
73
        if ($secondFactor === null) {
74
            $form->addError(new FormError('ra.form.start_vetting_procedure.unknown_registration_code'));
75
            $logger->notice('Cannot start new vetting procedure, no second factor found');
76
77
            return ['form' => $form->createView()];
78
        }
79
80
        if (!$this->isGranted('ROLE_SRAA') && $secondFactor->institution !== $this->getIdentity()->institution) {
81
            $form->addError(new FormError('ra.form.start_vetting_procedure.different_institution_error'));
82
            $logger->notice(
83
                'Cannot start new vetting procedure, registrant belongs to a different institution than RA'
84
            );
85
86
            return ['form' => $form->createView()];
87
        }
88
89
        $enabledSecondFactors = $this->container->getParameter('surfnet_stepup_ra.enabled_second_factors');
90
        if (!in_array($secondFactor->type, $enabledSecondFactors, true)) {
91
            $logger->warning(
92
                sprintf(
93
                    'An RA attempted vetting of disabled second factor "%s" of type "%s"',
94
                    $secondFactor->id,
95
                    $secondFactor->type
96
                )
97
            );
98
99
            return $this
100
                ->render(
101
                    'SurfnetStepupRaRaBundle:Vetting:secondFactorTypeDisabled.html.twig',
102
                    ['secondFactorType' => $secondFactor->type]
103
                )
104
                ->setStatusCode(Response::HTTP_BAD_REQUEST);
105
        }
106
107
        /** @var SamlToken $token */
108
        $token = $this->get('security.token_storage')->getToken();
109
        $command->authorityId = $this->getIdentity()->id;
110
        $command->authorityLoa = $token->getLoa();
111
        $command->secondFactor = $secondFactor;
0 ignored issues
show
Documentation Bug introduced by
It seems like $secondFactor can also be of type false. However, the property $secondFactor is declared as type object<Surfnet\StepupMid...o\VerifiedSecondFactor>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
112
113
        if ($this->getVettingService()->isExpiredRegistrationCode($command)) {
114
            $form->addError(
115
                new FormError(
116
                    $this->getTranslator()
117
                        ->trans(
118
                            'ra.verify_identity.registration_code_expired',
119
                            [
120
                                '%self_service_url%' => $this->getParameter('surfnet_stepup_ra.self_service_url'),
121
                            ]
122
                        )
123
                )
124
            );
125
126
            $logger->notice(
127
                'Second factor registration code is expired',
128
                ['registration_requested_at' => $secondFactor->registrationRequestedAt->format('Y-m-d')]
129
            );
130
131
            return ['form' => $form->createView()];
132
        }
133
134
        if (!$this->getVettingService()->isLoaSufficientToStartProcedure($command)) {
135
            $form->addError(new FormError('ra.form.start_vetting_procedure.loa_insufficient'));
136
137
            $logger->notice('Cannot start new vetting procedure, Authority LoA is insufficient');
138
139
            return ['form' => $form->createView()];
140
        }
141
142
        $procedureId = $this->getVettingService()->startProcedure($command);
143
144
        $this->get('ra.procedure_logger')
145
            ->forProcedure($procedureId)
146
            ->notice(sprintf('Starting new Vetting Procedure for second factor of type "%s"', $secondFactor->type));
147
148
        $secondFactorType = new SecondFactorType($secondFactor->type);
149
        if ($secondFactorType->isYubikey()) {
150
            return $this->redirectToRoute('ra_vetting_yubikey_verify', ['procedureId' => $procedureId]);
151
        } elseif ($secondFactorType->isSms()) {
152
            return $this->redirectToRoute('ra_vetting_sms_send_challenge', ['procedureId' => $procedureId]);
153
        } elseif ($this->getSecondFactorTypeService()->isGssf($secondFactorType)) {
154
            return $this->redirectToRoute(
155
                'ra_vetting_gssf_initiate',
156
                [
157
                    'procedureId' => $procedureId,
158
                    'provider'    => $secondFactor->type
159
                ]
160
            );
161
        } elseif ($secondFactorType->isU2f()) {
162
            return $this->redirectToRoute('ra_vetting_u2f_start_authentication', ['procedureId' => $procedureId]);
163
        } else {
164
            throw new RuntimeException(
165
                sprintf('RA does not support vetting procedure for second factor type "%s"', $secondFactor->type)
166
            );
167
        }
168
    }
169
170
    public function cancelProcedureAction($procedureId)
171
    {
172
        $logger = $this->get('ra.procedure_logger')->forProcedure($procedureId);
173
174 View Code Duplication
        if (!$this->getVettingService()->hasProcedure($procedureId)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
175
            $logger->notice(sprintf('Vetting procedure "%s" not found', $procedureId));
176
            throw new NotFoundHttpException(sprintf('Vetting procedure "%s" not found', $procedureId));
177
        }
178
179
        $this->getVettingService()->cancelProcedure($procedureId);
180
        $this->addFlash('info', $this->get('translator')->trans('ra.vetting.flash.cancelled'));
181
182
        return $this->redirectToRoute('ra_vetting_search');
183
    }
184
185
    /**
186
     * @Template
187
     * @param Request $request
188
     * @param string $procedureId
189
     * @return array|Response
190
     */
191
    public function verifyIdentityAction(Request $request, $procedureId)
192
    {
193
        $this->denyAccessUnlessGranted(['ROLE_RA']);
194
195
        $logger = $this->get('ra.procedure_logger')->forProcedure($procedureId);
196
        $logger->notice('Verify Identity Form requested');
197
198 View Code Duplication
        if (!$this->getVettingService()->hasProcedure($procedureId)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
199
            $logger->notice(sprintf('Vetting procedure "%s" not found', $procedureId));
200
            throw new NotFoundHttpException(sprintf('Vetting procedure "%s" not found', $procedureId));
201
        }
202
203
        $command = new VerifyIdentityCommand();
204
        $form = $this->createForm('ra_verify_identity', $command)->handleRequest($request);
205
206
        /** @var SubmitButton $cancelButton */
207
        $cancelButton = $form->get('cancel');
208 View Code Duplication
        if ($cancelButton->isClicked()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
209
            $this->getVettingService()->cancelProcedure($procedureId);
210
            $this->addFlash('info', $this->get('translator')->trans('ra.vetting.flash.cancelled'));
211
212
            return $this->redirectToRoute('ra_vetting_search');
213
        }
214
215
        $vettingService = $this->getVettingService();
216
        $commonName = $vettingService->getIdentityCommonName($procedureId);
217
218
        $showForm = function ($error = null) use ($form, $commonName) {
219
            if ($error) {
220
                $form->addError(new FormError($error));
221
            }
222
223
            return ['commonName' => $commonName, 'form' => $form->createView()];
224
        };
225
226
        if (!$form->isValid()) {
227
            $logger->notice('Verify Identity Form not submitted, displaying form');
228
229
            return $showForm();
230
        }
231
232
        try {
233
            $vettingService->verifyIdentity($procedureId, $command);
234
        } catch (DomainException $e) {
235
            $this->get('logger')->error(
236
                "RA attempted to verify identity, but the vetting procedure does not allow it",
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal RA attempted to verify i...edure does not allow it does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
237
                ['exception' => $e, 'procedure' => $procedureId]
238
            );
239
240
            return $showForm('ra.verify_identity.identity_verification_failed');
241
        }
242
243
        try {
244
            $vetting = $vettingService->vet($procedureId);
245
            if ($vetting->isSuccessful()) {
246
                $logger->notice('Identity Verified, vetting completed');
247
248
                return $this->redirectToRoute('ra_vetting_completed', ['procedureId' => $procedureId]);
249
            }
250
251
            $logger->error('RA attempted to vet second factor, but the command failed');
252
253
            if (in_array(VettingService::REGISTRATION_CODE_EXPIRED_ERROR, $vetting->getErrors())) {
254
                $registrationCodeExpiredError = $this->getTranslator()
255
                    ->trans(
256
                        'ra.verify_identity.registration_code_expired',
257
                        [
258
                            '%self_service_url%' => $this->getParameter('surfnet_stepup_ra.self_service_url'),
259
                        ]
260
                    );
261
262
                return $showForm($registrationCodeExpiredError);
263
            }
264
265
            return $showForm('ra.verify_identity.second_factor_vetting_failed');
266
        } catch (DomainException $e) {
267
            $logger->error(
268
                "RA attempted to vet second factor, but the vetting procedure didn't allow it",
269
                ['exception' => $e]
270
            );
271
272
            return $showForm('ra.verify_identity.second_factor_vetting_failed');
273
        }
274
    }
275
276
    /**
277
     * @Template
278
     */
279
    public function vettingCompletedAction()
280
    {
281
        return [];
282
    }
283
284
    /**
285
     * @return SecondFactorService
286
     */
287
    private function getSecondFactorService()
288
    {
289
        return $this->get('ra.service.second_factor');
290
    }
291
292
    /**
293
     * @return SecondFactorTypeService
294
     */
295
    private function getSecondFactorTypeService()
296
    {
297
        return $this->get('surfnet_stepup.service.second_factor_type');
298
    }
299
300
    /**
301
     * @return VettingService
302
     */
303
    private function getVettingService()
304
    {
305
        return $this->get('ra.service.vetting');
306
    }
307
308
    /**
309
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity
310
     */
311
    private function getIdentity()
312
    {
313
        return $this->get('security.token_storage')->getToken()->getUser();
314
    }
315
316
    /**
317
     * @return TranslatorInterface
318
     */
319
    private function getTranslator()
320
    {
321
        return $this->get('translator');
322
    }
323
}
324