Passed
Push — feature/symfony6-upgrade ( 166417...86e2b9 )
by Paul
06:45
created

SecondFactorController::revokeAction()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 57
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 36
c 0
b 0
f 0
nc 5
nop 3
dl 0
loc 57
rs 8.7217

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
/**
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
 */
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...
18
19
namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;
20
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
22
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
23
use Surfnet\StepupSelfService\SelfServiceBundle\Command\RevokeCommand;
24
use Surfnet\StepupSelfService\SelfServiceBundle\Form\Type\RevokeSecondFactorType;
25
use Surfnet\StepupSelfService\SelfServiceBundle\Service\AuthorizationService;
26
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
27
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfAssertedTokens\RecoveryTokenService;
28
use Symfony\Component\HttpFoundation\Request;
29
use Symfony\Component\HttpFoundation\Response;
30
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
31
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
32
use Symfony\Component\Routing\Annotation\Route;
33
34
class SecondFactorController extends Controller
0 ignored issues
show
Coding Style introduced by
Missing doc comment for class SecondFactorController
Loading history...
35
{
36
    public function __construct(private \Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfAssertedTokens\RecoveryTokenService $recoveryTokenService, private \Surfnet\StepupSelfService\SelfServiceBundle\Service\AuthorizationService $authorizationService, private \Surfnet\StepupBundle\Service\SecondFactorTypeService $secondFactorTypeService)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
37
    {
38
    }
39
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
40
     * @Template
41
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
42
    #[Route(path: '/overview', name: 'ss_second_factor_list', methods:  ['GET'])]
43
    public function list(): array
44
    {
45
        $identity = $this->getIdentity();
46
        $institution = $this->getIdentity()->institution;
47
        $options = $this->get('self_service.service.institution_configuration_options')
0 ignored issues
show
Bug introduced by
The method get() does not exist on Surfnet\StepupSelfServic...\SecondFactorController. ( Ignorable by Annotation )

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

47
        $options = $this->/** @scrutinizer ignore-call */ get('self_service.service.institution_configuration_options')

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
48
            ->getInstitutionConfigurationOptionsFor($institution);
49
        /** @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...
50
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
51
        // Get all available second factors from the config.
52
        $allSecondFactors = $this->getParameter('ss.enabled_second_factors');
53
54
        $expirationHelper = $this->get('surfnet_stepup.registration_expiration_helper');
55
56
        $secondFactors = $service->getSecondFactorsForIdentity(
57
            $identity,
58
            $allSecondFactors,
59
            $options->allowedSecondFactors,
60
            $options->numberOfTokensPerIdentity
61
        );
62
63
        /** @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...
64
        $recoveryTokenService = $this->recoveryTokenService;
65
        /** @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...
66
        $authorizationService = $this->authorizationService;
67
        $recoveryTokensAllowed = $authorizationService->mayRegisterRecoveryTokens($identity);
68
        $selfAssertedTokenRegistration = $options->allowSelfAssertedTokens === true && $recoveryTokensAllowed;
69
        $hasRemainingTokenTypes = $recoveryTokenService->getRemainingTokenTypes($identity) !== [];
70
        $recoveryTokens = [];
71
        if ($selfAssertedTokenRegistration && $recoveryTokensAllowed) {
72
            $recoveryTokens = $recoveryTokenService->getRecoveryTokensForIdentity($identity);
73
        }
74
        $loaService = $this->secondFactorTypeService;
75
76
        return [
77
            'loaService' => $loaService,
78
            'email' => $identity->email,
79
            'maxNumberOfTokens' => $secondFactors->getMaximumNumberOfRegistrations(),
80
            'registrationsLeft' => $secondFactors->getRegistrationsLeft(),
81
            'unverifiedSecondFactors' => $secondFactors->unverified,
82
            'verifiedSecondFactors' => $secondFactors->verified,
83
            'vettedSecondFactors' => $secondFactors->vetted,
84
            'availableSecondFactors' => $secondFactors->available,
85
            'expirationHelper' => $expirationHelper,
86
            'selfAssertedTokenRegistration' => $selfAssertedTokenRegistration,
87
            'recoveryTokens' => $recoveryTokens,
88
            'hasRemainingRecoveryTokens' => $hasRemainingTokenTypes,
89
        ];
90
    }
91
92
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $request should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $state should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $secondFactorId should have a doc-comment as per coding-style.
Loading history...
93
     * @Template
94
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
95
    #[Route(
96
        path: '/second-factor/{state}/{secondFactorId}/revoke',
97
        name: 'ss_second_factor_revoke',
98
        requirements: ['state' => '^(unverified|verified|vetted)$'],
99
        methods: ['GET','POST']
100
    )]
101
    public function revoke(Request $request, string $state, string $secondFactorId): array|Response
102
    {
103
        $identity = $this->getIdentity();
104
105
        /** @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...
106
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
107
        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

107
        if (!$service->identityHasSecondFactorOfStateWithId(/** @scrutinizer ignore-type */ $identity->id, $state, $secondFactorId)) {
Loading history...
108
            $this->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...
109
                'Identity "%s" tried to revoke "%s" second factor "%s", but does not own that second factor',
110
                $identity->id,
111
                $state,
112
                $secondFactorId
113
            ));
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...
114
            throw new NotFoundHttpException();
115
        }
116
117
        $secondFactor = match ($state) {
118
            'unverified' => $service->findOneUnverified($secondFactorId),
119
            'verified' => $service->findOneVerified($secondFactorId),
120
            'vetted' => $service->findOneVetted($secondFactorId),
121
            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...
122
        };
123
124
        if ($secondFactor === null) {
125
            throw new NotFoundHttpException(
126
                sprintf("No %s second factor with id '%s' exists.", $state, $secondFactorId)
127
            );
128
        }
129
130
        $command = new RevokeCommand();
131
        $command->identity = $identity;
132
        $command->secondFactor = $secondFactor;
133
134
        $form = $this->createForm(RevokeSecondFactorType::class, $command)->handleRequest($request);
135
136
        if ($form->isSubmitted() && $form->isValid()) {
137
            /** @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...
138
            $flashBag = $this->get('session')->getFlashBag();
139
140
            if ($service->revoke($command)) {
141
                $flashBag->add('success', 'ss.second_factor.revoke.alert.revocation_successful');
142
            } else {
143
                $flashBag->add('error', 'ss.second_factor.revoke.alert.revocation_failed');
144
            }
145
146
            return $this->redirectToRoute('ss_second_factor_list');
147
        }
148
149
        return [
150
            'form'         => $form->createView(),
151
            'secondFactor' => $secondFactor,
152
        ];
153
    }
154
}
155