Completed
Push — release/3.1 ( 4bc9e6...ab193b )
by Michiel
03:25 queued 01:15
created

BootstrapYubikeySecondFactorCommand::execute()   B

Complexity

Conditions 8
Paths 31

Size

Total Lines 85

Duplication

Lines 85
Ratio 100 %

Importance

Changes 0
Metric Value
dl 85
loc 85
rs 7.0828
c 0
b 0
f 0
cc 8
nc 31
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 2020 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\MiddlewareBundle\Console\Command;
20
21
use Exception;
22
use Rhumsaa\Uuid\Uuid;
23
use Surfnet\Stepup\Identity\Value\Institution;
24
use Surfnet\Stepup\Identity\Value\NameId;
25
use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\UnverifiedSecondFactor;
26
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProveYubikeyPossessionCommand;
27
use Symfony\Component\Console\Input\InputArgument;
28
use Symfony\Component\Console\Input\InputInterface;
29
use Symfony\Component\Console\Output\OutputInterface;
30
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
31
32 View Code Duplication
final class BootstrapYubikeySecondFactorCommand extends AbstractBootstrapCommand
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in 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...
33
{
34
    protected function configure()
35
    {
36
        $this
37
            ->setDescription('Creates a Yubikey second factor for a specified user')
38
            ->addArgument('name-id', InputArgument::REQUIRED, 'The NameID of the identity to create')
39
            ->addArgument('institution', InputArgument::REQUIRED, 'The institution of the identity to create')
40
            ->addArgument(
41
                'yubikey',
42
                InputArgument::REQUIRED,
43
                'The public ID of the Yubikey. Remove the last 32 characters of a Yubikey OTP to acquire this.'
44
            )
45
            ->addArgument(
46
                'registration-status',
47
                InputArgument::REQUIRED,
48
                'Valid arguments: unverified, verified, vetted'
49
            )
50
            ->addArgument('actor-id', InputArgument::REQUIRED, 'The id of the vetting actor');
51
    }
52
53
    protected function execute(InputInterface $input, OutputInterface $output)
54
    {
55
        $this->tokenStorage->setToken(
56
            new AnonymousToken('cli.bootstrap-yubikey-token', 'cli', ['ROLE_SS', 'ROLE_RA'])
0 ignored issues
show
Documentation introduced by
array('ROLE_SS', 'ROLE_RA') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a array<integer,object<Sym...curity\Core\Role\Role>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
57
        );
58
        $nameId = new NameId($input->getArgument('name-id'));
59
        $institutionText = $input->getArgument('institution');
60
        $institution = new Institution($institutionText);
0 ignored issues
show
Bug introduced by
It seems like $institutionText defined by $input->getArgument('institution') on line 59 can also be of type array<integer,string> or null; however, Surfnet\Stepup\Identity\...titution::__construct() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
61
        $mailVerificationRequired = $this->requiresMailVerification($institutionText);
62
        $registrationStatus = $input->getArgument('registration-status');
63
        $yubikey = $input->getArgument('yubikey');
64
        $actorId = $input->getArgument('actor-id');
65
        $this->enrichEventMetadata($actorId);
66
        if (!$this->tokenBootstrapService->hasIdentityWithNameIdAndInstitution($nameId, $institution)) {
67
            $output->writeln(
68
                sprintf(
69
                    '<error>An identity with name ID "%s" from institution "%s" does not exist, create it first.</error>',
70
                    $nameId->getNameId(),
71
                    $institution->getInstitution()
72
                )
73
            );
74
75
            return;
76
        }
77
        $identity = $this->tokenBootstrapService->findOneByNameIdAndInstitution($nameId, $institution);
78
        $output->writeln(sprintf('<comment>Adding a %s Yubikey token for %s</comment>', $registrationStatus, $identity->commonName));
79
        $this->beginTransaction();
80
        $secondFactorId = Uuid::uuid4()->toString();
81
82
        try {
83
            switch ($registrationStatus) {
84
                case "unverified":
85
                    $output->writeln('<comment>Creating an unverified Yubikey token</comment>');
86
                    $this->provePossession($secondFactorId, $identity, $yubikey);
87
                    break;
88
                case "verified":
89
                    $output->writeln('<comment>Creating an unverified Yubikey token</comment>');
90
                    $this->provePossession($secondFactorId, $identity, $yubikey);
91
                    $unverifiedSecondFactor = $this->tokenBootstrapService->findUnverifiedToken($identity->id, 'yubikey');
92
                    if ($mailVerificationRequired) {
93
                        $output->writeln('<comment>Creating a verified Yubikey token</comment>');
94
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
95
                    }
96
                    break;
97
                case "vetted":
98
                    $output->writeln('<comment>Creating an unverified Yubikey token</comment>');
99
                    $this->provePossession($secondFactorId, $identity, $yubikey);
100
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
101
                    $unverifiedSecondFactor = $this->tokenBootstrapService->findUnverifiedToken($identity->id, 'yubikey');
102
                    if ($mailVerificationRequired) {
103
                        $output->writeln('<comment>Creating a verified Yubikey token</comment>');
104
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
105
                    }
106
                    $verifiedSecondFactor = $this->tokenBootstrapService->findVerifiedToken($identity->id, 'yubikey');
107
                    $output->writeln('<comment>Vetting the verified Yubikey token</comment>');
108
                    $this->vetSecondFactor(
109
                        'yubikey',
110
                        $actorId,
111
                        $identity,
112
                        $secondFactorId,
113
                        $verifiedSecondFactor,
114
                        $yubikey
115
                    );
116
                    break;
117
            }
118
            $this->finishTransaction();
119
        } catch (Exception $e) {
120
            $output->writeln(
121
                sprintf(
122
                    '<error>An Error occurred when trying to bootstrap the Yubikey token: "%s"</error>',
123
                    $e->getMessage()
124
                )
125
            );
126
            $this->rollback();
127
            throw $e;
128
        }
129
        $output->writeln(
130
            sprintf(
131
                '<info>Successfully created identity with UUID %s and %s second factor with UUID %s</info>',
132
                $identity->id,
133
                $registrationStatus,
134
                $secondFactorId
135
            )
136
        );
137
    }
138
139
    private function provePossession($secondFactorId, $identity, $phoneNumber)
140
    {
141
        $command = new ProveYubikeyPossessionCommand();
142
        $command->UUID = (string)Uuid::uuid4();
143
        $command->secondFactorId = $secondFactorId;
144
        $command->identityId = $identity->id;
145
        $command->yubikeyPublicId = $phoneNumber;
146
        $this->process($command);
147
    }
148
}
149