Passed
Pull Request — master (#14)
by Tim
02:28
created

ConsentController::logout()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 3
b 0
f 0
nc 3
nop 1
dl 0
loc 15
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\consent\Controller;
6
7
use Exception;
8
use SimpleSAML\Auth;
9
use SimpleSAML\Configuration;
10
use SimpleSAML\Error;
11
use SimpleSAML\HTTP\RunnableResponse;
12
use SimpleSAML\IdP;
13
use SimpleSAML\Locale\Translate;
14
use SimpleSAML\Logger;
15
use SimpleSAML\Module;
16
use SimpleSAML\Session;
17
use SimpleSAML\Stats;
18
use SimpleSAML\Utils;
19
use SimpleSAML\XHTML\Template;
20
use Symfony\Component\HttpFoundation\Request;
21
22
/**
23
 * Controller class for the consent module.
24
 *
25
 * This class serves the consent views available in the module.
26
 *
27
 * @package SimpleSAML\Module\consent
28
 */
29
class ConsentController
30
{
31
    /** @var \SimpleSAML\Configuration */
32
    protected $config;
33
34
    /** @var \SimpleSAML\Session */
35
    protected $session;
36
37
    /**
38
     * @var \SimpleSAML\Auth\State|string
39
     * @psalm-var \SimpleSAML\Auth\State|class-string
40
     */
41
    protected $authState = Auth\State::class;
42
43
    /**
44
     * @var \SimpleSAML\Logger|string
45
     * @psalm-var \SimpleSAML\Logger|class-string
46
     */
47
    protected $logger = Logger::class;
48
49
50
    /**
51
     * ConsentController constructor.
52
     *
53
     * @param \SimpleSAML\Configuration $config The configuration to use.
54
     * @param \SimpleSAML\Session $session The current user session.
55
     */
56
    public function __construct(Configuration $config, Session $session)
57
    {
58
        $this->config = $config;
59
        $this->session = $session;
60
    }
61
62
63
    /**
64
     * Inject the \SimpleSAML\Auth\State dependency.
65
     *
66
     * @param \SimpleSAML\Auth\State $authState
67
     */
68
    public function setAuthState(Auth\State $authState): void
69
    {
70
        $this->authState = $authState;
71
    }
72
73
74
    /**
75
     * Inject the \SimpleSAML\Logger dependency.
76
     *
77
     * @param \SimpleSAML\Logger $logger
78
     */
79
    public function setLogger(Logger $logger): void
80
    {
81
        $this->logger = $logger;
82
    }
83
84
85
    /**
86
     * Display consent form.
87
     *
88
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
89
     *
90
     * @return \SimpleSAML\XHTML\Template|\SimpleSAML\HTTP\RunnableResponse
91
     */
92
    public function getconsent(Request $request)
93
    {
94
//        session_cache_limiter('nocache');
95
96
        $this->logger::info('Consent - getconsent: Accessing consent interface');
97
98
        $stateId = $request->query->get('StateId');
99
        if ($stateId === null) {
100
            throw new Error\BadRequest('Missing required StateId query parameter.');
101
        }
102
103
        $state = $this->authState::loadState($stateId, 'consent:request');
104
105
        if (is_null($state)) {
106
            throw new Error\NoState();
107
        } elseif (array_key_exists('core:SP', $state)) {
108
            $spentityid = $state['core:SP'];
109
        } elseif (array_key_exists('saml:sp:State', $state)) {
110
            $spentityid = $state['saml:sp:State']['core:SP'];
111
        } else {
112
            $spentityid = 'UNKNOWN';
113
        }
114
115
        // The user has pressed the yes-button
116
        if ($request->query->get('yes') !== null) {
117
            if ($request->query->get('saveconsent') !== null) {
118
                $this->logger::stats('consentResponse remember');
119
            } else {
120
                $this->logger::stats('consentResponse rememberNot');
121
            }
122
123
            $statsInfo = [
124
                'remember' => $request->query->get('saveconsent'),
125
            ];
126
            if (isset($state['Destination']['entityid'])) {
127
                $statsInfo['spEntityID'] = $state['Destination']['entityid'];
128
            }
129
            Stats::log('consent:accept', $statsInfo);
130
131
            if (
132
                array_key_exists('consent:store', $state)
133
                && $request->query->get('saveconsent') === '1'
134
            ) {
135
                // Save consent
136
                $store = $state['consent:store'];
137
                $userId = $state['consent:store.userId'];
138
                $targetedId = $state['consent:store.destination'];
139
                $attributeSet = $state['consent:store.attributeSet'];
140
141
                $this->logger::debug(
142
                    'Consent - saveConsent() : [' . $userId . '|' . $targetedId . '|' . $attributeSet . ']'
143
                );
144
                try {
145
                    $store->saveConsent($userId, $targetedId, $attributeSet);
146
                } catch (Exception $e) {
147
                    $this->logger::error('Consent: Error writing to storage: ' . $e->getMessage());
148
                }
149
            }
150
151
            return new RunnableResponse([Auth\ProcessingChain::class, 'resumeProcessing'], [$state]);
152
        }
153
154
        // Prepare attributes for presentation
155
        $attributes = $state['Attributes'];
156
        $noconsentattributes = $state['consent:noconsentattributes'];
157
158
        // Remove attributes that do not require consent
159
        foreach ($attributes as $attrkey => $attrval) {
160
            if (in_array($attrkey, $noconsentattributes, true)) {
161
                unset($attributes[$attrkey]);
162
            }
163
        }
164
        $para = [
165
            'attributes' => &$attributes
166
        ];
167
168
        // Reorder attributes according to attributepresentation hooks
169
        Module::callHooks('attributepresentation', $para);
170
171
        // Parse parameters
172
        if (array_key_exists('name', $state['Source'])) {
173
            $srcName = $state['Source']['name'];
174
        } elseif (array_key_exists('OrganizationDisplayName', $state['Source'])) {
175
            $srcName = $state['Source']['OrganizationDisplayName'];
176
        } else {
177
            $srcName = $state['Source']['entityid'];
178
        }
179
180
        if (array_key_exists('name', $state['Destination'])) {
181
            $dstName = $state['Destination']['name'];
182
        } elseif (array_key_exists('OrganizationDisplayName', $state['Destination'])) {
183
            $dstName = $state['Destination']['OrganizationDisplayName'];
184
        } else {
185
            $dstName = $state['Destination']['entityid'];
186
        }
187
188
        // Make, populate and layout consent form
189
        $t = new Template($this->config, 'consent:consentform.twig');
190
        $translator = $t->getTranslator();
191
        $t->data['srcMetadata'] = $state['Source'];
192
        $t->data['dstMetadata'] = $state['Destination'];
193
        $t->data['yesTarget'] = Module::getModuleURL('consent/getconsent');
194
        $t->data['yesData'] = ['StateId' => $stateId];
195
        $t->data['noTarget'] = Module::getModuleURL('consent/noconsent');
196
        $t->data['noData'] = ['StateId' => $stateId];
197
        $t->data['attributes'] = $attributes;
198
        $t->data['checked'] = $state['consent:checked'];
199
        $t->data['stateId'] = $stateId;
200
201
        $t->data['srcName'] = htmlspecialchars(
202
            is_array($srcName) ? $translator->getPreferredTranslation($srcName) : $srcName
203
        );
204
        $t->data['dstName'] = htmlspecialchars(
205
            is_array($dstName) ? $translator->getPreferredTranslation($dstName) : $dstName
206
        );
207
208
        if (array_key_exists('descr_purpose', $state['Destination'])) {
209
            $t->data['dstDesc'] = $translator->getPreferredTranslation(
210
                Utils\Arrays::arrayize(
211
                    $state['Destination']['descr_purpose'],
212
                    'en'
213
                )
214
            );
215
        }
216
217
        // Fetch privacypolicy
218
        if (
219
            array_key_exists('UIInfo', $state['Destination']) &&
220
            array_key_exists('PrivacyStatementURL', $state['Destination']['UIInfo']) &&
221
            (!empty($state['Destination']['UIInfo']['PrivacyStatementURL']))
222
        ) {
223
            $privacypolicy = reset($state['Destination']['UIInfo']['PrivacyStatementURL']);
224
        } elseif (
225
            array_key_exists('UIInfo', $state['Source']) &&
226
            array_key_exists('PrivacyStatementURL', $state['Source']['UIInfo']) &&
227
            (!empty($state['Source']['UIInfo']['PrivacyStatementURL']))
228
        ) {
229
            $privacypolicy = reset($state['Source']['UIInfo']['PrivacyStatementURL']);
230
        } else {
231
            $privacypolicy = false;
232
        }
233
        if ($privacypolicy !== false) {
234
            $privacypolicy = str_replace(
235
                '%SPENTITYID%',
236
                urlencode($spentityid),
237
                $privacypolicy
238
            );
239
        }
240
        $t->data['sppp'] = $privacypolicy;
241
242
        // Set focus element
243
        switch ($state['consent:focus']) {
244
            case 'yes':
245
                $t->data['autofocus'] = 'yesbutton';
246
                break;
247
            case 'no':
248
                $t->data['autofocus'] = 'nobutton';
249
                break;
250
            case null:
251
            default:
252
                break;
253
        }
254
255
        $t->data['usestorage'] = array_key_exists('consent:store', $state);
256
257
        if (array_key_exists('consent:hiddenAttributes', $state)) {
258
            $t->data['hiddenAttributes'] = $state['consent:hiddenAttributes'];
259
        } else {
260
            $t->data['hiddenAttributes'] = [];
261
        }
262
263
        return $t;
264
    }
265
266
267
    /**
268
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
269
     *
270
     * @return \SimpleSAML\XHTML\Template
271
     */
272
    public function noconsent(Request $request): Template
273
    {
274
        $stateId = $request->query->get('StateId');
275
        if ($stateId === null) {
276
            throw new Error\BadRequest('Missing required StateId query parameter.');
277
        }
278
279
        $state = $this->authState::loadState($stateId, 'consent:request');
280
        if (is_null($state)) {
281
            throw new Error\NoState();
282
        }
283
284
        $resumeFrom = Module::getModuleURL(
285
            'consent/getconsent',
286
            ['StateId' => $stateId]
287
        );
288
289
        $logoutLink = Module::getModuleURL(
290
            'consent/logout',
291
            ['StateId' => $stateId]
292
        );
293
294
        $aboutService = null;
295
        if (!isset($state['consent:showNoConsentAboutService']) || $state['consent:showNoConsentAboutService']) {
296
            if (isset($state['Destination']['url.about'])) {
297
                $aboutService = $state['Destination']['url.about'];
298
            }
299
        }
300
301
        $statsInfo = [];
302
        if (isset($state['Destination']['entityid'])) {
303
            $statsInfo['spEntityID'] = $state['Destination']['entityid'];
304
        }
305
        Stats::log('consent:reject', $statsInfo);
306
307
        if (array_key_exists('name', $state['Destination'])) {
308
            $dstName = $state['Destination']['name'];
309
        } elseif (array_key_exists('OrganizationDisplayName', $state['Destination'])) {
310
            $dstName = $state['Destination']['OrganizationDisplayName'];
311
        } else {
312
            $dstName = $state['Destination']['entityid'];
313
        }
314
315
        $t = new Template($this->config, 'consent:noconsent.twig');
316
        $translator = $t->getTranslator();
317
        $t->data['dstMetadata'] = $state['Destination'];
318
        $t->data['resumeFrom'] = $resumeFrom;
319
        $t->data['aboutService'] = $aboutService;
320
        $t->data['logoutLink'] = $logoutLink;
321
        $t->data['dstName'] = htmlspecialchars(
322
            is_array($dstName) ? $translator->getPreferredTranslation($dstName) : $dstName
323
        );
324
        return $t;
325
    }
326
327
328
    /**
329
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
330
     *
331
     * @return \SimpleSAML\HTTP\RunnableResponse
332
     */
333
    public function logout(Request $request): RunnableResponse
334
    {
335
        $stateId = $request->query->get('StateId', null);
336
        if ($stateId === null) {
337
            throw new Error\BadRequest('Missing required StateId query parameter.');
338
        }
339
340
        $state = $this->authState::loadState($stateId, 'consent:request');
341
        if (is_null($state)) {
342
            throw new Error\NoState();
343
        }
344
        $state['Responder'] = ['\SimpleSAML\Module\consent\Logout', 'postLogout'];
345
346
        $idp = IdP::getByState($state);
347
        return new RunnableResponse([$idp, 'handleLogoutRequest'], [&$state, $stateId]);
348
    }
349
350
351
    /**
352
     * @return \SimpleSAML\XHTML\Template
353
     */
354
    public function logoutcompleted(): Template
355
    {
356
        return new Template($this->config, 'consent:logout_completed.twig');
357
    }
358
}
359