Completed
Push — develop ( 4b5d7b...eb590e )
by Boy
15:32 queued 11:48
created

VettingController::verifyIdentityAction()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 72
Code Lines 42

Duplication

Lines 10
Ratio 13.89 %

Importance

Changes 6
Bugs 0 Features 2
Metric Value
dl 10
loc 72
c 6
b 0
f 2
rs 6.3883
cc 8
eloc 42
nc 11
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Value\SecondFactorType;
23
use Surfnet\StepupRa\RaBundle\Command\StartVettingProcedureCommand;
24
use Surfnet\StepupRa\RaBundle\Command\VerifyIdentityCommand;
25
use Surfnet\StepupRa\RaBundle\Exception\DomainException;
26
use Surfnet\StepupRa\RaBundle\Exception\RuntimeException;
27
use Surfnet\StepupRa\RaBundle\Security\Authentication\Token\SamlToken;
28
use Surfnet\StepupRa\RaBundle\Service\SecondFactorService;
29
use Surfnet\StepupRa\RaBundle\Service\VettingService;
30
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
31
use Symfony\Component\Form\FormError;
32
use Symfony\Component\Form\SubmitButton;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
36
37
class VettingController extends Controller
38
{
39
    /**
40
     * @Template
41
     * @param Request $request
42
     * @return array|Response
43
     */
44
    public function startProcedureAction(Request $request)
45
    {
46
        $this->denyAccessUnlessGranted(['ROLE_RA']);
47
        $logger = $this->get('logger');
48
49
        $logger->notice('Vetting Procedure Search started');
50
51
        $command = new StartVettingProcedureCommand();
52
53
        $form = $this->createForm('ra_start_vetting_procedure', $command)->handleRequest($request);
54
55
        if (!$form->isValid()) {
56
            $logger->notice('No search submitted, displaying search by registration code form');
57
58
            return ['form' => $form->createView()];
59
        }
60
61
        $secondFactor = $this->getSecondFactorService()
62
            ->findVerifiedSecondFactorByRegistrationCode($command->registrationCode);
63
64
        if ($secondFactor === null) {
65
            $form->addError(new FormError('ra.form.start_vetting_procedure.unknown_registration_code'));
66
            $logger->notice('Cannot start new vetting procedure, no second factor found');
67
68
            return ['form' => $form->createView()];
69
        }
70
71
        $enabledSecondFactors = $this->container->getParameter('surfnet_stepup_ra.enabled_second_factors');
72
        if (!in_array($secondFactor->type, $enabledSecondFactors, true)) {
73
            $logger->warning(
74
                sprintf(
75
                    'An RA attempted vetting of disabled second factor "%s" of type "%s"',
76
                    $secondFactor->id,
77
                    $secondFactor->type
78
                )
79
            );
80
81
            return $this
82
                ->render(
83
                    'SurfnetStepupRaRaBundle:Vetting:secondFactorTypeDisabled.html.twig',
84
                    ['secondFactorType' => $secondFactor->type]
85
                )
86
                ->setStatusCode(Response::HTTP_BAD_REQUEST);
87
        }
88
89
        /** @var SamlToken $token */
90
        $token = $this->get('security.token_storage')->getToken();
91
        $command->authorityId = $this->getIdentity()->id;
92
        $command->authorityLoa = $token->getLoa();
93
        $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...
94
95
        if (!$this->getVettingService()->isLoaSufficientToStartProcedure($command)) {
96
            $form->addError(new FormError('ra.form.start_vetting_procedure.loa_insufficient'));
97
98
            $logger->notice('Cannot start new vetting procedure, Authority LoA is insufficient');
99
100
            return ['form' => $form->createView()];
101
        }
102
103
        $procedureId = $this->getVettingService()->startProcedure($command);
104
105
        $this->get('ra.procedure_logger')
106
            ->forProcedure($procedureId)
107
            ->notice(sprintf('Starting new Vetting Procedure for second factor of type "%s"', $secondFactor->type));
108
109
        $secondFactorType = new SecondFactorType($secondFactor->type);
110
        if ($secondFactorType->isYubikey()) {
111
            return $this->redirectToRoute('ra_vetting_yubikey_verify', ['procedureId' => $procedureId]);
112
        } elseif ($secondFactorType->isSms()) {
113
            return $this->redirectToRoute('ra_vetting_sms_send_challenge', ['procedureId' => $procedureId]);
114
        } elseif ($secondFactorType->isGssf()) {
115
            return $this->redirectToRoute(
116
                'ra_vetting_gssf_initiate',
117
                [
118
                    'procedureId' => $procedureId,
119
                    'provider'    => $secondFactor->type
120
                ]
121
            );
122
        } elseif ($secondFactorType->isU2f()) {
123
            return $this->redirectToRoute('ra_vetting_u2f_start_authentication', ['procedureId' => $procedureId]);
124
        } else {
125
            throw new RuntimeException(
126
                sprintf('RA does not support vetting procedure for second factor type "%s"', $secondFactor->type)
127
            );
128
        }
129
    }
130
131
    public function cancelProcedureAction($procedureId)
132
    {
133
        $logger = $this->get('ra.procedure_logger')->forProcedure($procedureId);
134
135 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...
136
            $logger->notice(sprintf('Vetting procedure "%s" not found', $procedureId));
137
            throw new NotFoundHttpException(sprintf('Vetting procedure "%s" not found', $procedureId));
138
        }
139
140
        $this->getVettingService()->cancelProcedure($procedureId);
141
        $this->addFlash('info', $this->get('translator')->trans('ra.vetting.flash.cancelled'));
142
143
        return $this->redirectToRoute('ra_vetting_search');
144
    }
