Completed
Pull Request — develop (#227)
by Michiel
04:22 queued 02:14
created

displayVettingTypesAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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