Completed
Push — master ( a3c457...aab356 )
by
unknown
03:38
created

handleBootstrapIdentityWithYubikeySecondFactorCommand()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 36
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 23
nc 2
nop 1
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\StepupMiddleware\CommandHandlingBundle\Identity\CommandHandler;
20
21
use Broadway\CommandHandling\CommandHandler;
22
use Broadway\Repository\RepositoryInterface;
23
use Surfnet\Stepup\Configuration\Value\Institution as ConfigurationInstitution;
24
use Surfnet\Stepup\Identity\Api\Identity as IdentityApi;
25
use Surfnet\Stepup\Identity\Entity\ConfigurableSettings;
26
use Surfnet\Stepup\Identity\Identity;
27
use Surfnet\Stepup\Identity\Value\CommonName;
28
use Surfnet\Stepup\Identity\Value\DocumentNumber;
29
use Surfnet\Stepup\Identity\Value\Email;
30
use Surfnet\Stepup\Identity\Value\GssfId;
31
use Surfnet\Stepup\Identity\Value\IdentityId;
32
use Surfnet\Stepup\Identity\Value\Institution;
33
use Surfnet\Stepup\Identity\Value\Locale;
34
use Surfnet\Stepup\Identity\Value\NameId;
35
use Surfnet\Stepup\Identity\Value\PhoneNumber;
36
use Surfnet\Stepup\Identity\Value\SecondFactorId;
37
use Surfnet\Stepup\Identity\Value\SecondFactorIdentifierFactory;
38
use Surfnet\Stepup\Identity\Value\StepupProvider;
39
use Surfnet\Stepup\Identity\Value\U2fKeyHandle;
40
use Surfnet\Stepup\Identity\Value\YubikeyPublicId;
41
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
42
use Surfnet\StepupBundle\Value\SecondFactorType;
43
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Service\AllowedSecondFactorListService;
44
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Service\InstitutionConfigurationOptionsService;
45
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\IdentityRepository;
46
use Surfnet\StepupMiddleware\CommandHandlingBundle\Exception\SecondFactorNotAllowedException;
47
use Surfnet\StepupMiddleware\CommandHandlingBundle\Exception\UnsupportedLocaleException;
48
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\BootstrapIdentityWithYubikeySecondFactorCommand;
49
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\CreateIdentityCommand;
50
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ExpressLocalePreferenceCommand;
51
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProveGssfPossessionCommand;
52
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProvePhonePossessionCommand;
53
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProveU2fDevicePossessionCommand;
54
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProveYubikeyPossessionCommand;
55
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\RevokeOwnSecondFactorCommand;
56
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\RevokeRegistrantsSecondFactorCommand;
57
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\UpdateIdentityCommand;
58
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VerifyEmailCommand;
59
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VetSecondFactorCommand;
60
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\CommandHandler\Exception\DuplicateIdentityException;
61
62
/**
63
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
64
 * @SuppressWarnings(PHPMD.TooManyMethods)
65
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
66
 */
