Completed
Pull Request — develop (#92)
by Boy
03:20
created

GatewayController::ssoAction()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 58
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 58
rs 9.0077
cc 4
eloc 36
nc 3
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\GatewayBundle\Controller;
20
21
use Exception;
22
use SAML2_Assertion;
23
use SAML2_Const;
24
use SAML2_Response;
25
use Surfnet\SamlBundle\SAML2\AuthnRequest;
26
use Surfnet\SamlBundle\SAML2\AuthnRequestFactory;
27
use Surfnet\StepupGateway\GatewayBundle\Saml\AssertionAdapter;
28
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpFoundation\Response;
31
use Symfony\Component\HttpKernel\Exception\HttpException;
32
33
class GatewayController extends Controller
34
{
35
    public function ssoAction(Request $httpRequest)
36
    {
37
        /** @var \Psr\Log\LoggerInterface $logger */
38
        $logger = $this->get('logger');
39
        $logger->notice('Received AuthnRequest, started processing');
40
41
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
42
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
43
44
        try {
45
            $originalRequest = $redirectBinding->processUnsignedRequest($httpRequest);
0 ignored issues
show
Bug introduced by
The method processUnsignedRequest() does not seem to exist on object<Surfnet\SamlBundle\Http\RedirectBinding>.

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...
46
        } catch (Exception $e) {
47
            $logger->critical(sprintf('Could not process Request, error: "%s"', $e->getMessage()));
48
49
            return $this->render('unrecoverableError');
50
        }
51
52
        $originalRequestId = $originalRequest->getRequestId();
53
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
54
        $logger->notice(sprintf(
55
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
56
            $originalRequest->getServiceProvider(),
57
            $originalRequest->getRequestId()
58
        ));
59
60
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\Proxy\ProxyStateHandler $stateHandler */
61
        $stateHandler = $this->get('gateway.proxy.state_handler');
62
        $stateHandler
63
            ->setRequestId($originalRequestId)
64
            ->setRequestServiceProvider($originalRequest->getServiceProvider())
65
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''));
66
67
        // check if the requested Loa is supported
68
        $requiredLoa = $originalRequest->getAuthenticationContextClassRef();
69
        if ($requiredLoa && !$this->get('surfnet_stepup.service.loa_resolution')->hasLoa($requiredLoa)) {
70
            $logger->info(sprintf(
71
                'Requested required Loa "%s" does not exist, sending response with status Requester Error',
72
                $requiredLoa
73
            ));
74
        }
75
        $stateHandler->setRequiredLoaIdentifier($requiredLoa);
76
77
        $proxyRequest = AuthnRequestFactory::createNewRequest(
78
            $this->get('surfnet_saml.hosted.service_provider'),
79
            $this->get('surfnet_saml.remote.idp')
80
        );
81
82
        $proxyRequest->setScoping([$originalRequest->getServiceProvider()]);
83
        $stateHandler->setGatewayRequestId($proxyRequest->getRequestId());
84
85
        $logger->notice(sprintf(
86
            'Sending Proxy AuthnRequest with request ID: "%s" for original AuthnRequest "%s"',
87
            $proxyRequest->getRequestId(),
88
            $originalRequest->getRequestId()
89
        ));
90
91
        return $redirectBinding->createRedirectResponseFor($proxyRequest);
92
    }
93
94
    public function proxySsoAction()
95
    {
96
        throw new HttpException(418, 'Not Yet Implemented');
97
    }
98
99
    /**
100
     * @param Request $request
101
     * @return \Symfony\Component\HttpFoundation\Response
102
     */
103
    public function consumeAssertionAction(Request $request)
104
    {
105
        $responseContext = $this->getResponseContext();
106
        $originalRequestId = $responseContext->getInResponseTo();
107
108
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
109
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
110
        $logger->notice('Received SAMLResponse, attempting to process for Proxy Response');
111
112
        try {
113
            /** @var \SAML2_Assertion $assertion */
114
            $assertion = $this->get('surfnet_saml.http.post_binding')->processResponse(
115
                $request,
116
                $this->get('surfnet_saml.remote.idp'),
117
                $this->get('surfnet_saml.hosted.service_provider')
118
            );
119
        } catch (Exception $exception) {
120
            $logger->error(sprintf('Could not process received Response, error: "%s"', $exception->getMessage()));
121
122
            $response = $this->createResponseFailureResponse($responseContext);
123
124
            return $this->renderSamlResponse('unprocessableResponse', $response);
125
        }
126
127
        $adaptedAssertion = new AssertionAdapter($assertion);
128
        $expectedInResponseTo = $responseContext->getExpectedInResponseTo();
129 View Code Duplication
        if (!$adaptedAssertion->inResponseToMatches($expectedInResponseTo)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
            $logger->critical(sprintf(
131
                'Received Response with unexpected InResponseTo: "%s", %s',
132
                $adaptedAssertion->getInResponseTo(),
133
                ($expectedInResponseTo ? 'expected "' . $expectedInResponseTo . '"' : ' no response expected')
134
            ));
135
136
            return $this->render('unrecoverableError');
137
        }
138
139
        $logger->notice('Successfully processed SAMLResponse');
140
141
        $responseContext->saveAssertion($assertion);
142
143
        $logger->notice(sprintf('Forwarding to second factor controller for loa determination and handling'));
144
145
        return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:selectSecondFactorForVerification');
146
    }
147
148
    public function respondAction()
