Passed
Pull Request — main (#308)
by Paul
18:42 queued 09:10
created

consumeSelfVetAssertion()   B

Complexity

Conditions 6
Paths 15

Size

Total Lines 60
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 38
c 1
b 0
f 0
nc 15
nop 2
dl 0
loc 60
rs 8.6897

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 2021 SURFnet B.V.
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\SelfVet;
22
23
use Exception;
24
use Psr\Log\LoggerInterface;
25
use Surfnet\SamlBundle\Entity\IdentityProvider;
26
use Surfnet\SamlBundle\Entity\ServiceProvider;
27
use Surfnet\SamlBundle\Http\PostBinding;
28
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
29
use Surfnet\SamlBundle\SAML2\Response\Assertion\InResponseTo;
30
use Surfnet\StepupSelfService\SelfServiceBundle\Command\SelfVetCommand;
31
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
32
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfVetMarshaller;
33
use Surfnet\StepupSelfService\SelfServiceBundle\Value\SelfVetRequestId;
34
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
35
use Symfony\Component\HttpFoundation\RedirectResponse;
36
use Symfony\Component\HttpFoundation\Request;
37
use Symfony\Component\HttpFoundation\RequestStack;
38
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
39
use Symfony\Component\Routing\Attribute\Route;
40
use Symfony\Component\Security\Core\Exception\AuthenticationException;
41
42
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
43
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - Controllers are prone to higher coupling. This one is no exception
44
 * TODO: Split up into smaller controllers
45
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
46
class SelfVetConsumeController extends AbstractController
47
{
48
    final public const SELF_VET_SESSION_ID = 'second_factor_self_vet_request_id';
49
50
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
51
        private readonly LoggerInterface          $logger,
52
        private readonly SecondFactorService      $secondFactorService,
53
        private readonly SelfVetMarshaller        $selfVetMarshaller,
54
        private readonly ServiceProvider          $serviceProvider,
55
        private readonly IdentityProvider         $identityProvider,
56
        private readonly PostBinding              $postBinding,
57
        private readonly SamlAuthenticationLogger $samlAuthenticationLogger,
58
        private readonly RequestStack             $requestStack,
59
    ) {
60
    }
61
62
    #[Route(
63
        path: '/second-factor/{secondFactorId}/self-vet-consume-assertion',
64
        name: 'ss_second_factor_self_vet_consume_assertion',
65
        methods: ['POST'],
66
    )]
67
    public function consumeSelfVetAssertion(Request $httpRequest, string $secondFactorId): RedirectResponse
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function consumeSelfVetAssertion()
Loading history...
68
    {
69
        $identity = $this->getUser()->getIdentity();
0 ignored issues
show
Bug introduced by
The method getIdentity() does not exist on Symfony\Component\Security\Core\User\UserInterface. It seems like you code against a sub-type of Symfony\Component\Security\Core\User\UserInterface such as Surfnet\StepupSelfServic...n\AuthenticatedIdentity. ( Ignorable by Annotation )

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

69
        $identity = $this->getUser()->/** @scrutinizer ignore-call */ getIdentity();
Loading history...
70
        if (!$this->selfVetMarshaller->isAllowed($identity, $secondFactorId)) {
71
            throw $this->createNotFoundException();
72
        }
73
74
        if (!$this->requestStack->getSession()->has(self::SELF_VET_SESSION_ID)) {
75
            $this->logger->error(
76
                'Received an authentication response for self vetting a second factor, but no response was expected'
77
            );
78
            throw new AccessDeniedHttpException('Did not expect an authentication response');
79
        }
80
81
        $this->logger->notice('Received an authentication response for self vetting a second factor');
82
83
        /** @var SelfVetRequestId $initiatedRequestId */
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...
84
        $initiatedRequestId = $this->requestStack->getSession()->get(self::SELF_VET_SESSION_ID);
85
86
        $samlLogger = $this->samlAuthenticationLogger->forAuthentication($initiatedRequestId->requestId());
87
88
        $this->requestStack->getSession()->remove(self::SELF_VET_SESSION_ID);
89
90
        try {
91
            $assertion = $this->postBinding->processResponse(
92
                $httpRequest,
93
                $this->identityProvider,
94
                $this->serviceProvider
95
            );
96
97
            if (!InResponseTo::assertEquals($assertion, $initiatedRequestId->requestId())) {
98
                $samlLogger->error(
99
                    sprintf(
100
                        'Expected a response to the request with ID "%s", but the SAMLResponse was a response to a different request',
101
                        $initiatedRequestId
0 ignored issues
show
Bug introduced by
$initiatedRequestId of type Surfnet\StepupSelfServic...\Value\SelfVetRequestId is incompatible with the type double|integer|string expected by parameter $values of sprintf(). ( Ignorable by Annotation )

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

101
                        /** @scrutinizer ignore-type */ $initiatedRequestId
Loading history...
102
                    )
103
                );
104
                throw new AuthenticationException('Unexpected InResponseTo in SAMLResponse');
105
            }
106
            $candidateSecondFactor = $this->secondFactorService->findOneVerified($secondFactorId);
107
            // Proof of possession of higher/equal LoA was successful, now apply the self vet command on Middleware
108
            $command = new SelfVetCommand();
109
            $command->identity = $this->getUser()->getIdentity();
110
            $command->secondFactor = $candidateSecondFactor;
111
            $command->authoringLoa = $assertion->getAuthnContextClassRef();
112
113
            if ($this->secondFactorService->selfVet($command)) {
114
                $this->addFlash('success', 'ss.self_vet.second_factor.alert.successful');
115
            } else {
116
                $this->addFlash('error', 'ss.self_vet.second_factor.alert.failed');
117
            }
118
        } catch (Exception) {
119
            $this->addFlash('error', 'ss.self_vet.second_factor.verification_failed');
120
        }
121
        return $this->redirectToRoute('ss_second_factor_list');
122
    }
123
}
124