Passed
Pull Request — main (#308)
by Paul
13:38 queued 06:44
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
declare(strict_types = 1);
4
5
/**
6
 * Copyright 2014 SURFnet bv
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;
22
23
use DateInterval;
24
use Mpdf\Mpdf;
25
use Mpdf\Output\Destination as MpdfDestination;
26
use Psr\Log\LoggerInterface;
27
use Surfnet\StepupMiddlewareClientBundle\Identity\Dto\VerifiedSecondFactor;
28
use Surfnet\StepupSelfService\SelfServiceBundle\Service\ControllerCheckerService;
29
use Surfnet\StepupSelfService\SelfServiceBundle\Service\InstitutionConfigurationOptionsService;
30
use Surfnet\StepupSelfService\SelfServiceBundle\Service\RaLocationService;
31
use Surfnet\StepupSelfService\SelfServiceBundle\Service\RaService;
32
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorAvailabilityHelper;
33
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
34
use Surfnet\StepupSelfService\SelfServiceBundle\Service\VettingTypeService;
35
use Surfnet\StepupSelfService\SelfServiceBundle\Value\VettingType\VettingTypeInterface;
36
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
37
use Symfony\Component\HttpFoundation\RedirectResponse;
38
use Symfony\Component\HttpFoundation\Request;
39
use Symfony\Component\HttpFoundation\Response;
40
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
41
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
42
use Symfony\Component\Routing\Attribute\Route;
43
44
/**
45
 * TODO: split into smaller controllers
46
 * TODO: create PDF generation in dedicated service
47
 */
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...
48
class RegistrationController extends AbstractController
49
{
50
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
51
        private readonly VettingTypeService $vettingTypeService,
52
        private readonly InstitutionConfigurationOptionsService $configurationOptionsService,
53
        private readonly SecondFactorService $secondFactorService,
54
        private readonly LoggerInterface $logger,
55
        private readonly SecondFactorAvailabilityHelper $secondFactorAvailabilityHelper,
56
        private readonly RaService $raService,
57
        private readonly RaLocationService $raLocationService,
58
        private readonly ControllerCheckerService $checkerService,
59
    ) {
60
    }
61
62
    #[Route(
63
        path: '/registration/select-token',
64
        name: 'ss_registration_display_types',
65
        methods: ['GET'],
66
    )]
67
    public function displaySecondFactorTypes(): Response
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function displaySecondFactorTypes()
Loading history...
68
    {
69
        $institution = $this->getUser()->getIdentity()->institution;
70
        $institutionConfigurationOptions = $this->configurationOptionsService
71
            ->getInstitutionConfigurationOptionsFor($institution);
72
73
        $identity = $this->getUser()->getIdentity();
74
75
        // Get all available second factors from the config.
76
        $allSecondFactors = $this->getParameter('ss.enabled_second_factors');
77
78
        $secondFactors = $this->secondFactorService->getSecondFactorsForIdentity(
79
            $identity,
80
            $allSecondFactors,
81
            $institutionConfigurationOptions->allowedSecondFactors,
82
            $institutionConfigurationOptions->numberOfTokensPerIdentity
83
        );
84
85
        if ($secondFactors->getRegistrationsLeft() <= 0) {
86
            $this->logger->notice(
87
                'User tried to register a new token but maximum number of tokens is reached. Redirecting to overview'
88
            );
89
            return $this->forward('SurfnetStepupSelfServiceSelfServiceBundle:SecondFactor:list');
90
        }
91
92
        $availableTokens = $this->secondFactorAvailabilityHelper->filter($secondFactors);
93
94
        return $this->render(
95
            'registration/display_second_factor_types.html.twig',
96
            [
97
                'commonName' => $this->getUser()->getIdentity()->commonName,
98
                'availableSecondFactors' => $availableTokens,
99
                'verifyEmail' => $this->checkerService->emailVerificationIsRequired(),
100
            ]
101
        );
102
    }
103
104
    #[Route(
105
        path: '/second-factor/{secondFactorId}/vetting-types',
106
        name: 'ss_second_factor_vetting_types',
107
        methods:  ['GET'],
108
    )]