145
146
    /**
147
     * @Template
148
     * @param Request $request
149
     * @param string $procedureId
150
     * @return array|Response
151
     */
152
    public function verifyIdentityAction(Request $request, $procedureId)
153
    {
154
        $this->denyAccessUnlessGranted(['ROLE_RA']);
155
156
        $logger = $this->get('ra.procedure_logger')->forProcedure($procedureId);
157
        $logger->notice('Verify Identity Form requested');
158
159 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...
160
            $logger->notice(sprintf('Vetting procedure "%s" not found', $procedureId));
161
            throw new NotFoundHttpException(sprintf('Vetting procedure "%s" not found', $procedureId));
162
        }
163
164
        $command = new VerifyIdentityCommand();
165
        $form = $this->createForm('ra_verify_identity', $command)->handleRequest($request);
166
167
        /** @var SubmitButton $cancelButton */
168
        $cancelButton = $form->get('cancel');
169 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...
170
            $this->getVettingService()->cancelProcedure($procedureId);
171
            $this->addFlash('info', $this->get('translator')->trans('ra.vetting.flash.cancelled'));
172
173
            return $this->redirectToRoute('ra_vetting_search');
174
        }
175
176
        $vettingService = $this->getVettingService();
177
        $commonName = $vettingService->getIdentityCommonName($procedureId);
178
179
        $showForm = function ($error = null) use ($form, $commonName) {
180
            if ($error) {
181
                $form->addError(new FormError($error));
182
            }
183
184
            return ['commonName' => $commonName, 'form' => $form->createView()];
185
        };
186
187
        if (!$form->isValid()) {
188
            $logger->notice('Verify Identity Form not submitted, displaying form');
189
190
            return $showForm();
191
        }
192
193
        try {
194
            $vettingService->verifyIdentity($procedureId, $command);
195
        } catch (DomainException $e) {
196
            $this->get('logger')->error(
197
                "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...
198
                ['exception' => $e, 'procedure' => $procedureId]
199
            );
200
201
            return $showForm('ra.verify_identity.identity_verification_failed');
202
        }
203
204
        try {
205
            $vetted = $vettingService->vet($procedureId);
206
            if ($vetted) {
207
                $logger->notice('Identity Verified, vetting completed');
208
209
                return $this->redirectToRoute('ra_vetting_completed', ['procedureId' => $procedureId]);
210
            }
211
212
            $logger->error('RA attempted to vet second factor, but the command failed');
213
214
            return $showForm('ra.verify_identity.second_factor_vetting_failed');
215
        } catch (DomainException $e) {
216
            $logger->error(
217
                "RA attempted to vet second factor, but the vetting procedure didn't allow it",
218
                ['exception' => $e]
219
            );
220
221
            return $showForm('ra.verify_identity.second_factor_vetting_failed');
222
        }
223
    }
224
225
    /**
226
     * @Template
227
     */
228
    public function vettingCompletedAction()
229
    {
230
        return [];
231
    }
232
233
    /**
234
     * @return SecondFactorService
235
     */
236
    private function getSecondFactorService()
237
    {
238
        return $this->get('ra.service.second_factor');
239
    }
240
241
    /**
242
     * @return VettingService
243
     */
244
    private function getVettingService()
245
    {
246
        return $this->get('ra.service.vetting');
247
    }
248
249
    /**
250
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity
251
     */
252
    private function getIdentity()
253
    {
254
        return $this->get('security.token_storage')->getToken()->getUser();
255
    }
256
}
257