Passed
Pull Request — master (#19)
by
unknown
08:04
created

ConsentController::noconsent()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 44
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 29
nc 10
nop 1
dl 0
loc 44
rs 8.2114
c 0
b 0
f 0
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
        $this->logger::info('Consent - getconsent: Accessing consent interface');
95
96
        $stateId = $request->query->get('StateId');
97
        if ($stateId === null) {
98
            throw new Error\BadRequest('Missing required StateId query parameter.');
99
        }
100
101
        $state = $this->authState::loadState($stateId, 'consent:request');
102
103
        if (is_null($state)) {
104
            throw new Error\NoState();
105
        } elseif (array_key_exists('core:SP', $state)) {
106
            $spentityid = $state['core:SP'];
107
        } elseif (array_key_exists('saml:sp:State', $state)) {
108
            $spentityid = $state['saml:sp:State']['core:SP'];
109
        } else {
110
            $spentityid = 'UNKNOWN';
111
        }
112
113
        // The user has pressed the yes-button
114
        if ($request->query->get('yes') !== null) {
115
            if ($request->query->get('saveconsent') !== null) {
116
                $this->logger::stats('consentResponse remember');
117
            } else {
118
                $this->logger::stats('consentResponse rememberNot');
119
            }
120
121
            $statsInfo = [
122
                'remember' => $request->query->get('saveconsent'),
123
            ];
124
            if (isset($state['Destination']['entityid'])) {
125
                $statsInfo['spEntityID'] = $state['Destination']['entityid'];
126
            }
127
            Stats::log('consent:accept', $statsInfo);
128
129
            if (
130
                array_key_exists('consent:store', $state)
131
                && $request->query->get('saveconsent') === '1'
132
            ) {
133
                // Save consent
134
                $store = $state['consent:store'];
135
                $userId = $state['consent:store.userId'];
136
                $targetedId = $state['consent:store.destination'];
137
                $attributeSet = $state['consent:store.attributeSet'];
138
139
                $this->logger::debug(
140
                    'Consent - saveConsent() : [' . $userId . '|' . $targetedId . '|' . $attributeSet . ']'
141
                );
142
                try {
143
                    $store->saveConsent($userId, $targetedId, $attributeSet);
144
                } catch (Exception $e) {
145
                    $this->logger::error('Consent: Error writing to storage: ' . $e->getMessage());
146
                }
147
            }
148
149
            return new RunnableResponse([Auth\ProcessingChain::class, 'resumeProcessing'], [$state]);
150
        }
151
152
        // Prepare attributes for presentation
153
        $attributes = $state['Attributes'];
154
        $noconsentattributes = $state['consent:noconsentattributes'];
155
156
        // Remove attributes that do not require consent
157
        foreach ($attributes as $attrkey => $attrval) {
158
            if (in_array($attrkey, $noconsentattributes, true)) {
159
                unset($attributes[$attrkey]);
160
            }
161
        }
162
        $para = [
163
            'attributes' => &$attributes
164
        ];
165
166
        // Reorder attributes according to attributepresentation hooks
167
        Module::callHooks('attributepresentation', $para);
168
169
        // Unset the values for attributes that need to be hidden
170
        if (array_key_exists('consent:hiddenAttributes', $state)) {
171
            foreach ($state['consent:hiddenAttributes'] as $hidden) {
172
                if (array_key_exists($hidden, $attributes)) {
173
                    $attributes[$hidden] = null;
174
                }
175
            }
176
        }
177
178
        // Make, populate and layout consent form
179
        $t = new Template($this->config, 'consent:consentform.twig');
180
        $l = $t->getLocalization();
181
        $l->addAttributeDomains();
182
        $translator = $t->getTranslator();
0 ignored issues
show
Unused Code introduced by
The assignment to $translator is dead and can be removed.
Loading history...
183
        $t->data['attributes'] = $attributes;
184
        $t->data['checked'] = $state['consent:checked'];
185
        $t->data['stateId'] = $stateId;
186
        $t->data['source'] = $state['Source'];
187
        $t->data['destination'] = $state['Destination'];
188
189
        if (isset($state['Destination']['descr_purpose'])) {
190
            $t->data['descr_purpose'] = $state['Destination']['descr_purpose'];
191
        } elseif (isset($state['Destination']['description'])) {
192
            $t->data['descr_purpose'] = $state['Destination']['description'];
193
        } elseif (isset($state['Destination']['UIInfo']['Description'])) {
194
            $t->data['descr_purpose'] = $state['Destination']['UIInfo']['Description'];
195
        }
196
197
        // Fetch privacy policy
198
        if (
199
            array_key_exists('UIInfo', $state['Destination']) &&
200
            array_key_exists('PrivacyStatementURL', $state['Destination']['UIInfo']) &&
201
            (!empty($state['Destination']['UIInfo']['PrivacyStatementURL']))
202
        ) {
203
            $privacypolicy = reset($state['Destination']['UIInfo']['PrivacyStatementURL']);
204
        } elseif (
205
            array_key_exists('UIInfo', $state['Source']) &&
206
            array_key_exists('PrivacyStatementURL', $state['Source']['UIInfo']) &&
207
            (!empty($state['Source']['UIInfo']['PrivacyStatementURL']))
208
        ) {
209
            $privacypolicy = reset($state['Source']['UIInfo']['PrivacyStatementURL']);
210
        } else {
211
            $privacypolicy = false;
212
        }
213
        if ($privacypolicy !== false) {
214
            $privacypolicy = str_replace(
215
                '%SPENTITYID%',
216
                urlencode($spentityid),
217
                $privacypolicy
218
            );
219
        }
220
        $t->data['sppp'] = $privacypolicy;
221
222
        // Set focus element
223
        switch ($state['consent:focus']) {
224
            case 'yes':
225
                $t->data['autofocus'] = 'yesbutton';
226
                break;
227
            case 'no':
228
                $t->data['autofocus'] = 'nobutton';
229
                break;
230
            case null:
231
            default:
232
                break;
233
        }
234
235
        $t->data['usestorage'] = array_key_exists('consent:store', $state);
236
237
        return $t;
238
    }
