Passed
Pull Request — main (#308)
by Paul
13:29 queued 06:46
created

SecondFactorController   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 119
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 74
dl 0
loc 119
rs 10
c 1
b 0
f 0
wmc 11

3 Methods

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

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