Passed
Push — master ( c4afc2...9cde23 )
by Pieter van der
27:49 queued 12:42
created

displayVettingTypesAction()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 56
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 32
nc 4
nop 2
dl 0
loc 56
rs 8.7857
c 1
b 0
f 0

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\StepupSelfService\SelfServiceBundle\Controller;
20
21
use DateInterval;
22
use Mpdf\Mpdf;
23
use Mpdf\Output\Destination as MpdfDestination;
24
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
25
use Surfnet\StepupSelfService\SamlStepupProviderBundle\Provider\ViewConfig;
26
use Surfnet\StepupSelfService\SelfServiceBundle\Service\RaLocationService;
27
use Surfnet\StepupSelfService\SelfServiceBundle\Service\RaService;
28
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
29
use Surfnet\StepupSelfService\SelfServiceBundle\Service\VettingTypeService;
30
use Surfnet\StepupSelfService\SelfServiceBundle\Value\AvailableTokenCollection;
31
use Surfnet\StepupSelfService\SelfServiceBundle\Value\VettingType\VettingTypeInterface;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\Response;
34
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
35
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
36
37
class RegistrationController extends Controller
38
{
39
    /**
40
     * @Template
41
     */
42
    public function displaySecondFactorTypesAction()
43
    {
44
        $institution = $this->getIdentity()->institution;
45
        $institutionConfigurationOptions = $this->get('self_service.service.institution_configuration_options')
46
            ->getInstitutionConfigurationOptionsFor($institution);
47
48
        $identity = $this->getIdentity();
49
50
        /** @var SecondFactorService $service */
51
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
52
53
        // Get all available second factors from the config.
54
        $allSecondFactors = $this->getParameter('ss.enabled_second_factors');
55
56
        $secondFactors = $service->getSecondFactorsForIdentity(
57
            $identity,
58
            $allSecondFactors,
59
            $institutionConfigurationOptions->allowedSecondFactors,
60
            $institutionConfigurationOptions->numberOfTokensPerIdentity
61
        );
62
63
        if ($secondFactors->getRegistrationsLeft() <= 0) {
64
            $this->get('logger')->notice(
65
                'User tried to register a new token but maximum number of tokens is reached. Redirecting to overview'
66
            );
67
            return $this->forward('SurfnetStepupSelfServiceSelfServiceBundle:SecondFactor:list');
68
        }
69
70
71
        $availableGsspSecondFactors = [];
72
        foreach ($secondFactors->available as $index => $secondFactor) {
73
            if ($this->has("gssp.view_config.{$secondFactor}")) {
74
                /** @var ViewConfig $secondFactorConfig */
75
                $secondFactorConfig = $this->get("gssp.view_config.{$secondFactor}");
76
                $availableGsspSecondFactors[$index] = $secondFactorConfig;
77
                // Remove the gssp second factors from the regular second factors.
78
                unset($secondFactors->available[$index]);
79
            }
80
        }
81
82
        $availableTokens = AvailableTokenCollection::from($secondFactors->available, $availableGsspSecondFactors);
83
84
        return [
85
            'commonName' => $this->getIdentity()->commonName,
86
            'availableSecondFactors' => $availableTokens,
87
            'verifyEmail' => $this->emailVerificationIsRequired(),
88
        ];
89
    }
90
91
    /**
92
     * @Template
93
     * @param string $secondFactorId
94
     */
95
    public function displayVettingTypesAction(Request $request, $secondFactorId)
96
    {
97
        /**
98
         * @var VettingTypeService
99
         */
100
        $vettingTypeService = $this->get(VettingTypeService::class);
101
        $vettingTypeCollection = $vettingTypeService->vettingTypes($this->getIdentity(), $secondFactorId);
102
103
        $logger = $this->get('logger');
104
105
        $nudgeSelfAssertedTokens = $vettingTypeCollection->isPreferred(VettingTypeInterface::SELF_ASSERTED_TOKENS);
106
        $nudgeRaVetting = $vettingTypeCollection->isPreferred(VettingTypeInterface::ON_PREMISE);
107
108
        // Nudging section: helping the Identity into choosing the right vetting type:
109
110
        // Option 1: A self-asserted token registration nudge was requested via query string (?activate=self)
111
        if ($nudgeSelfAssertedTokens && $vettingTypeCollection->allowSelfAssertedTokens()) {
112
            $logger->notice('Nudging (forcing) self-asserted token registration');
113
            return $this->forward(
114
                'SurfnetStepupSelfServiceSelfServiceBundle:SelfAssertedTokens:selfAssertedTokenRegistration',
115
                ['secondFactorId' => $secondFactorId]
116
            );
117
        }
118
119
        // Option 2: A ra-vetting nudge was requested via query string (?activate=ra)
120
        if ($nudgeRaVetting) {
121
            $logger->notice('Nudging (forcing) RA vetting');
122
            return $this->forward(
123
                'SurfnetStepupSelfServiceSelfServiceBundle:Registration:sendRegistrationEmail',
124
                ['secondFactorId' => $secondFactorId]
125
            );
126
        }
127
128
        // Option 3: non-formal nudge, skip over selection screen. As only ra vetting is available.
129
        if (!$vettingTypeCollection->allowSelfVetting() && !$vettingTypeCollection->allowSelfAssertedTokens()) {
130
            $logger
131
                ->notice(
132
                    'Skipping ahead to the RA vetting option as self vetting or self-asserted tokens are not allowed'
133
                );
134
            return $this->forward(
135
                'SurfnetStepupSelfServiceSelfServiceBundle:Registration:sendRegistrationEmail',
136
                ['secondFactorId' => $secondFactorId]
137
            );
138
        }
139
140
        $institution = $this->getIdentity()->institution;
141
        $currentLocale = $request->getLocale();
142
        $vettingTypeHint = $vettingTypeService->vettingTypeHint($institution, $currentLocale);
143
144
        return [
145
            'allowSelfVetting' => $vettingTypeCollection->allowSelfVetting(),
146
            'allowSelfAssertedTokens' => $vettingTypeCollection->allowSelfAssertedTokens(),
147
            'hasVettingTypeHint' => !is_null($vettingTypeHint),
148
            'vettingTypeHint' => $vettingTypeHint,
149
            'verifyEmail' => $this->emailVerificationIsRequired(),
150
            'secondFactorId' => $secondFactorId,
151
        ];
152
    }
153
154
    /**
155
     * @Template
156
     */
157
    public function emailVerificationEmailSentAction()
158
    {
159
        return ['email' => $this->getIdentity()->email];
160
    }
161
162
    /**
163
     * @Template
164
     *
165
     * @param Request $request
166
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
167
     */
168
    public function verifyEmailAction(Request $request)
169
    {
170
        $nonce = $request->query->get('n', '');
171
        $identityId = $this->getIdentity()->id;
172
173
        /** @var SecondFactorService $service */
174
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
175
176
        $secondFactor = $service->findUnverifiedByVerificationNonce($identityId, $nonce);
177
178
        if ($secondFactor === null) {
179
            throw new NotFoundHttpException('No second factor can be verified using this URL.');
180
        }
181
182
        if ($service->verifyEmail($identityId, $nonce)) {
183
            return $this->redirectToRoute(
184
                'ss_second_factor_vetting_types',
185
                ['secondFactorId' => $secondFactor->id]
186
            );
187
        }
188
189
        return [];
190
    }
191
192
    /**
193
     * Intermediate action where the registration mail is sent. After which the
194
     * email-sent page is displayed. Preventing the mail message from being sent
195
     * over and over again when the user performs a page reload.
196
     */
197
    public function sendRegistrationEmailAction(string $secondFactorId)
198
    {
199
        // Send the registration email
200
        $this->get('self_service.service.ra')
201
            ->sendRegistrationMailMessage($this->getIdentity()->id, $secondFactorId);
202
        return $this->redirectToRoute(
203
            'ss_registration_registration_email_sent',
204
            ['secondFactorId' => $secondFactorId]
205
        );
206
    }
207
208
    /**
209
     * @param $secondFactorId
210
     * @return Response
211
     */
212
    public function registrationEmailSentAction($secondFactorId)
213
    {
214
        $parameters = $this->buildRegistrationActionParameters($secondFactorId);
215
        // Report that it was sent
216
        return $this->render(
217
            'SurfnetStepupSelfServiceSelfServiceBundle:registration:registration_email_sent.html.twig',
218
            $parameters
219
        );
220
    }
221
222
    /**
223
     * @param $secondFactorId
224
     * @return Response
225
     */
226
    public function registrationPdfAction($secondFactorId)
227
    {
228
        $parameters = $this->buildRegistrationActionParameters($secondFactorId);
229
230
        $response = $this->render(
231
            'SurfnetStepupSelfServiceSelfServiceBundle:registration:registration_email_sent_pdf.html.twig',
232
            $parameters
233
        );
234
        $content = $response->getContent();
235
236
237
        $mpdf = new Mpdf(
238
            array(
239
                'tempDir' => sys_get_temp_dir(),
240
            )
241
        );
242
        $mpdf->setLogger($this->get('logger'));
243
244
        $mpdf->WriteHTML($content);
245
        $output = $mpdf->Output('registration-code.pdf', MpdfDestination::STRING_RETURN);
246
247
        $response = new Response($output);
248
        $disposition = $response->headers->makeDisposition(
249
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
250
            'registration-code.pdf'
251
        );
252
253
        $response->headers->set('Content-Disposition', $disposition);
254
        $response->headers->set('Content-Description', 'File Transfer');
255
        $response->headers->set('Content-Transfer-Encoding', 'binary');
256
        $response->headers->set('Cache-Control', 'public, must-revalidate, max-age=0');
257
        $response->headers->set('Pragma', 'public');
258
        $response->headers->set('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');
259
        $response->headers->set('Last-Modified', '' . gmdate('D, d M Y H:i:s') . ' GMT');
260
        $response->headers->set('Content-Type', 'application/pdf');
261
262
        return $response;
263
    }
264
265
266
    private function buildRegistrationActionParameters($secondFactorId)
267
    {
268
        $identity = $this->getIdentity();
269
270
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\VerifiedSecondFactor $secondFactor */
271
        $secondFactor = $this->get('surfnet_stepup_self_service_self_service.service.second_factor')
272
            ->findOneVerified($secondFactorId);
273
274
        $parameters = [
275
            'email'            => $identity->email,
276
            'secondFactorId'   => $secondFactor->id,
277
            'registrationCode' => $secondFactor->registrationCode,
278
            'expirationDate'   => $secondFactor->registrationRequestedAt->add(
279
                new DateInterval('P14D')
280
            ),
281
            'locale'           => $identity->preferredLocale,
282
            'verifyEmail'      => $this->emailVerificationIsRequired(),
283
        ];
284
285
        /** @var RaService $raService */
286
        $raService         = $this->get('self_service.service.ra');
287
        /** @var RaLocationService $raLocationService */
288
        $raLocationService = $this->get('self_service.service.ra_location');
289
290
        $institutionConfigurationOptions = $this->get('self_service.service.institution_configuration_options')
291
            ->getInstitutionConfigurationOptionsFor($identity->institution);
292
293
        if ($institutionConfigurationOptions->useRaLocations) {
294
            $parameters['raLocations'] = $raLocationService->listRaLocationsFor($identity->institution);
295
        } elseif (!$institutionConfigurationOptions->showRaaContactInformation) {
296
            $parameters['ras'] = $raService->listRasWithoutRaas($identity->institution);
297
        } else {
298
            $parameters['ras'] = $raService->listRas($identity->institution);
299
        }
300
301
        return $parameters;
302
    }
303
}
304