Completed
Push — master ( 1ba3e4...d44357 )
by
unknown
02:08
created

VettingController   C

Complexity

Total Complexity 28

Size/Duplication

Total Lines 260
Duplicated Lines 5.38 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 28
c 5
b 0
f 0
lcom 1
cbo 19
dl 14
loc 260
rs 6.875

9 Methods

Rating   Name   Duplication   Size   Complexity  
A vettingCompletedAction() 0 4 1
A getSecondFactorService() 0 4 1
C startProcedureAction() 0 95 11
A cancelProcedureAction() 4 14 2
C verifyIdentityAction() 10 84 9
A getVettingService() 0 4 1
A getIdentity() 0 4 1
A getTranslator() 0 4 1
A getSecondFactorTypeService() 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
 */
42
class VettingController extends Controller
43
{
44
    /**
45
     * @Template
46
     * @param Request $request
47
     * @return array|Response
48
     *
49
     * @SuppressWarnings(PHPMD.CyclomaticComplexity) https://www.pivotaltracker.com/story/show/135045063
50
     * @SuppressWarnings(PHPMD.NPathComplexity)      https://www.pivotaltracker.com/story/show/135045063
51
     */
52
    public function startProcedureAction(Request $request)
53
    {
54
        $this->denyAccessUnlessGranted(['ROLE_RA']);
55
        $logger = $this->get('logger');
56
57
        $logger->notice('Vetting Procedure Search started');
58
59
        $command = new StartVettingProcedureCommand();
60
61
        $form = $this->createForm('ra_start_vetting_procedure', $command)->handleRequest($request);
62
63
        if (!$form->isValid()) {
64
            $logger->notice('No search submitted, displaying search by registration code form');
65
66
            return ['form' => $form->createView()];
67
        }
68
69
        $secondFactor = $this->getSecondFactorService()
70
            ->findVerifiedSecondFactorByRegistrationCode($command->registrationCode);
71
72
        if ($secondFactor === null) {
73
            $form->addError(new FormError('ra.form.start_vetting_procedure.unknown_registration_code'));
74
            $logger->notice('Cannot start new vetting procedure, no second factor found');
75
76
            return ['form' => $form->createView()];
77
        }
78
79
        if (!$this->isGranted('ROLE_SRAA') && $secondFactor->institution !== $this->getIdentity()->institution) {
80
            $form->addError(new FormError('ra.form.start_vetting_procedure.different_institution_error'));
81
            $logger->notice(
82
                'Cannot start new vetting procedure, registrant belongs to a different institution than RA'
83
            );
84
85
            return ['form' => $form->createView()];
86
        }
87
88
        $enabledSecondFactors = $this->container->getParameter('surfnet_stepup_ra.enabled_second_factors');
89
        if (!in_array($secondFactor->type, $enabledSecondFactors, true)) {
90
            $logger->warning(
91
                sprintf(
92
                    'An RA attempted vetting of disabled second factor "%s" of type "%s"',
93
                    $secondFactor->id,
94
                    $secondFactor->type
95
                )
96
            );
97
98
            return $this
99
                ->render(
100
                    'SurfnetStepupRaRaBundle:Vetting:secondFactorTypeDisabled.html.twig',
101
                    ['secondFactorType' => $secondFactor->type]
102
                )
103
                ->setStatusCode(Response::HTTP_BAD_REQUEST);
104
        }
105
106
        /** @var SamlToken $token */
107
        $token = $this->get('security.token_storage')->getToken();
108
        $command->authorityId = $this->getIdentity()->id;
109
        $command->authorityLoa = $token->getLoa();
110
        $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...
111
112
        if (!$this->getVettingService()->isLoaSufficientToStartProcedure($command)) {
113
            $form->addError(new FormError('ra.form.start_vetting_procedure.loa_insufficient'));
114
115
            $logger->notice('Cannot start new vetting procedure, Authority LoA is insufficient');
116
117
            return ['form' => $form->createView()];
118
        }
119
120
        $procedureId = $this->getVettingService()->startProcedure($command);
121
122
        $this->get('ra.procedure_logger')
123
            ->forProcedure($procedureId)
124
            ->notice(sprintf('Starting new Vetting Procedure for second factor of type "%s"', $secondFactor->type));
125
126
        $secondFactorType = new SecondFactorType($secondFactor->type);
127
        if ($secondFactorType->isYubikey()) {
128
            return $this->redirectToRoute('ra_vetting_yubikey_verify', ['procedureId' => $procedureId]);
129
        } elseif ($secondFactorType->isSms()) {
130
            return $this->redirectToRoute('ra_vetting_sms_send_challenge', ['procedureId' => $procedureId]);
131
        } elseif ($this->getSecondFactorTypeService()->isGssf($secondFactorType)) {
132
            return $this->redirectToRoute(
133
                'ra_vetting_gssf_initiate',
134
                [
135
                    'procedureId' => $procedureId,
136
                    'provider'    => $secondFactor->type
137
                ]
138
            );
139
        } elseif ($secondFactorType->isU2f()) {
140
            return $this->redirectToRoute('ra_vetting_u2f_start_authentication', ['procedureId' => $procedureId]);
141
        } else {
142
            throw new RuntimeException(
143
                sprintf('RA does not support vetting procedure for second factor type "%s"', $secondFactor->type)
144
            );
145
        }
146
    }
147
148
    public function cancelProcedureAction($procedureId)
149
    {
150
        $logger = $this->get('ra.procedure_logger')->forProcedure($procedureId);
151
152 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...
153
            $logger->notice(sprintf('Vetting procedure "%s" not found', $procedureId));
154
            throw new NotFoundHttpException(sprintf('Vetting procedure "%s" not found', $procedureId));
155
        }
156
157
        $this->getVettingService()->cancelProcedure($procedureId);
158
        $this->addFlash('info', $this->get('translator')->trans('ra.vetting.flash.cancelled'));
159
160
        return $this->redirectToRoute('ra_vetting_search');
161
    }