109
    public function displayVettingTypes(Request $request, string $secondFactorId): Response
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function displayVettingTypes()
Loading history...
110
    {
111
        /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
112
         * @var VettingTypeService
113
         */
114
        $vettingTypeService = $this->vettingTypeService;
115
        $vettingTypeCollection = $vettingTypeService->vettingTypes($this->getUser()->getIdentity(), $secondFactorId);
116
117
        $nudgeSelfAssertedTokens = $vettingTypeCollection->isPreferred(VettingTypeInterface::SELF_ASSERTED_TOKENS);
118
        $nudgeRaVetting = $vettingTypeCollection->isPreferred(VettingTypeInterface::ON_PREMISE);
119
120
        // Nudging section: helping the Identity into choosing the right vetting type:
121
122
        // Option 1: A self-asserted token registration nudge was requested via query string (?activate=self)
123
        if ($nudgeSelfAssertedTokens && $vettingTypeCollection->allowSelfAssertedTokens()) {
124
            $this->logger->notice('Nudging (forcing) self-asserted token registration');
125
            return $this->forward(
126
                'SurfnetStepupSelfServiceSelfServiceBundle:SelfAssertedTokens:selfAssertedTokenRegistration',
127
                ['secondFactorId' => $secondFactorId]
128
            );
129
        }
130
131
        // Option 2: A ra-vetting nudge was requested via query string (?activate=ra)
132
        if ($nudgeRaVetting) {
133
            $this->logger->notice('Nudging (forcing) RA vetting');
134
            return $this->forward(
135
                'SurfnetStepupSelfServiceSelfServiceBundle:Registration:sendRegistrationEmail',
136
                ['secondFactorId' => $secondFactorId]
137
            );
138
        }
139
140
        // Option 3: non-formal nudge, skip over selection screen. As only ra vetting is available.
141
        if (!$vettingTypeCollection->allowSelfVetting() && !$vettingTypeCollection->allowSelfAssertedTokens()) {
142
            $this->logger
143
                ->notice(
144
                    'Skipping ahead to the RA vetting option as self vetting or self-asserted tokens are not allowed'
145
                );
146
            return $this->forward(
147
                'SurfnetStepupSelfServiceSelfServiceBundle:Registration:sendRegistrationEmail',
148
                ['secondFactorId' => $secondFactorId]
149
            );
150
        }
151
152
        $institution = $this->getUser()->getIdentity()->institution;
153
        $currentLocale = $request->getLocale();
154
        $vettingTypeHint = $vettingTypeService->vettingTypeHint($institution, $currentLocale);
155
156
        return $this->render(
157
            'registration/display_vetting_types.html.twig',
158
            [
159
                'allowSelfVetting' => $vettingTypeCollection->allowSelfVetting(),
160
                'allowSelfAssertedTokens' => $vettingTypeCollection->allowSelfAssertedTokens(),
161
                'hasVettingTypeHint' => !is_null($vettingTypeHint),
162
                'vettingTypeHint' => $vettingTypeHint,
163
                'verifyEmail' => $this->checkerService->emailVerificationIsRequired(),
164
                'secondFactorId' => $secondFactorId,
165
            ]
166
        );
167
    }
168
169
170
    #[Route(
171
        path: '/registration/{secondFactorId}/email-verification-email-sent',
172
        name: 'ss_registration_email_verification_email_sent',
173
        methods: ['GET'],
174
    )]
175
    public function emailVerificationEmailSent(): Response
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function emailVerificationEmailSent()
Loading history...
176
    {
177
        return $this->render(
178
            view: 'registration/email_verification_email_sent.html.twig',
179
            parameters: ['email' => $this->getUser()->getIdentity()->email]);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 8 spaces, but found 12.
Loading history...
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
180
    }
181
182
    #[Route(
183
        path: '/verify-email',
184
        name: 'ss_registration_verify_email',
185
        methods: ['GET'],
186
    )]
187
    public function verifyEmail(Request $request): Response
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function verifyEmail()
Loading history...
188
    {
189
        $nonce = $request->query->get('n', '');
190
        $identityId = $this->getUser()->getIdentity()->id;
191
        $secondFactor = $this->secondFactorService->findUnverifiedByVerificationNonce($identityId, $nonce);
192
193
        if ($secondFactor === null) {
194
            throw new NotFoundHttpException('No second factor can be verified using this URL.');
195
        }
196
197
        if ($this->secondFactorService->verifyEmail($identityId, $nonce)) {
198
            return $this->redirectToRoute(
199
                'ss_second_factor_vetting_types',
200
                ['secondFactorId' => $secondFactor->id]
201
            );
202
        }
203
204
        return $this->render('registration/verify_email.html.twig');
205
    }
206
207
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $secondFactorId should have a doc-comment as per coding-style.
Loading history...
208
     * Intermediate action where the registration mail is sent. After which the
209
     * email-sent page is displayed. Preventing the mail message from being sent
210
     * over and over again when the user performs a page reload.
211
     */
0 ignored issues
show
Coding Style introduced by
There must be no blank lines after the function comment
Loading history...
Coding Style introduced by
Missing @return tag in function comment
Loading history...
212
    #[Route(