149
    {
150
        $responseContext = $this->getResponseContext();
151
        $originalRequestId = $responseContext->getInResponseTo();
152
153
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
154
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
155
        $logger->notice('Creating Response');
156
157
        $grantedLoa = null;
158
        if ($responseContext->isSecondFactorVerified()) {
159
            $secondFactor = $this->get('gateway.service.second_factor_service')->findByUuid(
160
                $responseContext->getSelectedSecondFactor()
161
            );
162
163
            $grantedLoa = $this->get('surfnet_stepup.service.loa_resolution')->getLoaByLevel(
164
                $secondFactor->getLoaLevel()
165
            );
166
        }
167
168
        /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ProxyResponseService $proxyResponseService */
169
        $proxyResponseService = $this->get('gateway.service.response_proxy');
170
        $response             = $proxyResponseService->createProxyResponse(
171
            $responseContext->reconstituteAssertion(),
172
            $responseContext->getServiceProvider(),
173
            (string) $grantedLoa
174
        );
175
176
        $responseContext->responseSent();
177
178
        $logger->notice(sprintf(
179
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
180
            $responseContext->getInResponseTo(),
181
            $response->getId()
182
        ));
183
184
        return $this->renderSamlResponse('consumeAssertion', $response);
185
    }
186
187 View Code Duplication
    public function sendLoaCannotBeGivenAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
    {
189
        $responseContext = $this->getResponseContext();
190
        $originalRequestId = $responseContext->getInResponseTo();
191
192
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
193
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
194
        $logger->notice('Loa cannot be given, creating Response with NoAuthnContext status');
195
196
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
197
        $responseBuilder = $this->get('gateway.proxy.response_builder');
198
199
        $response = $responseBuilder
200
            ->createNewResponse($responseContext)
201
            ->setResponseStatus(SAML2_Const::STATUS_RESPONDER, SAML2_Const::STATUS_NO_AUTHN_CONTEXT)
202
            ->get();
203
204
        $logger->notice(sprintf(
205
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
206
            $responseContext->getInResponseTo(),
207
            $response->getId()
208
        ));
209
210
        return $this->renderSamlResponse('consumeAssertion', $response);
211
    }
212
213 View Code Duplication
    public function sendAuthenticationCancelledByUserAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
214
    {
215
        $responseContext = $this->getResponseContext();
216
        $originalRequestId = $responseContext->getInResponseTo();
217
218
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
219
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
220
        $logger->notice('Authentication was cancelled by the user, creating Response with AuthnFailed status');
221
222
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
223
        $responseBuilder = $this->get('gateway.proxy.response_builder');
224
225
        $response = $responseBuilder
226
            ->createNewResponse($responseContext)
227
            ->setResponseStatus(
228
                SAML2_Const::STATUS_RESPONDER,
229
                SAML2_Const::STATUS_AUTHN_FAILED,
230
                'Authentication cancelled by user'
231
            )
232
            ->get();
233
234
        $logger->notice(sprintf(
235
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
236
            $responseContext->getInResponseTo(),
237
            $response->getId()
238
        ));
239
240
        return $this->renderSamlResponse('consumeAssertion', $response);
241
    }
242
243
    /**
244
     * @param string         $view
245
     * @param SAML2_Response $response
246
     * @return Response
247
     */
248 View Code Duplication
    public function renderSamlResponse($view, SAML2_Response $response)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
249
    {
250
        $responseContext = $this->getResponseContext();
251
252
        return $this->render($view, [
253
            'acu'        => $responseContext->getDestination(),
254
            'response'   => $this->getResponseAsXML($response),
255
            'relayState' => $responseContext->getRelayState()
256
        ]);
257
    }
258
259
    /**
260
     * @param string   $view
261
     * @param array    $parameters
262
     * @param Response $response
0 ignored issues
show
Documentation introduced by
Should the type for parameter $response not be null|Response?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
263
     * @return Response
264
     */
265
    public function render($view, array $parameters = array(), Response $response = null)
266
    {
267
        return parent::render(
268
            'SurfnetStepupGatewayGatewayBundle:Gateway:' . $view . '.html.twig',
269
            $parameters,
270
            $response
271
        );
272
    }
273
274
    /**
275
     * @return \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext
276
     */
277
    public function getResponseContext()
278
    {
279
        return $this->get('gateway.proxy.response_context');
280
    }
281
282
    /**
283
     * @param SAML2_Response $response
284
     * @return string
285
     */
286
    private function getResponseAsXML(SAML2_Response $response)
287
    {
288
        return base64_encode($response->toUnsignedXML()->ownerDocument->saveXML());
289
    }
290
291
    /**
292
     * @return SAML2_Response
293
     */
294
    private function createRequesterFailureResponse()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
295
    {
296
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
297
        $responseBuilder = $this->get('gateway.proxy.response_builder');
298
        $context = $this->getResponseContext();
299
300
        $response = $responseBuilder
301
            ->createNewResponse($context)
302
            ->setResponseStatus(SAML2_Const::STATUS_REQUESTER, SAML2_Const::STATUS_REQUEST_UNSUPPORTED)
303
            ->get();
304
305
        return $response;
306
307
    }
308
309
    /**
310
     * @param $context
311
     * @return SAML2_Response
312
     */
313
    private function createResponseFailureResponse($context)
314
    {
315
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
316
        $responseBuilder = $this->get('gateway.proxy.response_builder');
317
318
        $response = $responseBuilder
319
            ->createNewResponse($context)
320
            ->setResponseStatus(SAML2_Const::STATUS_RESPONDER)
321
            ->get();
322
323
        return $response;
324
    }
325
}
326