-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWebformHelper.php
More file actions
306 lines (268 loc) · 10.5 KB
/
Copy pathWebformHelper.php
File metadata and controls
306 lines (268 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
<?php
namespace Drupal\os2forms_nemlogin_openid_connect\Helper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\os2web_nemlogin\Plugin\AuthProviderInterface;
use Drupal\os2web_nemlogin\Service\AuthProviderService;
use Drupal\webform\Utility\WebformFormHelper;
use Drupal\webform\WebformInterface;
use Drupal\webform\WebformRequestInterface;
use Drupal\webform\WebformSubmissionInterface;
use Symfony\Component\Yaml\Yaml;
/**
* Webform helper.
*/
class WebformHelper {
use StringTranslationTrait;
private const TEMPORARY_KEY = 'os2forms_nemlogin_openid_connect';
/**
* The auth provider service.
*
* @var \Drupal\os2web_nemlogin\Service\AuthProviderService
*/
private AuthProviderService $authProviderService;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
private MessengerInterface $messenger;
/**
* The route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
private RouteMatchInterface $routeMatch;
/**
* The webform request handler.
*
* @var \Drupal\webform\WebformRequestInterface
*/
private WebformRequestInterface $webformRequest;
/**
* Constructor.
*/
public function __construct(AuthProviderService $authProviderService, MessengerInterface $messenger, RouteMatchInterface $routeMatch, WebformRequestInterface $webformRequest) {
$this->authProviderService = $authProviderService;
$this->messenger = $messenger;
$this->routeMatch = $routeMatch;
$this->webformRequest = $webformRequest;
}
/**
* Get auth provider plugin for a webform.
*
* Resolves the plugin from the webform's NemID settings (session_type),
* matching how os2forms_nemid resolves the plugin used for logging in, and
* falls back to the site-wide active plugin.
*
* @param \Drupal\webform\WebformInterface|null $webform
* The webform. If not set, the webform of the current request, if any, is
* used.
*
* @return \Drupal\os2web_nemlogin\Plugin\AuthProviderInterface
* The auth provider plugin.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function getAuthProviderPlugin(?WebformInterface $webform = NULL): AuthProviderInterface {
$webform ??= $this->webformRequest->getCurrentWebform();
$settings = $webform?->getThirdPartySetting('os2forms', 'os2forms_nemid');
$sessionType = $settings['session_type'] ?? NULL;
return !empty($sessionType)
? $this->authProviderService->getPluginInstance($sessionType)
: $this->authProviderService->getActivePlugin();
}
/**
* Implements hook_form_alter().
*
* @phpstan-param array<string, mixed> $form
*/
public function formAlter(array &$form, FormStateInterface $formState, string $formId): void {
$data = $formState->getTemporaryValue(self::TEMPORARY_KEY);
if (FALSE === ($data['access'] ?? TRUE)) {
// Flattening the elements makes it much easier to access nested elements.
$elements = &WebformFormHelper::flattenElements($form['elements']);
$this->messenger->addError($this->t('Access to form denied'));
if (isset($data['message'])) {
$form['os2forms_nemlogin_openid_connect_message'] = [
'#theme' => 'status_messages',
'#message_list' => [
'error' => [$data['message']],
],
];
}
// Hide all actions ….
$form['actions']['#access'] = FALSE;
// … and fields.
foreach ($elements as &$element) {
$element['#access'] = FALSE;
}
}
}
/**
* Implements hook_ENTITY_TYPE_prepare_form().
*/
public function webformSubmissionPrepareForm(WebformSubmissionInterface $webformSubmission, string $operation, FormStateInterface $formState): void {
// Only perform access check when displaying submission form.
$accessCheckRouteNames = [
// Webform attached to a node.
'entity.node.canonical',
// Creating a new submission.
'entity.webform.canonical',
// Editing a submission.
'entity.webform_submission.edit_form',
];
if (!in_array($this->routeMatch->getRouteName(), $accessCheckRouteNames, TRUE)) {
return;
}
try {
$error = $this->checkAccess($webformSubmission, $operation, $formState);
if (NULL !== $error) {
$webform = $webformSubmission->getWebform();
$settings = $webform->getThirdPartySettings('os2forms')['os2forms_nemid']['os2forms_nemlogin_openid_connect']['authentication_settings'] ?? NULL;
$message = !empty($settings['error_message']) ? $settings['error_message'] : $error;
$formState->setTemporaryValue(self::TEMPORARY_KEY, [
'access' => FALSE,
'message' => $message,
]);
}
}
catch (\Exception $exception) {
// Only the gods know what can go wrong in the code above.
}
}
/**
* Check access.
*
* @return string|null
* Access denied message if any or null.
*/
private function checkAccess(WebformSubmissionInterface $webformSubmission, string $operation, FormStateInterface $formState): ?string {
$webform = $webformSubmission->getWebform();
$settings = $webform->getThirdPartySettings('os2forms')['os2forms_nemid']['os2forms_nemlogin_openid_connect']['authentication_settings'] ?? NULL;
// Both User claim and Form element must be set to check access.
if (!empty($settings['user_claim']) && !empty($settings['element_key'])) {
$elementKey = $settings['element_key'];
$userClaim = $settings['user_claim'];
$plugin = $this->getAuthProviderPlugin($webform);
if (!$plugin->isAuthenticated()) {
return (string) $this->t('Not authenticated');
}
$expected = $webformSubmission->getData()[$elementKey] ?? NULL;
if (empty($expected)) {
return (string) $this->t('Expected value not defined');
}
$actual = $plugin->fetchValue($userClaim);
if ((string) $actual !== (string) $expected) {
return (string) $this->t('Actual value does not match expected value');
}
}
// All's good!
return NULL;
}
/**
* Implements hook_webform_third_party_settings_form_alter().
*
* @phpstan-param array<string, mixed> $form
*/
public function webformThirdPartySettingsFormAlter(array &$form, FormStateInterface $form_state): void {
/** @var \Drupal\Core\Entity\EntityFormInterface $formObject */
$formObject = $form_state->getFormObject();
/** @var \Drupal\webform\WebformInterface $webform */
$webform = $formObject->getEntity();
$settings = $webform->getThirdPartySetting('os2forms', 'os2forms_nemid');
$options = $this->getUserClaimOptions($webform);
$form['third_party_settings']['os2forms']['os2forms_nemid']['os2forms_nemlogin_openid_connect']['authentication_settings'] = [
'#type' => 'fieldset',
'#title' => $this->t('Authentication settings'),
'#states' => [
'visible' => [
[':input[name="third_party_settings[os2forms][os2forms_nemid][webform_type]"]' => ['!value' => '']],
],
],
];
$form['third_party_settings']['os2forms']['os2forms_nemid']['os2forms_nemlogin_openid_connect']['authentication_settings']['user_claim'] = [
'#type' => 'select',
'#title' => $this->t('User claim'),
'#default_value' => $settings['os2forms_nemlogin_openid_connect']['authentication_settings']['user_claim'] ?? NULL,
'#empty_option' => $this->t('Not specified'),
'#options' => $options,
'#description' => $this->t('User data field whose value must match the value of the selected form element'),
'#states' => [
'required' => [
[':input[name="third_party_settings[os2forms][os2forms_nemid][os2forms_nemlogin_openid_connect][authentication_settings][element_key]"]' => ['!value' => '']],
],
],
];
$options = $this->getElementKeyOptions($webform);
$form['third_party_settings']['os2forms']['os2forms_nemid']['os2forms_nemlogin_openid_connect']['authentication_settings']['element_key'] = [
'#type' => 'select',
'#title' => $this->t('Form element'),
'#default_value' => $settings['os2forms_nemlogin_openid_connect']['authentication_settings']['element_key'] ?? NULL,
'#empty_option' => $this->t('Not specified'),
'#options' => $options,
'#description' => $this->t('Form element whose value must match the value of the User data field'),
'#states' => [
'required' => [
[':input[name="third_party_settings[os2forms][os2forms_nemid][os2forms_nemlogin_openid_connect][authentication_settings][user_claim]"]' => ['!value' => '']],
],
],
];
$form['third_party_settings']['os2forms']['os2forms_nemid']['os2forms_nemlogin_openid_connect']['authentication_settings']['error_message'] = [
'#type' => 'textfield',
'#title' => $this->t('Error message'),
'#default_value' => $settings['os2forms_nemlogin_openid_connect']['authentication_settings']['error_message'] ?? NULL,
'#description' => $this->t('Message to show to user if access is denied. If not set, a generic message will be shown.'),
];
}
/**
* Get user claim options.
*
* @param \Drupal\webform\WebformInterface $webform
* The webform.
*
* @return array
* The user claim options.
*
* @phpstan-return array<string, mixed>
*/
private function getUserClaimOptions(WebformInterface $webform): array {
try {
$plugin = $this->getAuthProviderPlugin($webform);
$claims = $plugin->getConfiguration()['nemlogin_openid_connect_user_claims'] ?? '';
$value = Yaml::parse($claims);
if (is_array($value)) {
asort($value);
return $value;
}
}
catch (\Exception $e) {
}
return [];
}
/**
* Get element key options.
*
* Only simple text elements, i.e. text fields and hidden fields, are
* returned.
*
* @param \Drupal\webform\WebformInterface $webform
* The webform.
*
* @return array
* The element key options.
*
* @phpstan-return array<string, mixed>
*/
private function getElementKeyOptions(WebformInterface $webform): array {
$elements = $webform->getElementsDecodedAndFlattened();
$textElements = array_filter($elements, static function (array $element) {
return in_array($element['#type'], ['textfield', 'hidden']);
});
return array_map(static function (array $element) {
return $element['#title'];
}, $textElements);
}
}