Completed
Pull Request — develop (#302)
by Michiel
04:12 queued 02:07
created

createIdentity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 1
nc 1
nop 5
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\ApiBundle\Identity\Entity\VerifiedSecondFactor;
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\CreateIdentityCommand;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProvePhonePossessionCommand;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VerifyEmailCommand;
30
use Symfony\Component\Console\Input\InputArgument;
31
use Symfony\Component\Console\Input\InputInterface;
32
use Symfony\Component\Console\Output\OutputInterface;
33
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
34
35
final class BootstrapIdentityWithSmsSecondFactorCommand extends AbstractBootstrapCommand
36
{
37 View Code Duplication
    protected function configure()
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...
38
    {
39
        $this
40
            ->setName('middleware:bootstrap:identity-with-sms')
41
            ->setDescription('Creates an identity with a SMS second factor')
42
            ->addArgument('name-id', InputArgument::REQUIRED, 'The NameID of the identity to create')
43
            ->addArgument('institution', InputArgument::REQUIRED, 'The institution of the identity to create')
44
            ->addArgument('common-name', InputArgument::REQUIRED, 'The Common Name of the identity to create')
45
            ->addArgument('email', InputArgument::REQUIRED, 'The e-mail address of the identity to create')
46
            ->addArgument('preferred-locale', InputArgument::REQUIRED, 'The preferred locale of the identity to create')
47
            ->addArgument(
48
                'phone-number',
49
                InputArgument::REQUIRED,
50
                'The phone number of the user should be formatted like "+31 (0) 612345678"'
51
            )
52
            ->addArgument(
53
                'registration-status',
54
                InputArgument::REQUIRED,
55
                'Valid arguments: unverified, verified, vetted'
56
            );
57
    }
58
59
    protected function execute(InputInterface $input, OutputInterface $output)
60
    {
61
        $this->tokenStorage->setToken(
62
            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...
63
        );
64
65
        $nameId = new NameId($input->getArgument('name-id'));
66
        $institution = new Institution($input->getArgument('institution'));
0 ignored issues
show
Bug introduced by
It seems like $input->getArgument('institution') targeting Symfony\Component\Consol...nterface::getArgument() 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?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
67
        $mailVerificationRequired = $this->requiresMailVerification($institution);
0 ignored issues
show
Documentation introduced by
$institution is of type object<Surfnet\Stepup\Identity\Value\Institution>, but the function expects a object<Surfnet\Stepup\Co...tion\Value\Institution>.

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...
68
        $commonName = $input->getArgument('common-name');
69
        $email = $input->getArgument('email');
70
        $preferredLocale = $input->getArgument('preferred-locale');
71
        $registrationStatus = $input->getArgument('registration-status');
72
        $phoneNumber = $input->getArgument('phone-number');
73
        $identity = false;
74
75
        $output->writeln(
76
            sprintf(
77
                '<notice>Adding a %s SMS token for %s</notice>',
78
                $registrationStatus,
79
                $commonName
80
            )
81
        );
82
83
        if ($this->identityRepository->hasIdentityWithNameIdAndInstitution($nameId, $institution)) {
84
            $output->writeln(
85
                sprintf(
86
                    '<notice>An identity with name ID "%s" from institution "%s" already exists, using that identity</notice>',
87
                    $nameId->getNameId(),
88
                    $institution->getInstitution()
89
                )
90
            );
91
            $identity = $this->identityRepository->findOneByNameIdAndInstitution($nameId, $institution);
92
        }
93
94
        $this->connection->beginTransaction();
95
96
        $secondFactorId = Uuid::uuid4()->toString();
97
98
        if (!$identity) {
99
            $output->writeln('<notice>Creating a new identity</notice>');
100
            $identity = $this->createIdentity($institution, $nameId, $commonName, $email, $preferredLocale);
101
        }
102
103
        try {
104
            switch ($registrationStatus) {
105
                case "unverified":
106
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
107
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
108
                    break;
109
                case "verified":
110
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
111
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
112
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
113
                    $unverifiedSecondFactor = $this->unverifiedSecondFactorRepository->findOneBy(
114
                        ['identityId' => $identity->id, 'type' => 'sms']
115
                    );
116
117
                    if ($mailVerificationRequired) {
118
                        $output->writeln('<notice>Creating a verified SMS token</notice>');
119
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
120
                    }
121
122
                    break;
123
                case "vetted":
124
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
125
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
126
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
127
                    $unverifiedSecondFactor = $this->unverifiedSecondFactorRepository->findOneBy(
128
                        ['identityId' => $identity->id, 'type' => 'sms']
129
                    );
130
131
                    if ($mailVerificationRequired) {
132
                        $output->writeln('<notice>Creating a verified SMS token</notice>');
133
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
134
                    }
135
                    /** @var VerifiedSecondFactor $verifiedSecondFactor */
136
                    $verifiedSecondFactor = $this->verifiedSecondFactorRepository->findOneBy(
137
                        ['identityId' => $identity->id, 'type' => 'sms']
138
                    );
139
                    $output->writeln('<notice>Vetting the verified SMS token</notice>');
140
                    $this->vetSecondFactor(
141
                        'sms',
142
                        'db9b8bdf-720c-44ba-a4c4-154953e45f14',
143
                        $identity,
144
                        $secondFactorId,
145
                        $verifiedSecondFactor,
146
                        $phoneNumber
147
                    );
148
                    break;
149
            }
150
151
            $this->eventBus->flush();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Broadway\EventHandling\EventBusInterface as the method flush() does only exist in the following implementations of said interface: Surfnet\StepupMiddleware...ndling\BufferedEventBus.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
152
            $this->connection->commit();
153
154
        } catch (Exception $e) {
155
            $output->writeln(
156
                sprintf(
157
                    '<error>An Error occurred when trying to bootstrap the identity: "%s"</error>',
158
                    $e->getMessage()
159
                )
160
            );
161
162
            $this->connection->rollBack();
163
164
            throw $e;
165
        }
166
167
        $output->writeln(
168
            sprintf(
169
                '<info>Successfully created identity with UUID %s and %s second factor with UUID %s</info>',
170
                $identity->id,
171
                $registrationStatus,
172
                $secondFactorId
173
            )
174
        );
175
    }
176
177 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...
178
    {
179
        $command = new ProvePhonePossessionCommand();
180
        $command->UUID = (string) Uuid::uuid4();
181
        $command->secondFactorId = $secondFactorId;
182
        $command->identityId = $identity->id;
183
        $command->phoneNumber = $phoneNumber;
184
        $this->pipeline->process($command);
185
    }
186
187 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...
188
    {
189
        $command = new VerifyEmailCommand();
190
        $command->UUID = (string) Uuid::uuid4();
191
        $command->identityId = $identity->id;
192
        $command->verificationNonce = $unverifiedSecondFactor->verificationNonce;
193
        $this->pipeline->process($command);
194
    }
195
196
    protected function createIdentity(
197
        Institution $institution,
198
        NameId $nameId,
199
        $commonName,
200
        $email,
201
        $preferredLocale
202
    ) {
203
204
        $identity = new CreateIdentityCommand();
205
        $identity->UUID = (string)Uuid::uuid4();
206
        $identity->id = (string)Uuid::uuid4();
207
        $identity->institution = $institution->getInstitution();
208
        $identity->nameId = $nameId->getNameId();
209
        $identity->commonName = $commonName;
210
        $identity->email = $email;
211
        $identity->preferredLocale = $preferredLocale;
212
        $this->pipeline->process($identity);
213
214
        return $identity;
215
    }
216
}
217