Completed
Push — feature/post-binding-without-c... ( c3fb1f )
by
unknown
02:20
created

SecondFactorOnlyController::ssoAction()   C

Complexity

Conditions 7
Paths 14

Size

Total Lines 88
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 88
rs 6.5184
cc 7
eloc 52
nc 14
nop 1

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
 */
18
19
namespace Surfnet\StepupGateway\SecondFactorOnlyBundle\Controller;
20
21
use Exception;
22
use Surfnet\SamlBundle\SAML2\AuthnRequest;
23
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Saml\ResponseFactory;
24
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\AdfsHelper;
25
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\LoaAliasLookupService;
26
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
27
use Symfony\Component\HttpFoundation\Request;
28
use Symfony\Component\HttpFoundation\Response;
29
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
30
31
class SecondFactorOnlyController extends Controller
32
{
33
    /**
34
     * @param Request $httpRequest
35
     * @return Response
36
     */
37
    public function ssoAction(Request $httpRequest)
38
    {
39
        $logger = $this->get('logger');
40
41
        if (!$this->getParameter('second_factor_only')) {
42
            $logger->notice('Access to ssoAction denied, second_factor_only parameter set to false.');
43
44
            throw $this->createAccessDeniedException('Second Factor Only feature is disabled');
45
        }
46
47
        $logger->notice('Received AuthnRequest on second-factor-only endpoint, started processing');
48
49
        // ADFS support
50
        $adfsHelper = $this->get('second_factor_only.adfs.request_helper');
51
        if ($adfsHelper->isAdfsRequest($httpRequest)) {
52
            $logger->notice('Received AuthnRequest from an ADFS');
53
            try {
54
                $httpRequest = $adfsHelper->transformRequest($httpRequest);
55
            } catch (Exception $e) {
56
                $logger->critical(sprintf('Could not process ADFS Request, error: "%s"', $e->getMessage()));
57
                return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
58
            }
59
        }
60
61
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
62
        $bindingFactory = $this->get('second_factor_only.http.binding_factory');
63
64
        try {
65
            $logger->notice('Determine what type of Binding is used in the Request');
66
            $binding = $bindingFactory->build($httpRequest);
67
            $originalRequest = $binding->receiveSignedAuthnRequestFrom($httpRequest);
68
        } catch (Exception $e) {
69
            $logger->critical(sprintf('Could not process Request, error: "%s"', $e->getMessage()));
70
71
            return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
72
        }
73
74
        $originalRequestId = $originalRequest->getRequestId();
75
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
76
        $logger->notice(sprintf(
77
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
78
            $originalRequest->getServiceProvider(),
79
            $originalRequest->getRequestId()
80
        ));
81
82
        $stateHandler = $this->get('gateway.proxy.state_handler');
83
        $stateHandler
84
            ->setRequestId($originalRequestId)
85
            ->setRequestServiceProvider($originalRequest->getServiceProvider())
86
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''))
87
            ->setResponseAction('SurfnetStepupGatewaySecondFactorOnlyBundle:SecondFactorOnly:respond')
88
            ->setResponseContextServiceId('second_factor_only.response_context');
89
90
        // Check if the NameID is provided and we may use it.
91
        $nameId = $originalRequest->getNameId();
92
        $secondFactorOnlyNameIdValidator = $this->get('second_factor_only.validate_nameid')->with($logger);
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $secondFactorOnlyNameIdValidator exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
93
        $serviceProviderMayUseSecondFactorOnly = $secondFactorOnlyNameIdValidator->validate(
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $serviceProviderMayUseSecondFactorOnly exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
94
            $originalRequest->getServiceProvider(),
95
            $nameId
96
        );
97
98
        if (!$serviceProviderMayUseSecondFactorOnly) {
99
            /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ResponseRenderingService $responseRendering */
100
            $responseRendering = $this->get('second_factor_only.response_rendering');
101
102
            return $responseRendering->renderRequesterFailureResponse($this->getResponseContext());
103
        }
104
105
        $stateHandler->saveIdentityNameId($nameId);
106
107
        // Check if the requested Loa is provided and supported.
108
        $loaId = $this->get('second_factor_only.loa_resolution')->with($logger)->resolve(
109
            $originalRequest->getAuthenticationContextClassRef()
110
        );
