Passed
Pull Request — master (#14)
by Tim
01:48
created

ConsentController::getconsent()   F

Complexity

Conditions 30
Paths 15590

Size

Total Lines 154
Code Lines 99

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
cc 30
eloc 99
c 7
b 0
f 0
nc 15590
nop 1
dl 0
loc 154
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        // Parse parameters
170
        if (array_key_exists('name', $state['Source'])) {
171
            $srcName = $state['Source']['name'];
172
        } elseif (array_key_exists('OrganizationDisplayName', $state['Source'])) {
173
            $srcName = $state['Source']['OrganizationDisplayName'];
174
        } else {
175
            $srcName = $state['Source']['entityid'];
176
        }
177
178
        if (array_key_exists('name', $state['Destination'])) {
179
            $dstName = $state['Destination']['name'];
180
        } elseif (array_key_exists('OrganizationDisplayName', $state['Destination'])) {
181
            $dstName = $state['Destination']['OrganizationDisplayName'];
182
        } else {
183
            $dstName = $state['Destination']['entityid'];
184
        }
185
186
        // Make, populate and layout consent form
187
        $t = new Template($this->config, 'consent:consentform.twig');
188
        $translator = $t->getTranslator();
189
        $t->data['attributes'] = $attributes;
190
        $t->data['checked'] = $state['consent:checked'];
191
        $t->data['stateId'] = $stateId;
192
193
        $t->data['srcName'] = is_array($srcName) ? $translator->getPreferredTranslation($srcName) : $srcName;
194
        $t->data['dstName'] = is_array($dstName) ? $translator->getPreferredTranslation($dstName) : $dstName;
195
196
        if (array_key_exists('descr_purpose', $state['Destination'])) {
197
            $t->data['dstDesc'] = $translator->getPreferredTranslation(
198
                Utils\Arrays::arrayize(
199
                    $state['Destination']['descr_purpose'],
200
                    'en'
201
                )
202
            );
203
        }
204
205
        // Fetch privacy policy
206
        if (
207
            array_key_exists('UIInfo', $state['Destination']) &&
208
            array_key_exists('PrivacyStatementURL', $state['Destination']['UIInfo']) &&
209
            (!empty($state['Destination']['UIInfo']['PrivacyStatementURL']))
210
        ) {
211
            $privacypolicy = reset($state['Destination']['UIInfo']['PrivacyStatementURL']);
212
        } elseif (
213
            array_key_exists('UIInfo', $state['Source']) &&
214
            array_key_exists('PrivacyStatementURL', $state['Source']['UIInfo']) &&
215
            (!empty($state['Source']['UIInfo']['PrivacyStatementURL']))
216
        ) {
217
            $privacypolicy = reset($state['Source']['UIInfo']['PrivacyStatementURL']);
218
        } else {
219
            $privacypolicy = false;
220
        }
221
        if ($privacypolicy !== false) {
222
            $privacypolicy = str_replace(
223
                '%SPENTITYID%',
224
                urlencode($spentityid),
225
                $privacypolicy
226
            );
227
        }
228
        $t->data['sppp'] = $privacypolicy;
229
230
        // Set focus element
231
        switch ($state['consent:focus']) {
232
            case 'yes':
233
                $t->data['autofocus'] = 'yesbutton';
234
                break;
235
            case 'no':
236
                $t->data['autofocus'] = 'nobutton';
237
                break;
238
            case null:
239
            default:
240
                break;
241
        }
242
243
        $t->data['usestorage'] = array_key_exists('consent:store', $state);
244
245
        return $t;
246
    }
247
248
249
    /**
250
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
251
     *
252
     * @return \SimpleSAML\XHTML\Template
253
     */
254
    public function noconsent(Request $request): Template
255
    {
256
        $stateId = $request->query->get('StateId');
257
        if ($stateId === null) {
258
            throw new Error\BadRequest('Missing required StateId query parameter.');
259
        }
260
261
        $state = $this->authState::loadState($stateId, 'consent:request');
262
        if (is_null($state)) {
263
            throw new Error\NoState();
264
        }
265
266
        $resumeFrom = Module::getModuleURL(
267
            'consent/getconsent',
268
            ['StateId' => $stateId]
269
        );
270
271
        $logoutLink = Module::getModuleURL(
272
            'consent/logout',
273
            ['StateId' => $stateId]
274
        );
275
276
        $aboutService = null;
277
        if (!isset($state['consent:showNoConsentAboutService']) || $state['consent:showNoConsentAboutService']) {
278
            if (isset($state['Destination']['url.about'])) {
279
                $aboutService = $state['Destination']['url.about'];
280
            }
281
        }
282
283
        $statsInfo = [];
284
        if (isset($state['Destination']['entityid'])) {
285
            $statsInfo['spEntityID'] = $state['Destination']['entityid'];
286
        }
287
        Stats::log('consent:reject', $statsInfo);
288
289
        if (array_key_exists('name', $state['Destination'])) {
290
            $dstName = $state['Destination']['name'];
291
        } elseif (array_key_exists('OrganizationDisplayName', $state['Destination'])) {
292
            $dstName = $state['Destination']['OrganizationDisplayName'];
293
        } else {
294
            $dstName = $state['Destination']['entityid'];
295
        }
296
297
        $t = new Template($this->config, 'consent:noconsent.twig');
298
        $translator = $t->getTranslator();
299
        $t->data['dstMetadata'] = $state['Destination'];
300
        $t->data['resumeFrom'] = $resumeFrom;
301
        $t->data['aboutService'] = $aboutService;
302
        $t->data['logoutLink'] = $logoutLink;
303
        $t->data['dstName'] = htmlspecialchars(
304
            is_array($dstName) ? $translator->getPreferredTranslation($dstName) : $dstName
305
        );
306
        return $t;
307
    }
308
309
310
    /**
311
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
312
     *
313
     * @return \SimpleSAML\HTTP\RunnableResponse
314
     */
315
    public function logout(Request $request): RunnableResponse
316
    {
317
        $stateId = $request->query->get('StateId', null);
318
        if ($stateId === null) {
319
            throw new Error\BadRequest('Missing required StateId query parameter.');
320
        }
321
322
        $state = $this->authState::loadState($stateId, 'consent:request');
323
        if (is_null($state)) {
324
            throw new Error\NoState();
325
        }
326
        $state['Responder'] = ['\SimpleSAML\Module\consent\Logout', 'postLogout'];
327
328
        $idp = IdP::getByState($state);
329
        return new RunnableResponse([$idp, 'handleLogoutRequest'], [&$state, $stateId]);
330
    }
331
332
333
    /**
334
     * @return \SimpleSAML\XHTML\Template
335
     */
336
    public function logoutcompleted(): Template
337
    {
338
        return new Template($this->config, 'consent:logout_completed.twig');
339
    }
340
}
341