162
163
    /**
164
     * @Template
165
     * @param Request $request
166
     * @param string $procedureId
167
     * @return array|Response
168
     */
169
    public function verifyIdentityAction(Request $request, $procedureId)
170
    {
171
        $this->denyAccessUnlessGranted(['ROLE_RA']);
172
173
        $logger = $this->get('ra.procedure_logger')->forProcedure($procedureId);
174
        $logger->notice('Verify Identity Form requested');
175
176 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...
177
            $logger->notice(sprintf('Vetting procedure "%s" not found', $procedureId));
178
            throw new NotFoundHttpException(sprintf('Vetting procedure "%s" not found', $procedureId));
179
        }
180
181
        $command = new VerifyIdentityCommand();
182
        $form = $this->createForm('ra_verify_identity', $command)->handleRequest($request);
183
184
        /** @var SubmitButton $cancelButton */
185
        $cancelButton = $form->get('cancel');
186 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...
187
            $this->getVettingService()->cancelProcedure($procedureId);
188
            $this->addFlash('info', $this->get('translator')->trans('ra.vetting.flash.cancelled'));
189
190
            return $this->redirectToRoute('ra_vetting_search');
191
        }
192
193
        $vettingService = $this->getVettingService();
194
        $commonName = $vettingService->getIdentityCommonName($procedureId);
195
196
        $showForm = function ($error = null) use ($form, $commonName) {
197
            if ($error) {
198
                $form->addError(new FormError($error));
199
            }
200
201
            return ['commonName' => $commonName, 'form' => $form->createView()];
202
        };
203
204
        if (!$form->isValid()) {
205
            $logger->notice('Verify Identity Form not submitted, displaying form');
206
207
            return $showForm();
208
        }
209
210
        try {
211
            $vettingService->verifyIdentity($procedureId, $command);
212
        } catch (DomainException $e) {
213
            $this->get('logger')->error(
214
                "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...
215
                ['exception' => $e, 'procedure' => $procedureId]
216
            );
217
218
            return $showForm('ra.verify_identity.identity_verification_failed');
219
        }
220
221
        try {
222
            $vetting = $vettingService->vet($procedureId);
223
            if ($vetting->isSuccessful()) {
224
                $logger->notice('Identity Verified, vetting completed');
225
226
                return $this->redirectToRoute('ra_vetting_completed', ['procedureId' => $procedureId]);
227
            }
228
229
            $logger->error('RA attempted to vet second factor, but the command failed');
230
231
            if (in_array(VettingService::REGISTRATION_CODE_EXPIRED_ERROR, $vetting->getErrors())) {
232
                $registrationCodeExpiredError = $this->getTranslator()
233
                    ->trans(
234
                        'ra.verify_identity.registration_code_expired',
235
                        [
236
                            '%self_service_url%' => $this->getParameter('surfnet_stepup_ra.self_service_url'),
237
                        ]
238
                    );
239
240
                return $showForm($registrationCodeExpiredError);
241
            }
242
243
            return $showForm('ra.verify_identity.second_factor_vetting_failed');
244
        } catch (DomainException $e) {
245
            $logger->error(
246
                "RA attempted to vet second factor, but the vetting procedure didn't allow it",
247
                ['exception' => $e]
248
            );
249
250
            return $showForm('ra.verify_identity.second_factor_vetting_failed');
251
        }
252
    }
253
254
    /**
255
     * @Template
256
     */
257
    public function vettingCompletedAction()
258
    {
259
        return [];
260
    }
261
262
    /**
263
     * @return SecondFactorService
264
     */
265
    private function getSecondFactorService()
266
    {
267
        return $this->get('ra.service.second_factor');
268
    }
269
270
    /**
271
     * @return SecondFactorTypeService
272
     */
273
    private function getSecondFactorTypeService()
274
    {
275
        return $this->get('surfnet_stepup.service.second_factor_type');
276
    }
277
278
    /**
279
     * @return VettingService
280
     */
281
    private function getVettingService()
282
    {
283
        return $this->get('ra.service.vetting');
284
    }
285
286
    /**
287
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity
288
     */
289
    private function getIdentity()
290
    {
291
        return $this->get('security.token_storage')->getToken()->getUser();
292
    }
293
294
    /**
295
     * @return TranslatorInterface
296
     */
297
    private function getTranslator()
298
    {
299
        return $this->get('translator');
300
    }
301
}
302