Completed
Push — feature/registration-code-prin... ( 7e9d48 )
by
unknown
12:50
created

RegistrationController   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 148
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 12
c 2
b 0
f 0
lcom 1
cbo 10
dl 0
loc 148
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A emailVerificationEmailSentAction() 0 4 1
A verifyEmailAction() 0 23 3
B displaySecondFactorTypesAction() 0 45 4
B registrationEmailSentAction() 0 38 3
A registrationPdfAction() 0 11 1
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\SelfServiceBundle\Service\SecondFactorService;
26
use Symfony\Component\HttpFoundation\Request;
27
use Symfony\Component\HttpFoundation\Response;
28
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
29
30
class RegistrationController extends Controller
31
{
32
    /**
33
     * @Template
34
     */
35
    public function displaySecondFactorTypesAction()
36
    {
37
        $institutionConfigurationOptions = $this->get('self_service.service.institution_configuration_options')
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $institutionConfigurationOptions 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...
38
            ->getInstitutionConfigurationOptionsFor($this->getIdentity()->institution);
39
40
        $identity = $this->getIdentity();
41
42
        /** @var SecondFactorService $service */
43
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
44
45
        // Get all available second factors from the config.
46
        $allSecondFactors = $this->getParameter('ss.enabled_second_factors');
47
48
        $secondFactors = $service->getSecondFactorsForIdentity(
49
            $identity,
50
            $allSecondFactors,
51
            $institutionConfigurationOptions->allowedSecondFactors,
52
            $this->getParameter('self_service.second_factor.max_tokens_per_identity')
53
        );
54
55
        if ($secondFactors->getRegistrationsLeft() <= 0) {
56
            $this->get('logger')->notice(
57
                'User tried to register a new token but maximum number of tokens is reached. Redirecting to overview'
58
            );
59
            return $this->forward('SurfnetStepupSelfServiceSelfServiceBundle:SecondFactor:list');
60
        }
61
62
63
        $availableGsspSecondFactors = [];
64
        foreach ($secondFactors->available as $index => $secondFactor) {
65
            if ($this->has("gssp.view_config.{$secondFactor}")) {
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $secondFactor instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
66
                /** @var ViewConfig $secondFactorConfig */
67
                $secondFactorConfig = $this->get("gssp.view_config.{$secondFactor}");
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $secondFactor instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
68
                $availableGsspSecondFactors[$index] = $secondFactorConfig;
69
                // Remove the gssp second factors from the regular second factors.
70
                unset($secondFactors->available[$index]);
71
            }
72
        }
73
        return [
74
            'commonName' => $this->getIdentity()->commonName,
75
            'availableSecondFactors' => $secondFactors->available,
76
            'availableGsspSecondFactors' => $availableGsspSecondFactors,
77
            'verifyEmail' => $this->emailVerificationIsRequired(),
78
        ];
79
    }
80
81
    /**
82
     * @Template
83
     */
84
    public function emailVerificationEmailSentAction()
85
    {
86
        return ['email' => $this->getIdentity()->email];
87
    }
88
89
    /**
90
     * @Template
91
     *
92
     * @param Request $request
93
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
94
     */
95
    public function verifyEmailAction(Request $request)
96
    {
97
        $nonce = $request->query->get('n', '');
98
        $identityId = $this->getIdentity()->id;
99
100
        /** @var SecondFactorService $service */
101
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
102
103
        $secondFactor = $service->findUnverifiedByVerificationNonce($identityId, $nonce);
104
105
        if ($secondFactor === null) {
106
            throw new NotFoundHttpException('No second factor can be verified using this URL.');
107
        }
108
109
        if ($service->verifyEmail($identityId, $nonce)) {
110
            return $this->redirectToRoute(
111
                'ss_registration_registration_email_sent',
112
                ['secondFactorId' => $secondFactor->id]
113
            );
114
        }
115
116
        return [];
117
    }
118
119
    /**
120
     * @param $secondFactorId
121
     * @return Response
122
     */
123
    public function registrationEmailSentAction($secondFactorId)
124
    {
125
        $identity = $this->getIdentity();
126
127
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\VerifiedSecondFactor $secondFactor */
128
        $secondFactor = $this->get('surfnet_stepup_self_service_self_service.service.second_factor')
129
            ->findOneVerified($secondFactorId);
130
131
        $parameters = [
132
            'email'            => $identity->email,
133
            'secondFactorId'   => $secondFactor->id,
134
            'registrationCode' => $secondFactor->registrationCode,
135
            'expirationDate'   => $secondFactor->registrationRequestedAt->add(
136
                new DateInterval('P14D')
137
            ),
138
            'locale'           => $identity->preferredLocale,
139
            'verifyEmail'      => $this->emailVerificationIsRequired(),
140
        ];
141
142
        $raService         = $this->get('self_service.service.ra');
143
        $raLocationService = $this->get('self_service.service.ra_location');
144
145
        $institutionConfigurationOptions = $this->get('self_service.service.institution_configuration_options')
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $institutionConfigurationOptions 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...
146
            ->getInstitutionConfigurationOptionsFor($identity->institution);
147
148
        if ($institutionConfigurationOptions->useRaLocations) {
149
            $parameters['raLocations'] = $raLocationService->listRaLocationsFor($identity->institution);
150
        } elseif (!$institutionConfigurationOptions->showRaaContactInformation) {
151
            $parameters['ras'] = $raService->listRasWithoutRaas($identity->institution);
152
        } else {
153
            $parameters['ras'] = $raService->listRas($identity->institution);
154
        }
155
156
        return $this->render(
157
            'SurfnetStepupSelfServiceSelfServiceBundle:Registration:registrationEmailSent.html.twig',
158
            $parameters
159
        );
160
    }
161
162
    /**
163
     * @param $secondFactorId
164
     * @return Response
0 ignored issues
show
Documentation introduced by
Should the return type not be Response|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
165
     */
166
    public function registrationPdfAction($secondFactorId)
167
    {
168
        $content = $this->registrationEmailSentAction($secondFactorId)
169
            ->getContent();
170
171
        $mpdf = new Mpdf();
172
        $mpdf->WriteHTML($content);
173
        $mpdf->Output('registration-code.pdf', MpdfDestination::DOWNLOAD);
174
175
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method registrationPdfAction() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
176
    }
177
}
178