Passed
Pull Request — main (#308)
by Paul
24:50 queued 14:16
created

SecondFactorController::revoke()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 58
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 37
nc 5
nop 3
dl 0
loc 58
rs 8.7057
c 0
b 0
f 0

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
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 Surfnet\StepupBundle\DateTime\RegistrationExpirationHelper;
24
use Psr\Log\LoggerInterface;
25
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
26
use Surfnet\StepupSelfService\SelfServiceBundle\Command\RevokeCommand;
27
use Surfnet\StepupSelfService\SelfServiceBundle\Form\Type\RevokeSecondFactorType;
28
use Surfnet\StepupSelfService\SelfServiceBundle\Service\AuthorizationService;
29
use Surfnet\StepupSelfService\SelfServiceBundle\Service\InstitutionConfigurationOptionsService;
30
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
31
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfAssertedTokens\RecoveryTokenService;
32
use Symfony\Bridge\Twig\Attribute\Template;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
use Symfony\Component\Routing\Annotation\Route;
38
39
class SecondFactorController extends Controller
0 ignored issues
show
Coding Style introduced by
Missing doc comment for class SecondFactorController
Loading history...
40
{
41
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
42
        LoggerInterface $logger,
43
        private readonly InstitutionConfigurationOptionsService $configurationOptionsService,
44
        private readonly RecoveryTokenService    $recoveryTokenService,
45
        private readonly AuthorizationService    $authorizationService,
46
        private readonly SecondFactorTypeService $secondFactorTypeService,
47
        private readonly SecondFactorService $secondFactorService,
48
        private readonly RegistrationExpirationHelper $registrationExpirationHelper,
49
    ) {
50
        parent::__construct($logger, $configurationOptionsService);
51
    }
52
    #[Template('second_factor/list.html.twig')]
53
    #[Route(path: '/overview', name: 'ss_second_factor_list', methods:  ['GET'])]
54
    public function list(): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function list()
Loading history...
55
    {
56
        $identity = $this->getIdentity();
57
        $institution = $this->getIdentity()->institution;
58
        $options = $this->configurationOptionsService
59
            ->getInstitutionConfigurationOptionsFor($institution);
60
61
        // Get all available second factors from the config.
62
        $allSecondFactors = $this->getParameter('ss.enabled_second_factors');
63
64
        $secondFactors = $this->secondFactorService->getSecondFactorsForIdentity(
65
            $identity,
66
            $allSecondFactors,
67
            $options->allowedSecondFactors,
68
            $options->numberOfTokensPerIdentity
69
        );
70
71
        /** @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...
72
        $recoveryTokenService = $this->recoveryTokenService;
73
        /** @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...
74
        $authorizationService = $this->authorizationService;
75
        $recoveryTokensAllowed = $authorizationService->mayRegisterRecoveryTokens($identity);
76
        $selfAssertedTokenRegistration = $options->allowSelfAssertedTokens === true && $recoveryTokensAllowed;
77
        $hasRemainingTokenTypes = $recoveryTokenService->getRemainingTokenTypes($identity) !== [];
78
        $recoveryTokens = [];
79
        if ($selfAssertedTokenRegistration && $recoveryTokensAllowed) {
80
            $recoveryTokens = $recoveryTokenService->getRecoveryTokensForIdentity($identity);
81
        }
82
        $loaService = $this->secondFactorTypeService;
83
84
        return [
85
            'loaService' => $loaService,
86
            'email' => $identity->email,
87
            'maxNumberOfTokens' => $secondFactors->getMaximumNumberOfRegistrations(),
88
            'registrationsLeft' => $secondFactors->getRegistrationsLeft(),
89
            'unverifiedSecondFactors' => $secondFactors->unverified,
90
            'verifiedSecondFactors' => $secondFactors->verified,
91
            'vettedSecondFactors' => $secondFactors->vetted,
92
            'availableSecondFactors' => $secondFactors->available,
93
            'expirationHelper' => $this->registrationExpirationHelper,
94
            'selfAssertedTokenRegistration' => $selfAssertedTokenRegistration,
95
            'recoveryTokens' => $recoveryTokens,
96
            'hasRemainingRecoveryTokens' => $hasRemainingTokenTypes,
97
        ];
98
    }
99
100
    #[Template('second_factor/revoke.html.twig')]
101
    #[Route(
102
        path: '/second-factor/{state}/{secondFactorId}/revoke',
103
        name: 'ss_second_factor_revoke',
104
        requirements: ['state' => '^(unverified|verified|vetted)$'],
105
        methods: ['GET','POST']
106
    )]
107
    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...
108
    {
109
        $identity = $this->getIdentity();
110
111
        /** @var SecondFactorService $service */
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...
112
        $service = $this->container->get('surfnet_stepup_self_service_self_service.service.second_factor');
113
        if (!$service->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

113
        if (!$service->identityHasSecondFactorOfStateWithId(/** @scrutinizer ignore-type */ $identity->id, $state, $secondFactorId)) {
Loading history...
114
            $this->container->get('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...
115
                'Identity "%s" tried to revoke "%s" second factor "%s", but does not own that second factor',
116
                $identity->id,
117
                $state,
118
                $secondFactorId
119
            ));
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...
120
            throw new NotFoundHttpException();
121
        }
122
123
        $secondFactor = match ($state) {
124
            'unverified' => $service->findOneUnverified($secondFactorId),
125
            'verified' => $service->findOneVerified($secondFactorId),
126
            'vetted' => $service->findOneVetted($secondFactorId),
127
            default => throw new LogicException('There are no other types of second factor.'),
0 ignored issues
show
Bug introduced by
The type Surfnet\StepupSelfServic...ntroller\LogicException was not found. Did you mean LogicException? If so, make sure to prefix the type with \.
Loading history...
128
        };
129
130
        if ($secondFactor === null) {
131
            throw new NotFoundHttpException(
132
                sprintf("No %s second factor with id '%s' exists.", $state, $secondFactorId)
133
            );
134
        }
135
136
        $command = new RevokeCommand();
137
        $command->identity = $identity;
138
        $command->secondFactor = $secondFactor;
139
140
        $form = $this->createForm(RevokeSecondFactorType::class, $command)->handleRequest($request);
141
142
        if ($form->isSubmitted() && $form->isValid()) {
143
            /** @var FlashBagInterface $flashBag */
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...
144
            $flashBag = $this->container->get('session')->getFlashBag();
145
146
            if ($service->revoke($command)) {
147
                $flashBag->add('success', 'ss.second_factor.revoke.alert.revocation_successful');
148
            } else {
149
                $flashBag->add('error', 'ss.second_factor.revoke.alert.revocation_failed');
150
            }
151
152
            return $this->redirectToRoute('ss_second_factor_list');
153
        }
154
155
        return [
156
            'form'         => $form->createView(),
157
            'secondFactor' => $secondFactor,
158
        ];
159
    }
160
}
161