-
Notifications
You must be signed in to change notification settings - Fork 0
/
cwd_saml_mapping.module
421 lines (373 loc) · 16.5 KB
/
cwd_saml_mapping.module
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<?php
use Drupal\user\UserInterface;
use Drupal\cwd_saml_mapping\ShibbolethHelper;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* @file
* Primary module hooks for cwd_saml_mapping module.
*/
function cwd_saml_mapping_saml_sp_drupal_login_user_attributes_alter($user, $attributes) {
//-------------------------------------------------------------------------------------
// Logic for adding and removing users from roles via saml_role_mapping config entities
//-------------------------------------------------------------------------------------
//Get all our saml_role_mapping configs for processing
$entity_ids = \Drupal::entityQuery('saml_role_mapping')->condition('status', 1)->execute();
$configs = \Drupal::entityTypeManager()->getStorage('saml_role_mapping')->loadMultiple($entity_ids);
//Variables for storing data and signaling a user save is needed.
$saveUser = false;
$samlManagedRoles = [];
$userRolesToAdd = [];
$saml_property_mappings = ShibbolethHelper::getMappingArray();
$missing_property_messages = [];
$rolesUnableToEvaluateForRemoval = [];
foreach ($configs as $role_assigment_config) {
//Create a list of all roles managed by saml properties
$needsRole = false;
$role = $role_assigment_config->get('role');
if (!in_array($role, $samlManagedRoles)) {
$samlManagedRoles[] = $role;
}
//Property in saml we are looking at
$samlprop = $role_assigment_config->get('samlprop');
if($samlprop == "other") {
$samlprop = $role_assigment_config->get('samlother');
}
//Drupal's accepted values we configure on our end
$values = explode("\r\n", $role_assigment_config->get('values'));
//Catch condition the property is not release to us from shibboleth (ex. Test Shibboleth does no release groups property)
if (!array_key_exists($samlprop, $attributes)) {
$missing_property_messages[] = $saml_property_mappings[$samlprop] . " => " . $role_assigment_config->get('id');
$rolesUnableToEvaluateForRemoval[] = $role;
continue;
}
//Catch condition that the property is released but has no data
if (is_null($attributes[$samlprop])) {
\Drupal::logger('cwd_saml_mapping')->warning("Shibboleth data not found for " . $saml_property_mappings[$samlprop] . " need to check the saml_role_mapping configuration for " . $role_assigment_config->get('id'));
$rolesUnableToEvaluateForRemoval[] = $role;
continue;
}
$specialmatchcriteria = $role_assigment_config->get('specialmatchcriteria') ?? "none";
switch($specialmatchcriteria) {
case "none":
//If saml attribute has more than one value in a field we will look at all values
if (count($attributes[$samlprop]) > 1) {
$saml_pro_data = $attributes[$samlprop];
$needsRole = count(array_intersect($saml_pro_data, $values)) > 0;
}
else {
//All others we look for a single value in our accepted values for the SAML property
$saml_pro_data = $attributes[$samlprop][0];
$needsRole = in_array($saml_pro_data, $values);
}
break;
case "contains":
//If saml attribute has more than one value in a field we will look at all values
if (count($attributes[$samlprop]) > 1) {
$saml_pro_data = $attributes[$samlprop];
//Search each saml data element in array if it contains any of the accepted values
foreach($saml_pro_data as $saml_data_element) {
if($needsRole) {
break;
}
//Find any partial containing match of the value we are searching for
foreach($values as $stringtofind) {
if(str_contains($saml_data_element,$stringtofind)) {
$needsRole = true;
break;
}
}
}
}
else {
//Single valued saml property
$saml_pro_data = $attributes[$samlprop][0];
//Check if the saml data contains any of our accepted values
foreach($values as $stringtofind) {
if(str_contains($saml_pro_data,$stringtofind)) {
$needsRole = true;
break;
}
}
}
break;
default:
break;
}
//If condition is met to add this role add to our array for processing after all configs have been evaluated
if ($needsRole) {
$userRolesToAdd[] = $role;
}
} // end of for loop processing saml_role_mapping configs
//Log message about configurations with missing properties
if(count($missing_property_messages) > 0) {
$message = "Property not found in Shibboleth data found for [" . implode("] , [", $missing_property_messages) . "]";
\Drupal::logger('cwd_saml_mapping')->info($message);
}
//Take and add roles to user as needed
foreach ($userRolesToAdd as $roleToAdd) {
if (!$user->hasRole($roleToAdd)) {
$user->addRole($roleToAdd);
$saveUser = true;
}
}
//Compute roles we need to take away and remove if needed
$userRolesToRemove = array_diff($samlManagedRoles, $userRolesToAdd);
//Don't remove roles we don't have all the properties from shibboleth to evaluate
$userRolesToRemove = array_diff($userRolesToRemove,$rolesUnableToEvaluateForRemoval);
foreach ($userRolesToRemove as $roleToRemove) {
if ($user->hasRole($roleToRemove)) {
$user->removeRole($roleToRemove);
$saveUser = true;
}
}
//-------------------------------------------------------------------------------------
// End of role logic
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
// Use global config to set user name
//-------------------------------------------------------------------------------------
$global_cwd_saml_mapping_config = \Drupal::config('cwd_saml_mapping.config_form');
$username_saml_prop = $global_cwd_saml_mapping_config->getRawData()['username_saml_prop'];
$new_user_name = $attributes[$username_saml_prop][0];
if ($user->name != $new_user_name) {
$user->name = $attributes[$username_saml_prop];
$saveUser = true;
}
//-------------------------------------------------------------------------------------
// End of use global config to set user name
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
// Logic for mapping data SAML into user fields
//-------------------------------------------------------------------------------------
$entity_ids = \Drupal::entityQuery('saml_field_mapping')->condition('status', 1)->execute();
$configs = \Drupal::entityTypeManager()->getStorage('saml_field_mapping')->loadMultiple($entity_ids);
foreach ($configs as $field_mapping_config) {
$current_field_value = $user->{$field_mapping_config->get('field')}->getValue()[0]['value'];
$new_field_data = $attributes[$field_mapping_config->get('samlprop')];
if (empty($new_field_data)) {
continue;
}
if (count($new_field_data) > 1) {
$new_field_value = implode(", ", $new_field_data);
}
else {
$new_field_value = $new_field_data[0];
}
if ($current_field_value != $new_field_value) {
$user->{$field_mapping_config->get('field')} = $new_field_value;
$saveUser = true;
}
}
//-------------------------------------------------------------------------------------
// End of mapping data SAML into user fields
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
//Save user is we need to retain changes
//-------------------------------------------------------------------------------------
if ($saveUser) {
$user->save();
}
//-------------------------------------------------------------------------------------
// End save user logic
//-------------------------------------------------------------------------------------
}
function cwd_saml_mapping_preprocess_item_list(&$variables) {
//If we are not on the user login page abandon this hook.
$current_route_name = \Drupal::service('current_route_match')->getRouteName();
if ($current_route_name != "user.login" && $current_route_name != "cwd_saml_mapping.accessdenied") {
return;
}
//Look at our global moduel config to see if we use prod saml in production Pantheon
$config = \Drupal::config('cwd_saml_mapping.config_form');
$show_all_idps = $config->getRawData()['show_all_idps'];
if($show_all_idps) {
foreach ($variables['items'] as $index => $link) {
$idp_name = $link['value']->getText()->getArguments()['%idp'] ?? null;
$idp_class = strtolower(preg_replace("/\s+/", "_", $idp_name));
$link['value']->setText(new TranslatableMarkup($idp_name . " Login"));
$link['attributes']->addClass(['login-link-button', $idp_class]);
}
return;
}
$use_saml_in_prod = $config->getRawData()['use_prod_in_saml'];
$is_prod_and_use_prod_shibboleth = (isset($_ENV['PANTHEON_ENVIRONMENT']) && $_ENV['PANTHEON_ENVIRONMENT'] === 'live' && $use_saml_in_prod);
if ($is_prod_and_use_prod_shibboleth) {
//Loop through links and remove ones that contain 'test'
foreach ($variables['items'] as $index => $link) {
if (gettype($link['value']) != "object") {
continue;
}
elseif (get_class($link['value']) != "Drupal\Core\Link") {
continue;
}
$idp_name = $link['value']->getText()->getArguments()['%idp'] ?? null;
$idp_class = strtolower(preg_replace("/\s+/", "_", $idp_name));
if ($idp_name && str_contains(strtolower(($idp_name)), "test") && !$show_all_idps) {
unset($variables['items'][$index]);
}
else {
$friendly_name = str_replace(" Prod", "", $idp_name);
$link['value']->setText(new TranslatableMarkup($friendly_name . " Login"));
$link['attributes']->addClass(['login-link-button', $idp_class]);
}
}
}
else {
//Loop through links and remove ones that contain 'prod'
foreach ($variables['items'] as $index => $link) {
if (gettype($link['value']) != "object") {
continue;
}
elseif (get_class($link['value']) != "Drupal\Core\Link") {
continue;
}
$idp_name = $link['value']->getText()->getArguments()['%idp'] ?? null;
$idp_class = strtolower(preg_replace("/\s+/", "_", $idp_name));
if ($idp_name && str_contains(strtolower(($idp_name)), "prod") && !$show_all_idps) {
unset($variables['items'][$index]);
}
else {
$link['value']->setText(new TranslatableMarkup($idp_name . " Login"));
$link['attributes']->addClass(['login-link-button', $idp_class]);
}
}
}
}
function cwd_saml_mapping_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if ($form_id == 'user_login_form') {
$config = \Drupal::config('cwd_saml_mapping.config_form');
$form['#cache'] = ['max-age' => 0];
$hide_drupal_login_prod = $config->getRawData()['hide_drupal_login_prod'] ?? false;
$is_prod_and_hide = (isset($_ENV['PANTHEON_ENVIRONMENT']) && $_ENV['PANTHEON_ENVIRONMENT'] === 'live' && $hide_drupal_login_prod);
$hide_drupal_login = $config->getRawData()['hide_drupal_login'] ?? false;
$sso_text = $config->getRawData()['sso_text'] ?? "Login with your NetID";
$form['new'] = array(
'#markup' => '<hr/><h2>' . $sso_text . ':</h2>',
'#weight' => -999,
);
if($hide_drupal_login || $is_prod_and_hide) {
unset($form['name']);
unset($form['pass']);
unset($form['actions']);
unset($form['#submit']);
return;
}
$drupal_login_text = $config->getRawData()['drupal_login_text'] ?? "Login with Drupal";
$form['name']['#weight'] = 9999;
$form['pass']['#weight'] = 9999;
$form['actions']['#weight'] = 9999;
$form['orstatement'] = array(
'#markup' => '<hr/><h2>'.$drupal_login_text.':</h2>',
'#weight' => 9998,
);
unset($form['name']['#attributes']['autofocus']);
}
}
function cwd_saml_mapping_local_tasks_alter(&$local_tasks) {
$config = \Drupal::config('cwd_saml_mapping.config_form');
$hide_drupal_login_prod = $config->getRawData()['hide_drupal_login_prod'] ?? false;
$is_prod_and_hide = (isset($_ENV['PANTHEON_ENVIRONMENT']) && $_ENV['PANTHEON_ENVIRONMENT'] === 'live' && $hide_drupal_login_prod);
$hide_drupal_login = $config->getRawData()['hide_drupal_login'] ?? false;
if($hide_drupal_login || $is_prod_and_hide) {
unset($local_tasks['user.register']);
unset($local_tasks['user.login']);
}
}
function cwd_saml_mapping_user_login(UserInterface $account) {
$relay_state = $_REQUEST['RelayState'];
if($relay_state != "/") {
return;
}
$entity_ids = \Drupal::entityQuery('saml_login_redirect')->condition('status', 1)->execute();
if($entity_ids == null) {
return;
}
$configs = \Drupal::entityTypeManager()->getStorage('saml_login_redirect')->loadMultiple($entity_ids);
usort($configs, function ($a, $b) {
return $a->get('weight') <=> $b->get('weight');
});
$roles = $account->getRoles();
foreach ($configs as $config) {
$config_roles = explode(',', $config->get('roles'));
// if roles and config_roles have any common element then redirect
if (count(array_intersect($roles, $config_roles)) > 0) {
// get config value of redirect
$redirect = $config->get('redirect');
$redirect = _cwd_saml_mapping_return_token_url($redirect, $account);
\Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $redirect);
return;
}
}
}
function cwd_saml_mapping_user_logout($account) {
$entity_ids = \Drupal::entityQuery('saml_logout_redirect')->condition('status', 1)->execute();
if($entity_ids == null) {
return;
}
$configs = \Drupal::entityTypeManager()->getStorage('saml_logout_redirect')->loadMultiple($entity_ids);
usort($configs, function ($a, $b) {
return $a->get('weight') <=> $b->get('weight');
});
$roles = $account->getRoles();
foreach ($configs as $config) {
$config_roles = explode(',', $config->get('roles'));
// if roles and config_roles have any common element then redirect
if (count(array_intersect($roles, $config_roles)) > 0) {
// get config value of redirect
$redirect = $config->get('redirect');
$redirect = _cwd_saml_mapping_return_token_url($redirect, $account);
\Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $redirect);
return;
}
}
}
function _cwd_saml_mapping_return_token_url($redirect_string, $account) {
$redirect_compenents = array_filter(explode('/', $redirect_string));
if (in_array('{uid}', $redirect_compenents)) {
$redirect_string = str_replace('{uid}', $account->id(), $redirect_string);
}
if (in_array('{username}', $redirect_compenents)) {
$redirect_string = str_replace('{username}', $account->getAccountName(), $redirect_string);
}
if (in_array('{email}', $redirect_compenents)) {
$redirect_string = str_replace('{email}', $account->getEmail(), $redirect_string);
}
return $redirect_string;
}
function cwd_saml_mapping_preprocess_page(&$variables) {
$config = \Drupal::config('cwd_saml_mapping.config_form');
$restrict_all_pages = $config->getRawData()['restrict_all_pages'] ?? false;
if($restrict_all_pages) {
$allowed_paths = [
"/user/login",
"/accessdenied",
];
$restriction_choice = $config->getRawData()['restrict_pages_url'];
switch($restriction_choice) {
case "direct":
$url_string = "/saml/drupal_login";
$samlsp_login_config = \Drupal::config('saml_sp_drupal_login.config');
$idps = $samlsp_login_config->getRawData()['idp'];
if (isset($_ENV['PANTHEON_ENVIRONMENT']) && $_ENV['PANTHEON_ENVIRONMENT'] === 'live') {
$url_string .= "/" . $idps['cornell_prod'];
}
else {
$url_string .= "/" . $idps['cornell_test'];
}
break;
case "login":
default:
$url_string = "/user/login";
break;
}
$current_user = \Drupal::currentUser();
$current_path = \Drupal::service('path.current')->getPath();
$url_string .= "?returnTo=" .$current_path;
if(!in_array($current_path,$allowed_paths) && $current_user->isAnonymous() ) {
$response = new RedirectResponse($url_string);
\Drupal::service('kernel')->rebuildContainer();
$response->send();
}
}
}