67
class IdentityCommandHandler extends CommandHandler
68
{
69
    /**
70
     * @var \Surfnet\Stepup\Identity\EventSourcing\IdentityRepository
71
     */
72
    private $eventSourcedRepository;
73
74
    /**
75
     * @var IdentityRepository
76
     */
77
    private $identityProjectionRepository;
78
79
    /**
80
     * @var \Surfnet\Stepup\Identity\Entity\ConfigurableSettings
81
     */
82
    private $configurableSettings;
83
84
    /**
85
     * @var AllowedSecondFactorListService
86
     */
87
    private $allowedSecondFactorListService;
88
89
    /** @var SecondFactorTypeService */
90
    private $secondFactorTypeService;
91
92
    /**
93
     * @var InstitutionConfigurationOptionsService
94
     */
95
    private $institutionConfigurationOptionsService;
96
97
    /**
98
     * @param RepositoryInterface                    $eventSourcedRepository
99
     * @param IdentityRepository                     $identityProjectionRepository
100
     * @param ConfigurableSettings                   $configurableSettings
101
     * @param AllowedSecondFactorListService         $allowedSecondFactorListService
102
     * @param SecondFactorTypeService                $secondFactorTypeService
103
     * @param InstitutionConfigurationOptionsService $institutionConfigurationOptionsService
104
     */
105
    public function __construct(
106
        RepositoryInterface $eventSourcedRepository,
107
        IdentityRepository $identityProjectionRepository,
108
        ConfigurableSettings $configurableSettings,
109
        AllowedSecondFactorListService $allowedSecondFactorListService,
110
        SecondFactorTypeService $secondFactorTypeService,
111
        InstitutionConfigurationOptionsService $institutionConfigurationOptionsService
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $institutionConfigurationOptionsService exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
112
    ) {
113
        $this->eventSourcedRepository = $eventSourcedRepository;
0 ignored issues
show
Documentation Bug introduced by
$eventSourcedRepository is of type object<Broadway\Repository\RepositoryInterface>, but the property $eventSourcedRepository was declared to be of type object<Surfnet\Stepup\Id...ing\IdentityRepository>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof 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 given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
114
        $this->identityProjectionRepository = $identityProjectionRepository;
115
        $this->configurableSettings = $configurableSettings;
116
        $this->allowedSecondFactorListService = $allowedSecondFactorListService;
117
        $this->secondFactorTypeService = $secondFactorTypeService;
118
        $this->institutionConfigurationOptionsService = $institutionConfigurationOptionsService;
119
    }
120
121
    public function handleCreateIdentityCommand(CreateIdentityCommand $command)
122
    {
123
        $preferredLocale = new Locale($command->preferredLocale);
124
        $this->assertIsValidLocale($preferredLocale);
125
126
        $identity = Identity::create(
127
            new IdentityId($command->id),
128
            new Institution($command->institution),
129
            new NameId($command->nameId),
130
            new CommonName($command->commonName),
131
            new Email($command->email),
132
            $preferredLocale
133
        );
134
135
        $this->eventSourcedRepository->save($identity);
136
    }
137
138
    public function handleUpdateIdentityCommand(UpdateIdentityCommand $command)
139
    {
140
        /** @var IdentityApi $identity */
141
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->id));
142
143
        $identity->rename(new CommonName($command->commonName));
144
        $identity->changeEmail(new Email($command->email));
145
146
        $this->eventSourcedRepository->save($identity);
147
    }
148
149
    public function handleBootstrapIdentityWithYubikeySecondFactorCommand(
150
        BootstrapIdentityWithYubikeySecondFactorCommand $command
151
    ) {
152
        $preferredLocale = new Locale($command->preferredLocale);
153
        $this->assertIsValidLocale($preferredLocale);
154
155
        $institution = new Institution($command->institution);
156
        $nameId = new NameId($command->nameId);
157
158
        if ($this->identityProjectionRepository->hasIdentityWithNameIdAndInstitution($nameId, $institution)) {
159
            throw DuplicateIdentityException::forBootstrappingWithYubikeySecondFactor($nameId, $institution);
160
        }
161
162
        $identity = Identity::create(
163
            new IdentityId($command->identityId),
164
            $institution,
165
            $nameId,
166
            new CommonName($command->commonName),
167
            new Email($command->email),
168
            $preferredLocale
169
        );
170
171
        $configurationInstitution = new ConfigurationInstitution(
172
            (string) $identity->getInstitution()
173
        );
174
175
        $tokenCount = $this->institutionConfigurationOptionsService->getMaxNumberOfTokensFor($configurationInstitution);
176
        $identity->setMaxNumberOfTokens($tokenCount);
177
178
        $identity->bootstrapYubikeySecondFactor(
179
            new SecondFactorId($command->secondFactorId),
180
            new YubikeyPublicId($command->yubikeyPublicId)
181
        );
182
183
        $this->eventSourcedRepository->save($identity);
184
    }