111
112
        if (empty($loaId)) {
113
            /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ResponseRenderingService $responseRendering */
114
            $responseRendering = $this->get('second_factor_only.response_rendering');
115
116
            return $responseRendering->renderRequesterFailureResponse($this->getResponseContext());
117
        }
118
119
        $stateHandler->setRequiredLoaIdentifier($loaId);
120
121
        $logger->notice('Forwarding to second factor controller for loa determination and handling');
122
123
        return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:selectSecondFactorForVerification');
124
    }
125
126
    /**
127
     * @return Response
128
     */
129
    public function respondAction()
130
    {
131
        $responseContext = $this->getResponseContext();
132
        $originalRequestId = $responseContext->getInResponseTo();
133
134
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
135
136
        if (!$this->getParameter('second_factor_only')) {
137
            $logger->notice(sprintf(
138
                'Access to %s denied, second_factor_only parameter set to false.',
139
                __METHOD__
140
            ));
141
            throw $this->createAccessDeniedException('Second Factor Only feature disabled');
142
        }
143
144
        $logger->notice('Creating second-factor-only Response');
145
146
        $selectedSecondFactorUuid = $this->getResponseContext()->getSelectedSecondFactor();
147
        if (!$selectedSecondFactorUuid) {
148
            $logger->error(
149
                'Cannot verify possession of an unknown second factor'
150
            );
151
152
            throw new BadRequestHttpException('Cannot verify possession of an unknown second factor.');
153
        }
154
155
        if (!$responseContext->isSecondFactorVerified()) {
156
            $logger->error('Second factor was not verified');
157
            throw new BadRequestHttpException(
158
                'Cannot verify possession of an unknown second factor.'
159
            );
160
        }
161
162
        $secondFactor = $this->get('gateway.service.second_factor_service')
163
            ->findByUuid($selectedSecondFactorUuid);
164
        $secondFactorTypeService = $this->get('surfnet_stepup.service.second_factor_type');
165
        $grantedLoa = $this->get('surfnet_stepup.service.loa_resolution')
166
            ->getLoaByLevel($secondFactor->getLoaLevel($secondFactorTypeService));
167
168
        /** @var LoaAliasLookupService $loaAliasLookup */
169
        $loaAliasLookup = $this->get('second_factor_only.loa_alias_lookup');
170
        $authnContextClassRef = $loaAliasLookup->findAliasByLoa($grantedLoa);
171
172
        /** @var ResponseFactory $response_factory */
173
        $responseFactory = $this->get('second_factor_only.saml_response_factory');
174
        $response = $responseFactory->createSecondFactorOnlyResponse(
175
            $responseContext->getIdentityNameId(),
176
            $responseContext->getServiceProvider(),
177
            $authnContextClassRef
178
        );
179
180
        $responseContext->responseSent();
181
182
        $logger->notice(sprintf(
183
            'Responding to request "%s" with newly created response "%s"',
184
            $responseContext->getInResponseTo(),
185
            $response->getId()
186
        ));
187
188
        $responseRendering = $this->get('second_factor_only.response_rendering');
189
190
        $adfsHelper = $this->get('second_factor_only.adfs.response_helper');
191
        if ($adfsHelper->isAdfsResponse($originalRequestId)) {
192
            $xmlResponse = $responseRendering->getResponseAsXML($response);
193
            try {
194
                $adfsParameters = $adfsHelper->retrieveAdfsParameters();
195
            } catch (Exception $e) {
196
                $logger->critical(sprintf('Could not process ADFS Response parameters, error: "%s"', $e->getMessage()));
197
                return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
198
            }
199
200
            $logger->notice('Sending ACS Response to ADFS plugin');
201
            return $this->render(
202
                '@SurfnetStepupGatewaySecondFactorOnly/Adfs/consumeAssertion.html.twig',
203
                [
204
                    'acu' => $responseContext->getDestination(),
205
                    'samlResponse' => $xmlResponse,
206
                    'context' => $adfsParameters->getContext(),
207
                    'authMethod' => $adfsParameters->getAuthMethod(),
208
                ]
209
            );
210
        }
211
        return $responseRendering->renderResponse($responseContext, $response);
212
    }
213
214
    /**
215
     * @return \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext
216
     */
217
    public function getResponseContext()
218
    {
219
        return $this->get('second_factor_only.response_context');
220
    }
221
}
222