Passed
Push — master ( 6b04b7...569dd7 )
by Thijs
14:08 queued 11:48
created

ConsentController   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 284
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 135
c 2
b 0
f 0
dl 0
loc 284
rs 9.2
wmc 40

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setAuthState() 0 3 1
A setLogger() 0 3 1
F getconsent() 0 139 26
B noconsent() 0 42 7
A logoutcompleted() 0 3 1
A logout() 0 15 3

How to fix   Complexity   

Complex Class

Complex classes like ConsentController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ConsentController, and based on these observations, apply Extract Interface, too.

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