Completed
Pull Request — feature/bootstrap-commands (#303)
by Michiel
03:42 queued 01:14
created

BootstrapSmsSecondFactorCommand::verifyEmail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
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\ProvePhonePossessionCommand;
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VerifyEmailCommand;
28
use Symfony\Component\Console\Input\InputArgument;
29
use Symfony\Component\Console\Input\InputInterface;
30
use Symfony\Component\Console\Output\OutputInterface;
31
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
32
33
final class BootstrapSmsSecondFactorCommand extends AbstractBootstrapCommand
34
{
35
    protected function configure()
36
    {
37
        $this
38
            ->setDescription('Creates a SMS second factor for a specified user')
39
            ->addArgument('name-id', InputArgument::REQUIRED, 'The NameID of the identity to create')
40
            ->addArgument('institution', InputArgument::REQUIRED, 'The institution of the identity to create')
41
            ->addArgument(
42
                'phone-number',
43
                InputArgument::REQUIRED,
44
                'The phone number of the user should be formatted like "+31 (0) 612345678"'
45
            )
46
            ->addArgument(
47
                'registration-status',
48
                InputArgument::REQUIRED,
49
                'Valid arguments: unverified, verified, vetted'
50
            )
51
            ->addArgument('actor-id', InputArgument::REQUIRED, 'The id of the vetting actor');
52
    }
53
54
    protected function execute(InputInterface $input, OutputInterface $output)
55
    {
56
        $this->tokenStorage->setToken(
57
            new AnonymousToken('cli.bootstrap-identity-with-sms-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...
58
        );
59
        $nameId = new NameId($input->getArgument('name-id'));
60
        $institutionText = $input->getArgument('institution');
61
        $institution = new Institution($institutionText);
0 ignored issues
show
Bug introduced by
It seems like $institutionText defined by $input->getArgument('institution') on line 60 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...
62
        $mailVerificationRequired = $this->requiresMailVerification($institutionText);
63
        $registrationStatus = $input->getArgument('registration-status');
64
        $phoneNumber = $input->getArgument('phone-number');
65
        $actorId = $input->getArgument('actor-id');
66
        $this->enrichEventMetadata($actorId);
67 View Code Duplication
        if (!$this->tokenBootstrapService->hasIdentityWithNameIdAndInstitution($nameId, $institution)) {
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...
68
            $output->writeln(
69
                sprintf(
70
                    '<error>An identity with name ID "%s" from institution "%s" does not exist, create it first.</error>',
71
                    $nameId->getNameId(),
72
                    $institution->getInstitution()
73
                )
74
            );
75
76
            return;
77
        }
78
        $identity = $this->tokenBootstrapService->findOneByNameIdAndInstitution($nameId, $institution);
79
        $output->writeln(sprintf('<comment>Adding a %s SMS token for %s</comment>', $registrationStatus, $identity->commonName));
80
        $this->beginTransaction();
81
        $secondFactorId = Uuid::uuid4()->toString();
82
83
        try {
84
            switch ($registrationStatus) {
85
                case "unverified":
86
                    $output->writeln('<comment>Creating an unverified SMS token</comment>');
87
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
88
                    break;
89
                case "verified":
90
                    $output->writeln('<comment>Creating an unverified SMS token</comment>');
91
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
92
                    $unverifiedSecondFactor = $this->tokenBootstrapService->findUnverifiedToken($identity->id, 'sms');
93
                    if ($mailVerificationRequired) {
94
                        $output->writeln('<comment>Creating a verified SMS token</comment>');
95
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
96
                    }
97
                    break;
98
                case "vetted":
99
                    $output->writeln('<comment>Creating an unverified SMS token</comment>');
100
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
101
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
102
                    $unverifiedSecondFactor = $this->tokenBootstrapService->findUnverifiedToken($identity->id, 'sms');
103
                    if ($mailVerificationRequired) {
104
                        $output->writeln('<comment>Creating a verified SMS token</comment>');
105
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
106
                    }
107
                    $verifiedSecondFactor = $this->tokenBootstrapService->findVerifiedToken($identity->id, 'sms');
108
                    $output->writeln('<comment>Vetting the verified SMS token</comment>');
109
                    $this->vetSecondFactor(
110
                        'sms',
111
                        $actorId,
112
                        $identity,
113
                        $secondFactorId,
114
                        $verifiedSecondFactor,
115
                        $phoneNumber
116
                    );
117
                    break;
118
            }
119
            $this->finishTransaction();
120
        } catch (Exception $e) {
121
            $output->writeln(
122
                sprintf(
123
                    '<error>An Error occurred when trying to bootstrap the identity: "%s"</error>',
124
                    $e->getMessage()
125
                )
126
            );
127
            $this->rollback();
128
            throw $e;
129
        }
130
        $output->writeln(
131
            sprintf(
132
                '<info>Successfully created identity with UUID %s and %s second factor with UUID %s</info>',
133
                $identity->id,
134
                $registrationStatus,
135
                $secondFactorId
136
            )
137
        );
138
    }
139
140 View Code Duplication
    private function provePossession($secondFactorId, $identity, $phoneNumber)
0 ignored issues
show
Duplication introduced by
This method 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...
141
    {
142
        $command = new ProvePhonePossessionCommand();
143
        $command->UUID = (string)Uuid::uuid4();
144
        $command->secondFactorId = $secondFactorId;
145
        $command->identityId = $identity->id;
146
        $command->phoneNumber = $phoneNumber;
147
        $this->process($command);
148
    }
149
150 View Code Duplication
    private function verifyEmail($identity, $unverifiedSecondFactor)
0 ignored issues
show
Duplication introduced by
This method 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...
151
    {
152
        $command = new VerifyEmailCommand();
153
        $command->UUID = (string)Uuid::uuid4();
154
        $command->identityId = $identity->id;
155
        $command->verificationNonce = $unverifiedSecondFactor->verificationNonce;
156
        $this->process($command);
157
    }
158
}
159