Completed
Push — feature/post-binding ( d0c113 )
by
unknown
02:23
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\Adfs\ResponseHelper;
24
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Saml\ResponseFactory;
25
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\AdfsHelper;
26
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\LoaAliasLookupService;
27
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
28
use Symfony\Component\HttpFoundation\Request;
29
use Symfony\Component\HttpFoundation\Response;
30
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
31
32
class SecondFactorOnlyController extends Controller
33
{
34
    /**
35
     * @param Request $httpRequest
36
     * @return Response
37
     */
38
    public function ssoAction(Request $httpRequest)
39
    {
40
        $logger = $this->get('logger');
41
42
        if (!$this->getParameter('second_factor_only')) {
43
            $logger->notice('Access to ssoAction denied, second_factor_only parameter set to false.');
44
45
            throw $this->createAccessDeniedException('Second Factor Only feature is disabled');
46
        }
47
48
        $logger->notice('Received AuthnRequest on second-factor-only endpoint, started processing');
49
50
        // ADFS support
51
        $adfsHelper = $this->get('second_factor_only.adfs.request_helper');
52
        if ($adfsHelper->isAdfsRequest($httpRequest)) {
53
            $logger->notice('Received AuthnRequest from an ADFS');
54
            try {
55
                $httpRequest = $adfsHelper->transformRequest($httpRequest);
56
            } catch (Exception $e) {
57
                $logger->critical(sprintf('Could not process ADFS Request, error: "%s"', $e->getMessage()));
58
                return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
59
            }
60
        }
61
62
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
63
        $bindingFactory = $this->get('second_factor_only.http.binding_factory');
64
65
        try {
66
            $logger->notice('Determine what type of Binding is used in the Request');
67
            $binding = $bindingFactory->build($httpRequest);
68
            $originalRequest = $binding->receiveSignedAuthnRequestFrom($httpRequest);
69
        } catch (Exception $e) {
70
            $logger->critical(sprintf('Could not process Request, error: "%s"', $e->getMessage()));
71
72
            return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
73
        }
74
75
        $originalRequestId = $originalRequest->getRequestId();
76
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
77
        $logger->notice(sprintf(
78
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
79
            $originalRequest->getServiceProvider(),
80
            $originalRequest->getRequestId()
81
        ));
82
83
        $stateHandler = $this->get('gateway.proxy.state_handler');
84
        $stateHandler
85
            ->setRequestId($originalRequestId)
86
            ->setRequestServiceProvider($originalRequest->getServiceProvider())
87
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''))
88
            ->setResponseAction('SurfnetStepupGatewaySecondFactorOnlyBundle:SecondFactorOnly:respond')
89
            ->setResponseContextServiceId('second_factor_only.response_context');
90
91
        // Check if the NameID is provided and we may use it.
92
        $nameId = $originalRequest->getNameId();
93
        $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...
94
        $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...
95
            $originalRequest->getServiceProvider(),
96
            $nameId
97
        );
98
99
        if (!$serviceProviderMayUseSecondFactorOnly) {
100
            /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ResponseRenderingService $responseRendering */
101
            $responseRendering = $this->get('second_factor_only.response_rendering');
102
103
            return $responseRendering->renderRequesterFailureResponse($this->getResponseContext());
104
        }
105
106
        $stateHandler->saveIdentityNameId($nameId);
107
108
        // Check if the requested Loa is provided and supported.
109
        $loaId = $this->get('second_factor_only.loa_resolution')->with($logger)->resolve(
110
            $originalRequest->getAuthenticationContextClassRef()
111
        );
112
113
        if (empty($loaId)) {
114
            /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ResponseRenderingService $responseRendering */
115
            $responseRendering = $this->get('second_factor_only.response_rendering');
116
117
            return $responseRendering->renderRequesterFailureResponse($this->getResponseContext());
118
        }
119
120
        $stateHandler->setRequiredLoaIdentifier($loaId);
121
122
        $logger->notice('Forwarding to second factor controller for loa determination and handling');