185
186 View Code Duplication
    public function handleProveYubikeyPossessionCommand(ProveYubikeyPossessionCommand $command)
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...
187
    {
188
        /** @var IdentityApi $identity */
189
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
190
191
        $this->assertSecondFactorIsAllowedFor(new SecondFactorType('yubikey'), $identity->getInstitution());
192
193
        $configurationInstitution = new ConfigurationInstitution(
194
            (string) $identity->getInstitution()
195
        );
196
        $tokenCount = $this->institutionConfigurationOptionsService->getMaxNumberOfTokensFor($configurationInstitution);
197
        $identity->setMaxNumberOfTokens($tokenCount);
198
199
        $identity->provePossessionOfYubikey(
200
            new SecondFactorId($command->secondFactorId),
201
            new YubikeyPublicId($command->yubikeyPublicId),
202
            $this->emailVerificationIsRequired($identity),
203
            $this->configurableSettings->createNewEmailVerificationWindow()
204
        );
205
206
        $this->eventSourcedRepository->save($identity);
207
    }
208
209
    /**
210
     * @param ProvePhonePossessionCommand $command
211
     */
212 View Code Duplication
    public function handleProvePhonePossessionCommand(ProvePhonePossessionCommand $command)
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...
213
    {
214
        /** @var IdentityApi $identity */
215
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
216
217
        $this->assertSecondFactorIsAllowedFor(new SecondFactorType('sms'), $identity->getInstitution());
218
219
        $configurationInstitution = new ConfigurationInstitution(
220
            (string) $identity->getInstitution()
221
        );
222
223
        $tokenCount = $this->institutionConfigurationOptionsService->getMaxNumberOfTokensFor($configurationInstitution);
224
        $identity->setMaxNumberOfTokens($tokenCount);
225
226
        $identity->provePossessionOfPhone(
227
            new SecondFactorId($command->secondFactorId),
228
            new PhoneNumber($command->phoneNumber),
229
            $this->emailVerificationIsRequired($identity),
230
            $this->configurableSettings->createNewEmailVerificationWindow()
231
        );
232
233
        $this->eventSourcedRepository->save($identity);
234
    }
235
236
    /**
237
     * @param ProveGssfPossessionCommand $command
238
     */
239
    public function handleProveGssfPossessionCommand(ProveGssfPossessionCommand $command)
240
    {
241
        /** @var IdentityApi $identity */
242
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
243
        $secondFactorType = $command->stepupProvider;
244
245
        // Validate that the chosen second factor type (stepupProvider) is allowed for the users instituti
246
        $this->assertSecondFactorIsAllowedFor(new SecondFactorType($secondFactorType), $identity->getInstitution());
247
248
        $configurationInstitution = new ConfigurationInstitution(
249
            (string) $identity->getInstitution()
250
        );
251
252
        $tokenCount = $this->institutionConfigurationOptionsService->getMaxNumberOfTokensFor($configurationInstitution);
253
        $identity->setMaxNumberOfTokens($tokenCount);
254
255
        $identity->provePossessionOfGssf(
256
            new SecondFactorId($command->secondFactorId),
257
            new StepupProvider($secondFactorType),
258
            new GssfId($command->gssfId),
259
            $this->emailVerificationIsRequired($identity),
260
            $this->configurableSettings->createNewEmailVerificationWindow()
261
        );
262
263
        $this->eventSourcedRepository->save($identity);
264
    }
265
266 View Code Duplication
    public function handleProveU2fDevicePossessionCommand(ProveU2fDevicePossessionCommand $command)
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...
267
    {
268
        /** @var IdentityApi $identity */
269
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
270
271
        $this->assertSecondFactorIsAllowedFor(new SecondFactorType('u2f'), $identity->getInstitution());
272
273
        $configurationInstitution = new ConfigurationInstitution(
274
            (string) $identity->getInstitution()
275
        );
276
277
        $tokenCount = $this->institutionConfigurationOptionsService->getMaxNumberOfTokensFor($configurationInstitution);
278
        $identity->setMaxNumberOfTokens($tokenCount);
279
280
        $identity->provePossessionOfU2fDevice(
281
            new SecondFactorId($command->secondFactorId),
282
            new U2fKeyHandle($command->keyHandle),
283
            $this->emailVerificationIsRequired($identity),
284
            $this->configurableSettings->createNewEmailVerificationWindow()
285
        );
286
287
        $this->eventSourcedRepository->save($identity);
288
    }
289
290
    /**
291
     * @param VerifyEmailCommand $command
292
     */
293
    public function handleVerifyEmailCommand(VerifyEmailCommand $command)
