Passed
Pull Request — main (#308)
by Michiel
14:02 queued 06:58
created

SecondFactorController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 7
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
/**
6
 * Copyright 2014 SURFnet bv
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
Coding Style introduced by
Missing @link tag in file comment
Loading history...
20
21
namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;
22
23
use LogicException;
24
use Surfnet\StepupBundle\DateTime\RegistrationExpirationHelper;
25
use Psr\Log\LoggerInterface;
26
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
27
use Surfnet\StepupSelfService\SelfServiceBundle\Command\RevokeCommand;
28
use Surfnet\StepupSelfService\SelfServiceBundle\Form\Type\RevokeSecondFactorType;
29
use Surfnet\StepupSelfService\SelfServiceBundle\Service\AuthorizationService;
30
use Surfnet\StepupSelfService\SelfServiceBundle\Service\InstitutionConfigurationOptionsService;
31
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
32
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfAssertedTokens\RecoveryTokenService;
33
use Symfony\Bridge\Twig\Attribute\Template;
34
use Symfony\Component\HttpFoundation\Request;
35
use Symfony\Component\HttpFoundation\Response;
36
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
37
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
38
use Symfony\Component\Routing\Attribute\Route;
39
40
class SecondFactorController extends Controller
0 ignored issues
show
Coding Style introduced by
Missing doc comment for class SecondFactorController
Loading history...
41
{
42
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
43
        private readonly LoggerInterface $logger,
44
        private readonly InstitutionConfigurationOptionsService $configurationOptionsService,
45
        private readonly RecoveryTokenService    $recoveryTokenService,
46
        private readonly AuthorizationService    $authorizationService,
47
        private readonly SecondFactorTypeService $secondFactorTypeService,
48
        private readonly SecondFactorService $secondFactorService,
49
        private readonly RegistrationExpirationHelper $registrationExpirationHelper,
50
    ) {
51
        parent::__construct($logger, $configurationOptionsService);
52
    }
53
    #[Template('second_factor/list.html.twig')]
54
    #[Route(path: '/overview', name: 'ss_second_factor_list', methods:  ['GET'])]
55
    public function list(): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function list()
Loading history...
56
    {
57
        $identity = $this->getIdentity();
58
        $institution = $this->getIdentity()->institution;
59
        $options = $this->configurationOptionsService
60
            ->getInstitutionConfigurationOptionsFor($institution);
61
62
        // Get all available second factors from the config.
63
        $allSecondFactors = $this->getParameter('ss.enabled_second_factors');
64
65
        $secondFactors = $this->secondFactorService->getSecondFactorsForIdentity(
66
            $identity,
67
            $allSecondFactors,
68
            $options->allowedSecondFactors,
69
            $options->numberOfTokensPerIdentity
70
        );
71
72
        /** @var RecoveryTokenService $recoveryTokenService */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
73
        $recoveryTokenService = $this->recoveryTokenService;
74
        /** @var AuthorizationService $authorizationService */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
75
        $authorizationService = $this->authorizationService;
76
        $recoveryTokensAllowed = $authorizationService->mayRegisterRecoveryTokens($identity);
77
        $selfAssertedTokenRegistration = $options->allowSelfAssertedTokens === true && $recoveryTokensAllowed;
78
        $hasRemainingTokenTypes = $recoveryTokenService->getRemainingTokenTypes($identity) !== [];
79
        $recoveryTokens = [];
80
        if ($selfAssertedTokenRegistration && $recoveryTokensAllowed) {
81
            $recoveryTokens = $recoveryTokenService->getRecoveryTokensForIdentity($identity);
82
        }
83
        $loaService = $this->secondFactorTypeService;
84
85
        return [
86
            'loaService' => $loaService,
87
            'email' => $identity->email,
88
            'maxNumberOfTokens' => $secondFactors->getMaximumNumberOfRegistrations(),
89
            'registrationsLeft' => $secondFactors->getRegistrationsLeft(),
90
            'unverifiedSecondFactors' => $secondFactors->unverified,
91
            'verifiedSecondFactors' => $secondFactors->verified,
92
            'vettedSecondFactors' => $secondFactors->vetted,
93
            'availableSecondFactors' => $secondFactors->available,
94
            'expirationHelper' => $this->registrationExpirationHelper,
95
            'selfAssertedTokenRegistration' => $selfAssertedTokenRegistration,
96
            'recoveryTokens' => $recoveryTokens,
97
            'hasRemainingRecoveryTokens' => $hasRemainingTokenTypes,
98
        ];
99
    }
100
101
    #[Template('second_factor/revoke.html.twig')]
102
    #[Route(
103
        path: '/second-factor/{state}/{secondFactorId}/revoke',
104
        name: 'ss_second_factor_revoke',
105
        requirements: ['state' => '^(unverified|verified|vetted)$'],
106
        methods: ['GET','POST']
107
    )]
108
    public function revoke(Request $request, string $state, string $secondFactorId): array|Response
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function revoke()
Loading history...
109
    {
110
        $identity = $this->getIdentity();
111
112
        if (!$this->secondFactorService->identityHasSecondFactorOfStateWithId($identity->id, $state, $secondFactorId)) {
0 ignored issues
show
Bug introduced by
It seems like $identity->id can also be of type null; however, parameter $identityId of Surfnet\StepupSelfServic...ndFactorOfStateWithId() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

112
        if (!$this->secondFactorService->identityHasSecondFactorOfStateWithId(/** @scrutinizer ignore-type */ $identity->id, $state, $secondFactorId)) {
Loading history...
113
            $this->logger->error(sprintf(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
114
                'Identity "%s" tried to revoke "%s" second factor "%s", but does not own that second factor',
115
                $identity->id,
116
                $state,
117
                $secondFactorId
118
            ));
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
119
            throw new NotFoundHttpException();
120
        }
121
122
        $secondFactor = match ($state) {
123
            'unverified' => $this->secondFactorService->findOneUnverified($secondFactorId),
124
            'verified' => $this->secondFactorService->findOneVerified($secondFactorId),
125
            'vetted' => $this->secondFactorService->findOneVetted($secondFactorId),
126
            default => throw new LogicException('There are no other types of second factor.'),
127
        };
128
129
        if ($secondFactor === null) {
130
            throw new NotFoundHttpException(
131
                sprintf("No %s second factor with id '%s' exists.", $state, $secondFactorId)
132
            );
133
        }
134
135
        $command = new RevokeCommand();
136
        $command->identity = $identity;
137
        $command->secondFactor = $secondFactor;
138
139
        $form = $this->createForm(RevokeSecondFactorType::class, $command)->handleRequest($request);
140
141
        if ($form->isSubmitted() && $form->isValid()) {
142
143
            if ($this->secondFactorService->revoke($command)) {
144
                $this->addFlash('success', 'ss.second_factor.revoke.alert.revocation_successful');
145
            } else {
146
                $this->addFlash('error', 'ss.second_factor.revoke.alert.revocation_failed');
147
            }
148
149
            return $this->redirectToRoute('ss_second_factor_list');
150
        }
151
152
        return [
153
            'form'         => $form->createView(),
154
            'secondFactor' => $secondFactor,
155
        ];
156
    }
157
}
158