123
124
        return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:selectSecondFactorForVerification');
125
    }
126
127
    /**
128
     * @return Response
129
     */
130
    public function respondAction()
131
    {
132
        $responseContext = $this->getResponseContext();
133
        $originalRequestId = $responseContext->getInResponseTo();
134
135
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
136
137
        if (!$this->getParameter('second_factor_only')) {
138
            $logger->notice(sprintf(
139
                'Access to %s denied, second_factor_only parameter set to false.',
140
                __METHOD__
141
            ));
142
            throw $this->createAccessDeniedException('Second Factor Only feature disabled');
143
        }
144
145
        $logger->notice('Creating second-factor-only Response');
146
147
        $selectedSecondFactorUuid = $this->getResponseContext()->getSelectedSecondFactor();
148
        if (!$selectedSecondFactorUuid) {
149
            $logger->error(
150
                'Cannot verify possession of an unknown second factor'
151
            );
152
153
            throw new BadRequestHttpException('Cannot verify possession of an unknown second factor.');
154
        }
155
156
        if (!$responseContext->isSecondFactorVerified()) {
157
            $logger->error('Second factor was not verified');
158
            throw new BadRequestHttpException(
159
                'Cannot verify possession of an unknown second factor.'
160
            );
161
        }
162
163
        $secondFactor = $this->get('gateway.service.second_factor_service')
164
            ->findByUuid($selectedSecondFactorUuid);
165
        $secondFactorTypeService = $this->get('surfnet_stepup.service.second_factor_type');
166
        $grantedLoa = $this->get('surfnet_stepup.service.loa_resolution')
167
            ->getLoaByLevel($secondFactor->getLoaLevel($secondFactorTypeService));
168
169
        /** @var LoaAliasLookupService $loaAliasLookup */
170
        $loaAliasLookup = $this->get('second_factor_only.loa_alias_lookup');
171
        $authnContextClassRef = $loaAliasLookup->findAliasByLoa($grantedLoa);
172
173
        /** @var ResponseFactory $response_factory */
174
        $responseFactory = $this->get('second_factor_only.saml_response_factory');
175
        $response = $responseFactory->createSecondFactorOnlyResponse(
176
            $responseContext->getIdentityNameId(),
177
            $responseContext->getServiceProvider(),
178
            $authnContextClassRef
179
        );
180
181
        $responseContext->responseSent();
182
183
        $logger->notice(sprintf(
184
            'Responding to request "%s" with newly created response "%s"',
185
            $responseContext->getInResponseTo(),
186
            $response->getId()
187
        ));
188
189
        $responseRendering = $this->get('second_factor_only.response_rendering');
190
191
        $adfsHelper = $this->get('second_factor_only.adfs.response_helper');
192
        if ($adfsHelper->isAdfsResponse($originalRequestId)) {
193
            $xmlResponse = $responseRendering->getResponseAsXML($response);
194
            try {
195
                $adfsParameters = $adfsHelper->retrieveAdfsParameters();
196
            } catch (Exception $e) {
197
                $logger->critical(sprintf('Could not process ADFS Response parameters, error: "%s"', $e->getMessage()));
198
                return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
199
            }
200
201
            $logger->notice('Sending ACS Response to ADFS plugin');
202
            return $this->render(
203
                '@SurfnetStepupGatewaySecondFactorOnly/Adfs/consumeAssertion.html.twig',
204
                [
205
                    'acu' => $responseContext->getDestination(),
206
                    'response' => $xmlResponse,
207
                    'context' => $adfsParameters->getContext(),
208
                    'authMethod' => $adfsParameters->getAuthMethod(),
209
                    'requestId' => $adfsParameters->getRequestId(),
210
                ]
211
            );
212
        }
213
        return $responseRendering->renderResponse($responseContext, $response);
214
    }
215
216
    /**
217
     * @return \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext
218
     */
219
    public function getResponseContext()
220
    {
221
        return $this->get('second_factor_only.response_context');
222
    }
223
}
224