239
240
241
    /**
242
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
243
     *
244
     * @return \SimpleSAML\XHTML\Template
245
     */
246
    public function noconsent(Request $request): Template
247
    {
248
        $stateId = $request->query->get('StateId');
249
        if ($stateId === null) {
250
            throw new Error\BadRequest('Missing required StateId query parameter.');
251
        }
252
253
        $state = $this->authState::loadState($stateId, 'consent:request');
254
        if (is_null($state)) {
255
            throw new Error\NoState();
256
        }
257
258
        $resumeFrom = Module::getModuleURL(
259
            'consent/getconsent',
260
            ['StateId' => $stateId]
261
        );
262
263
        $logoutLink = Module::getModuleURL(
264
            'consent/logout',
265
            ['StateId' => $stateId]
266
        );
267
268
        $aboutService = null;
269
        if (!isset($state['consent:showNoConsentAboutService']) || $state['consent:showNoConsentAboutService']) {
270
            if (isset($state['Destination']['url.about'])) {
271
                $aboutService = $state['Destination']['url.about'];
272
            } elseif (isset($state['Destination']['UIInfo']['InformationURL'])) {
273
                $aboutService = reset($state['Destination']['UIInfo']['InformationURL']);
274
            }
275
        }
276
277
        $statsInfo = [];
278
        if (isset($state['Destination']['entityid'])) {
279
            $statsInfo['spEntityID'] = $state['Destination']['entityid'];
280
        }
281
        Stats::log('consent:reject', $statsInfo);
282
283
        $t = new Template($this->config, 'consent:noconsent.twig');
284
        $translator = $t->getTranslator();
0 ignored issues
show
Unused Code introduced by
The assignment to $translator is dead and can be removed.
Loading history...
285
        $t->data['dstMetadata'] = $state['Destination'];
286
        $t->data['resumeFrom'] = $resumeFrom;
287
        $t->data['aboutService'] = $aboutService;
288
        $t->data['logoutLink'] = $logoutLink;
289
        return $t;
290
    }
291
292
293
    /**
294
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
295
     *
296
     * @return \SimpleSAML\HTTP\RunnableResponse
297
     */
298
    public function logout(Request $request): RunnableResponse
299
    {
300
        $stateId = $request->query->get('StateId', null);
301
        if ($stateId === null) {
302
            throw new Error\BadRequest('Missing required StateId query parameter.');
303
        }
304
305
        $state = $this->authState::loadState($stateId, 'consent:request');
306
        if (is_null($state)) {
307
            throw new Error\NoState();
308
        }
309
        $state['Responder'] = ['\SimpleSAML\Module\consent\Logout', 'postLogout'];
310
311
        $idp = IdP::getByState($state);
312
        return new RunnableResponse([$idp, 'handleLogoutRequest'], [&$state, $stateId]);
313
    }
314
315
316
    /**
317
     * @return \SimpleSAML\XHTML\Template
318
     */
319
    public function logoutcompleted(): Template
320
    {
321
        return new Template($this->config, 'consent:logout_completed.twig');
322
    }
323
}
324