Passed
Pull Request — master (#19)
by
unknown
02:06
created

ConsentController::setLogger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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']['description'])) {
190
            $t->data['descr_purpose'] = $state['Destination']['description'];
191
        } elseif (isset($state['Destination']['UIInfo']['Description'])) {
192
            $t->data['descr_purpose'] = $state['Destination']['UIInfo']['Description'];
193
        }
194
195
        // Fetch privacy policy
196
        if (
197
            array_key_exists('UIInfo', $state['Destination']) &&
198
            array_key_exists('PrivacyStatementURL', $state['Destination']['UIInfo']) &&
199
            (!empty($state['Destination']['UIInfo']['PrivacyStatementURL']))
200
        ) {
201
            $privacypolicy = reset($state['Destination']['UIInfo']['PrivacyStatementURL']);
202
        } elseif (
203
            array_key_exists('UIInfo', $state['Source']) &&
204
            array_key_exists('PrivacyStatementURL', $state['Source']['UIInfo']) &&
205
            (!empty($state['Source']['UIInfo']['PrivacyStatementURL']))
206
        ) {
207
            $privacypolicy = reset($state['Source']['UIInfo']['PrivacyStatementURL']);
208
        } else {
209
            $privacypolicy = false;
210
        }
211
        if ($privacypolicy !== false) {
212
            $privacypolicy = str_replace(
213
                '%SPENTITYID%',
214
                urlencode($spentityid),
215
                $privacypolicy
216
            );
217
        }
218
        $t->data['sppp'] = $privacypolicy;
219
220
        // Set focus element
221
        switch ($state['consent:focus']) {
222
            case 'yes':
223
                $t->data['autofocus'] = 'yesbutton';
224
                break;
225
            case 'no':
226
                $t->data['autofocus'] = 'nobutton';
227
                break;
228
            case null:
229
            default:
230
                break;
231
        }
232
233
        $t->data['usestorage'] = array_key_exists('consent:store', $state);
234
235
        return $t;
236
    }
237
238
239
    /**
240
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
241
     *
242
     * @return \SimpleSAML\XHTML\Template
243
     */
244
    public function noconsent(Request $request): Template
245
    {
246
        $stateId = $request->query->get('StateId');
247
        if ($stateId === null) {
248
            throw new Error\BadRequest('Missing required StateId query parameter.');
249
        }
250
251
        $state = $this->authState::loadState($stateId, 'consent:request');
252
        if (is_null($state)) {
253
            throw new Error\NoState();
254
        }
255
256
        $resumeFrom = Module::getModuleURL(
257
            'consent/getconsent',
258
            ['StateId' => $stateId]
259
        );
260
261
        $logoutLink = Module::getModuleURL(
262
            'consent/logout',
263
            ['StateId' => $stateId]
264
        );
265
266
        $aboutService = null;
267
        if (!isset($state['consent:showNoConsentAboutService']) || $state['consent:showNoConsentAboutService']) {
268
            if (isset($state['Destination']['UIInfo']['InformationURL'])) {
269
                $aboutService = reset($state['Destination']['UIInfo']['InformationURL']);
270
            }
271
        }
272
273
        $statsInfo = [];
274
        if (isset($state['Destination']['entityid'])) {
275
            $statsInfo['spEntityID'] = $state['Destination']['entityid'];
276
        }
277
        Stats::log('consent:reject', $statsInfo);
278
279
        $t = new Template($this->config, 'consent:noconsent.twig');
280
        $translator = $t->getTranslator();
0 ignored issues
show
Unused Code introduced by
The assignment to $translator is dead and can be removed.
Loading history...
281
        $t->data['dstMetadata'] = $state['Destination'];
282
        $t->data['resumeFrom'] = $resumeFrom;
283
        $t->data['aboutService'] = $aboutService;
284
        $t->data['logoutLink'] = $logoutLink;
285
        return $t;
286
    }
287
288
289
    /**
290
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
291
     *
292
     * @return \SimpleSAML\HTTP\RunnableResponse
293
     */
294
    public function logout(Request $request): RunnableResponse
295
    {
296
        $stateId = $request->query->get('StateId', null);
297
        if ($stateId === null) {
298
            throw new Error\BadRequest('Missing required StateId query parameter.');
299
        }
300
301
        $state = $this->authState::loadState($stateId, 'consent:request');
302
        if (is_null($state)) {
303
            throw new Error\NoState();
304
        }
305
        $state['Responder'] = ['\SimpleSAML\Module\consent\Logout', 'postLogout'];
306
307
        $idp = IdP::getByState($state);
308
        return new RunnableResponse([$idp, 'handleLogoutRequest'], [&$state, $stateId]);
309
    }
310
311
312
    /**
313
     * @return \SimpleSAML\XHTML\Template
314
     */
315
    public function logoutcompleted(): Template
316
    {
317
        return new Template($this->config, 'consent:logout_completed.twig');
318
    }
319
}
320