Completed
Pull Request — release/2.10 (#175)
by Michiel
13:45 queued 12:15
created

RegistrationController::verifyEmailAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
cc 3
nc 3
nop 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 Surfnet\StepupSelfService\SelfServiceBundle\Value\AvailableTokenCollection;
27
use Symfony\Component\HttpFoundation\Request;
28
use Symfony\Component\HttpFoundation\Response;
29
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
30
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
31
32
class RegistrationController extends Controller
33
{
34
    /**
35
     * @Template
36
     */
37
    public function displaySecondFactorTypesAction()
38
    {
39
        $institutionConfigurationOptions = $this->get('self_service.service.institution_configuration_options')
40
            ->getInstitutionConfigurationOptionsFor($this->getIdentity()->institution);
41
42
        $identity = $this->getIdentity();
43
44
        /** @var SecondFactorService $service */
45
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
46
47
        // Get all available second factors from the config.
48
        $allSecondFactors = $this->getParameter('ss.enabled_second_factors');
49
50
        $secondFactors = $service->getSecondFactorsForIdentity(
51
            $identity,
52
            $allSecondFactors,
53
            $institutionConfigurationOptions->allowedSecondFactors,
54
            $institutionConfigurationOptions->numberOfTokensPerIdentity
55
        );
56
57
        if ($secondFactors->getRegistrationsLeft() <= 0) {
58
            $this->get('logger')->notice(
59
                'User tried to register a new token but maximum number of tokens is reached. Redirecting to overview'
60
            );
61
            return $this->forward('SurfnetStepupSelfServiceSelfServiceBundle:SecondFactor:list');
62
        }
63
64
65
        $availableGsspSecondFactors = [];
66
        foreach ($secondFactors->available as $index => $secondFactor) {
67
            if ($this->has("gssp.view_config.{$secondFactor}")) {
68
                /** @var ViewConfig $secondFactorConfig */
69
                $secondFactorConfig = $this->get("gssp.view_config.{$secondFactor}");
70
                $availableGsspSecondFactors[$index] = $secondFactorConfig;
71
                // Remove the gssp second factors from the regular second factors.
72
                unset($secondFactors->available[$index]);
73
            }
74
        }
75
76
        $availableTokens = AvailableTokenCollection::from($secondFactors->available, $availableGsspSecondFactors);
77
78
        return [
79
            'commonName' => $this->getIdentity()->commonName,
80
            'availableSecondFactors' => $availableTokens,
81
            'verifyEmail' => $this->emailVerificationIsRequired(),
82
        ];
83
    }
84
85
    /**
86
     * @Template
87
     */
88
    public function emailVerificationEmailSentAction()
89
    {
90
        return ['email' => $this->getIdentity()->email];
91
    }
92
93
    /**
94
     * @Template
95
     *
96
     * @param Request $request
97
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
98
     */
99
    public function verifyEmailAction(Request $request)
100
    {
101
        $nonce = $request->query->get('n', '');
102
        $identityId = $this->getIdentity()->id;
103
104
        /** @var SecondFactorService $service */
105
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
106
107
        $secondFactor = $service->findUnverifiedByVerificationNonce($identityId, $nonce);
108
109
        if ($secondFactor === null) {
110
            throw new NotFoundHttpException('No second factor can be verified using this URL.');
111
        }
112
113
        if ($service->verifyEmail($identityId, $nonce)) {
114
            return $this->redirectToRoute(
115
                'ss_registration_registration_email_sent',
116
                ['secondFactorId' => $secondFactor->id]
117
            );
118
        }
119
120
        return [];
121
    }
122
123
    /**
124
     * @param $secondFactorId
125
     * @return Response
126
     */
127
    public function registrationEmailSentAction($secondFactorId)
128
    {
129
        $parameters = $this->buildRegistrationActionParameters($secondFactorId);
130
131
        return $this->render(
132
            'SurfnetStepupSelfServiceSelfServiceBundle:Registration:registrationEmailSent.html.twig',
133
            $parameters
134
        );
135
    }
136
137
    /**
138
     * @param $secondFactorId
139
     * @return Response
140
     */
141
    public function registrationPdfAction($secondFactorId)
142
    {
143
        $parameters = $this->buildRegistrationActionParameters($secondFactorId);
144
145
        $response = $this->render(
146
            'SurfnetStepupSelfServiceSelfServiceBundle:Registration:registrationEmailSentPdf.html.twig',
147
            $parameters
148
        );
149
        $content = $response->getContent();
150
151
152
        $mpdf = new Mpdf(
153
            array(
154
                'tempDir' => sys_get_temp_dir(),
155
            )
156
        );
157
        $mpdf->setLogger($this->get('logger'));
158
159
        $mpdf->WriteHTML($content);
160
        $output = $mpdf->Output('registration-code.pdf', MpdfDestination::STRING_RETURN);
161
162
        $response = new Response($output);
163
        $disposition = $response->headers->makeDisposition(
164
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
165
            'registration-code.pdf'
166
        );
167
168
        $response->headers->set('Content-Disposition', $disposition);
169
        $response->headers->set('Content-Description', 'File Transfer');
170
        $response->headers->set('Content-Transfer-Encoding', 'binary');
171
        $response->headers->set('Cache-Control', 'public, must-revalidate, max-age=0');
172
        $response->headers->set('Pragma', 'public');
173
        $response->headers->set('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');
174
        $response->headers->set('Last-Modified', '' . gmdate('D, d M Y H:i:s') . ' GMT');
175
        $response->headers->set('Content-Type', 'application/pdf');
176
177
        return $response;
178
    }
179
180
181
    private function buildRegistrationActionParameters($secondFactorId)
182
    {
183
        $identity = $this->getIdentity();
184
185
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\VerifiedSecondFactor $secondFactor */
186
        $secondFactor = $this->get('surfnet_stepup_self_service_self_service.service.second_factor')
187
            ->findOneVerified($secondFactorId);
188
189
        $parameters = [
190
            'email'            => $identity->email,
191
            'secondFactorId'   => $secondFactor->id,
192
            'registrationCode' => $secondFactor->registrationCode,
193
            'expirationDate'   => $secondFactor->registrationRequestedAt->add(
194
                new DateInterval('P14D')
195
            ),
196
            'locale'           => $identity->preferredLocale,
197
            'verifyEmail'      => $this->emailVerificationIsRequired(),
198
        ];
199
200
        $raService         = $this->get('self_service.service.ra');
201
        $raLocationService = $this->get('self_service.service.ra_location');
202
203
        $institutionConfigurationOptions = $this->get('self_service.service.institution_configuration_options')
204
            ->getInstitutionConfigurationOptionsFor($identity->institution);
205
206
        if ($institutionConfigurationOptions->useRaLocations) {
207
            $parameters['raLocations'] = $raLocationService->listRaLocationsFor($identity->institution);
208
        } elseif (!$institutionConfigurationOptions->showRaaContactInformation) {
209
            $parameters['ras'] = $raService->listRasWithoutRaas($identity->institution);
210
        } else {
211
            $parameters['ras'] = $raService->listRas($identity->institution);
212
        }
213
214
        return $parameters;
215
    }
216
}
217