213
        path: '/registration/{secondFactorId}/send-registration-email',
214
        name: 'ss_registration_send_registration_email',
215
        methods: ['GET'],
216
    )]
217
218
    public function sendRegistrationEmail(string $secondFactorId): RedirectResponse
219
    {
220
        // Send the registration email
221
        $this->raService
222
            ->sendRegistrationMailMessage($this->getUser()->getIdentity()->id, $secondFactorId);
223
        return $this->redirectToRoute(
224
            'ss_registration_registration_email_sent',
225
            ['secondFactorId' => $secondFactorId]
226
        );
227
    }
228
229
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
230
     * @param $secondFactorId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
231
     * @return Response
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
232
     */
233
    #[Route(
234
        path: '/registration/{secondFactorId}/registration-email-sent',
235
        name: 'ss_registration_registration_email_sent',
236
        methods: ['GET'],
237
    )]
238
    public function registrationEmailSent($secondFactorId): Response
239
    {
240
        $parameters = $this->buildRegistrationActionParameters($secondFactorId);
241
        // Report that it was sent
242
        return $this->render(
243
            'registration/registration_email_sent.html.twig',
244
            $parameters
245
        );
246
    }
247
248
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
249
     * @param $secondFactorId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
250
     * @return Response
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
251
     */
252
    #[Route(
253
        path: '/registration/{secondFactorId}/registration-pdf',
254
        name: 'ss_registration_registration_pdf',
255
        methods: ['GET'],
256
    )]
257
    public function registrationPdf($secondFactorId): Response
258
    {
259
        $parameters = $this->buildRegistrationActionParameters($secondFactorId);
260
261
        $response = $this->render(
262
            'registration/registration_email_sent_pdf.html.twig',
263
            $parameters
264
        );
265
        $content = $response->getContent();
266
267
        $mpdf = new Mpdf(
268
            ['tempDir' => sys_get_temp_dir()]
269
        );
270
        $mpdf->setLogger($this->logger);
271
272
        $mpdf->WriteHTML($content);
273
        $output = $mpdf->Output('registration-code.pdf', MpdfDestination::STRING_RETURN);
274
275
        $response = new Response($output);
276
        $disposition = $response->headers->makeDisposition(
277
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
278
            'registration-code.pdf'
279
        );
280
281
        $response->headers->set('Content-Disposition', $disposition);
282
        $response->headers->set('Content-Description', 'File Transfer');
283
        $response->headers->set('Content-Transfer-Encoding', 'binary');
284
        $response->headers->set('Cache-Control', 'public, must-revalidate, max-age=0');
285
        $response->headers->set('Pragma', 'public');
286
        $response->headers->set('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');
287
        $response->headers->set('Last-Modified', '' . gmdate('D, d M Y H:i:s') . ' GMT');
288
        $response->headers->set('Content-Type', 'application/pdf');
289
290
        return $response;
291
    }
292
293
    private function buildRegistrationActionParameters($secondFactorId): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function buildRegistrationActionParameters()
Loading history...
Coding Style introduced by
Private method name "RegistrationController::buildRegistrationActionParameters" must be prefixed with an underscore
Loading history...
294
    {
295
        $identity = $this->getUser()->getIdentity();
296
297
        /** @var VerifiedSecondFactor $secondFactor */
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...
298
        $secondFactor = $this->secondFactorService->findOneVerified($secondFactorId);
299
300
        $parameters = [
301
            'email'            => $identity->email,
302
            'secondFactorId'   => $secondFactor->id,
303
            'registrationCode' => $secondFactor->registrationCode,
304
            'expirationDate'   => $secondFactor->registrationRequestedAt->add(
305
                new DateInterval('P14D')
306
            ),
307
            'locale'           => $identity->preferredLocale,
308
            'verifyEmail'      => $this->checkerService->emailVerificationIsRequired(),
309
        ];
310
311
        $institutionConfigurationOptions = $this->configurationOptionsService
312
            ->getInstitutionConfigurationOptionsFor($identity->institution);
313
314
        if ($institutionConfigurationOptions->useRaLocations) {
315
            $parameters['raLocations'] = $this->raLocationService->listRaLocationsFor($identity->institution);
316
        } elseif (!$institutionConfigurationOptions->showRaaContactInformation) {
317
            $parameters['ras'] = $this->raService->listRasWithoutRaas($identity->institution);
318
        } else {
319
            $parameters['ras'] = $this->raService->listRas($identity->institution);
320
        }
321
322
        return $parameters;
323
    }
324
}
325