294
    {
295
        /** @var IdentityApi $identity */
296
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
297
298
        $identity->verifyEmail($command->verificationNonce);
299
300
        $this->eventSourcedRepository->save($identity);
301
    }
302
303
    public function handleVetSecondFactorCommand(VetSecondFactorCommand $command)
304
    {
305
        /** @var IdentityApi $authority */
306
        $authority = $this->eventSourcedRepository->load(new IdentityId($command->authorityId));
307
        /** @var IdentityApi $registrant */
308
        $registrant = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
309
310
        $secondFactorType = new SecondFactorType($command->secondFactorType);
311
        $secondFactorIdentifier = SecondFactorIdentifierFactory::forType(
312
            $secondFactorType,
313
            $command->secondFactorIdentifier
314
        );
315
316
        $authority->vetSecondFactor(
317
            $registrant,
318
            new SecondFactorId($command->secondFactorId),
319
            $secondFactorType,
320
            $secondFactorIdentifier,
321
            $command->registrationCode,
322
            new DocumentNumber($command->documentNumber),
323
            $command->identityVerified,
324
            $this->secondFactorTypeService
325
        );
326
327
        $this->eventSourcedRepository->save($authority);
328
        $this->eventSourcedRepository->save($registrant);
329
    }
330
331
    public function handleRevokeOwnSecondFactorCommand(RevokeOwnSecondFactorCommand $command)
332
    {
333
        /** @var IdentityApi $identity */
334
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
335
        $identity->revokeSecondFactor(new SecondFactorId($command->secondFactorId));
336
337
        $this->eventSourcedRepository->save($identity);
338
    }
339
340
    public function handleRevokeRegistrantsSecondFactorCommand(RevokeRegistrantsSecondFactorCommand $command)
341
    {
342
        /** @var IdentityApi $identity */
343
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
344
        $identity->complyWithSecondFactorRevocation(
345
            new SecondFactorId($command->secondFactorId),
346
            new IdentityId($command->authorityId)
347
        );
348
349
        $this->eventSourcedRepository->save($identity);
350
    }
351
352
    public function handleExpressLocalePreferenceCommand(ExpressLocalePreferenceCommand $command)
353
    {
354
        $preferredLocale = new Locale($command->preferredLocale);
355
        $this->assertIsValidLocale($preferredLocale);
356
357
        /** @var IdentityApi $identity */
358
        $identity = $this->eventSourcedRepository->load(new IdentityId($command->identityId));
359
        $identity->expressPreferredLocale($preferredLocale);
360
361
        $this->eventSourcedRepository->save($identity);
362
    }
363
364
    /**
365
     * @param Locale $locale
366
     */
367
    private function assertIsValidLocale(Locale $locale)
368
    {
369
        if (!$this->configurableSettings->isSupportedLocale($locale)) {
370
            throw new UnsupportedLocaleException(
371
                sprintf('Given locale "%s" is not a supported locale', (string) $locale)
372
            );
373
        }
374
    }
375
376
    private function assertSecondFactorIsAllowedFor(SecondFactorType $secondFactor, Institution $institution)
377
    {
378
        $allowedSecondFactorList = $this->allowedSecondFactorListService->getAllowedSecondFactorListFor(
379
            new ConfigurationInstitution($institution->getInstitution())
380
        );
381
382
        if (!$allowedSecondFactorList->allows($secondFactor)) {
383
            throw new SecondFactorNotAllowedException(sprintf(
384
                'Institution "%s" does not support second factor "%s"',
385
                $institution->getInstitution(),
386
                $secondFactor->getSecondFactorType()
387
            ));
388
        }
389
    }
390
391
    /**
392
     * @param IdentityApi $identity
393
     * @return bool
394
     */
395
    private function emailVerificationIsRequired(IdentityApi $identity)
396
    {
397
        $institution = new ConfigurationInstitution(
398
            (string) $identity->getInstitution()
399
        );
400
401
        $configuration = $this->institutionConfigurationOptionsService
402
            ->findInstitutionConfigurationOptionsFor($institution);
403
404
        if ($configuration === null) {
405
            return true;
406
        }
407
408
        return $configuration->verifyEmailOption->isEnabled();
409
    }
410
}
411