forked from Stanford/WMD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webauth.module
681 lines (579 loc) · 20.4 KB
/
webauth.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
<?php
/**
* @file
* Authenticates users through Stanford WebAuth
*
*/
define('WEBAUTH_DOMAIN', 'stanford.edu');
/**
* Implements hook_boot().
*
* This functions very very early, before most of Drupal has even loaded.
*
* The sole purposes of this function is to insure HTTPS protocol, and
* the security of the session.
*/
function webauth_boot() {
if (!empty($_SERVER['HTTPS'])) {
global $base_url, $user, $base_path;
// Mandate HTTPS for sessions.
ini_set('session.cookie_secure', 1);
$base_url = str_replace('http://', 'https://', $base_url);
if ($user->uid > 0) {
setcookie("WMDsecureLogin", 1, REQUEST_TIME + 3600, $base_path);
}
}
elseif (isset($_COOKIE["WMDsecureLogin"]) && $_COOKIE["WMDsecureLogin"]) {
// An session seems to exist, but we are not in HTTPs.
// Redirect so we can start secure session.
global $base_url, $base_path;
$url = $base_url . '?q=' . $_GET['q'];
$url = str_replace('http://', 'https://', $url);
header("Location: $url");
}
}
/**
* Implements hook_init().
*
* If a user was created via webauth, we validate their session there.
*
* This function also insures that webauth is handling 403s, and that
* pages for logged in users are not cached in browsers.
*/
function webauth_init() {
global $_webauth_session, $user;
$is_return_url = (bool) ($_GET['q'] == variable_get('webauth_path', conf_path() . '/webauth') . '/login');
$no_check_php_loop = (bool) (array_pop(explode('/', $_GET['q'])) != 'check.php');
$access_denied_page = variable_get('site_403', '');
// Update our access denied page.
if ($access_denied_page != 'webauth/403') {
variable_set('site_403', 'webauth/403');
}
if ($user->uid > 0 && $no_check_php_loop) {
header("Cache-Control: no-store, no-cache, must-revalidate");
// We only want to go further and check the wa_session if this user is
// authenticated via webauth.
if (db_query("SELECT * FROM {authmap} WHERE uid = :uid and module = :module", array(':uid' => $user->uid, ':module' => 'webauth'))->fetchField()) {
$_webauth_session = new WebAuthSession();
if ($_webauth_session->isLoggedIn() && !$_webauth_session->isValidSession()) {
// The webauth session has expired, so destroy the current session
session_destroy();
// Start a new session so that we don't clobber other functions that expect
// a session (like logout)
session_start();
// Only variables can be passed by reference workaround.
$null = NULL;
user_module_invoke('user/logout', $null, $user);
// Load the anonymous user
$user = drupal_anonymous_user();
}
}
}
}
/**
* Implements hook_menu().
*/
function webauth_menu() {
$items = array();
// Setup our authentication URL
$path = variable_get('webauth_path', conf_path() . '/webauth') . '/login';
$items[$path] = array(
'page callback' => 'webauth_return',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['webauth/403'] = array(
'page callback' => 'webauth_error_page',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['admin/config/webauth'] = array(
'title' => 'WebAuth',
'type' => MENU_NORMAL_ITEM,
'description' => 'Authenticate through Stanford WebAuth',
'page callback' => 'drupal_get_form',
'page arguments' => array('webauth_admin_settings'),
'access arguments' => array('administer site configuration'),
'file' => 'webauth.admin.inc',
);
$items['admin/config/webauth/settings'] = array(
'title' => 'WebAuth Settings',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['admin/config/webauth/authorizations'] = array(
'title' => 'Authorizations',
'description' => 'Edit the users and groups that are required for access.',
'page callback' => 'drupal_get_form',
'page arguments' => array('webauth_admin_users'),
'access arguments' => array('administer site configuration'),
'file' => 'webauth.admin.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 1,
);
$items['admin/config/webauth/mappings'] = array(
'title' => 'Role Mappings',
'description' => 'Edit the groups that can use WebAuth for content access.',
'page callback' => 'drupal_get_form',
'page arguments' => array('webauth_admin_groups'),
'access arguments' => array('administer site configuration'),
'file' => 'webauth.admin.inc',
'type' => MENU_LOCAL_TASK,
);
return $items;
}
/**
* Implements hook_block_info().
*/
function webauth_block_info() {
$blocks['webauth_login_block'] = array(
'info' => t('WebAuth Authentication'),
'status' => 1,
'visibility' => BLOCK_VISIBILITY_NOTLISTED,
'pages' => "user\nuser/*",
'weight' => 0,
'region' => 'sidebar_first'
);
return $blocks;
}
/**
* Implements hook_block_configure().
*/
function webauth_block_configure($delta = '') {
$form = array();
switch ($delta) {
case 'webauth_login_block':
$form['webauth_link_text'] = array(
'#type' => 'textfield',
'#title' => t('Text of the WebAuth login link'),
'#require' => TRUE,
'#size' => 60,
'#description' => t('Here you can replace the text of the WebAuth link.'),
'#default_value' => variable_get('webauth_link_text', 'Log in with WebAuth'),
);
}
return $form;
}
/**
* Implements hook_block_save().
*/
function webauth_block_save($delta = '', $edit = array()) {
switch ($delta) {
case 'webauth_login_block':
variable_set('webauth_link_text', filter_xss($edit['webauth_link_text']));
}
}
/**
* Implements hook_block_view().
*/
function webauth_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'webauth_login_block':
// only show block for anonymous users
if (user_is_logged_in()) { return $block; }
$block = array(
'subject' => t('WebAuth Login'),
'content' => _webauth_login_url_html(),
);
break;
}
return $block;
}
/**
* Implements hook_block_view_alter().
*/
function webauth_block_view_user_login_alter(&$data, $block) {
$allow_local = variable_get('webauth_allow_local', TRUE);
if (!$allow_local) {
unset($data['content']);
}
else {
$data['subject'] = t('Local User Login');
}
}
/**
* Generate the login block content
*/
function _webauth_login_url_html() {
global $user, $base_url, $_webauth_session;
// Create a webauth session if needed and not already created.
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
$webauth_login = $_webauth_session->getLoginUrl($_GET['q']);
if ($user->uid === 0) {
return theme('webauth_login_block',array('login_url' => $webauth_login, 'login_text' => variable_get('webauth_link_text', 'Log in with WebAuth')));
}
return NULL;
}
/**
* Handle 403 errors by redirecting users to webauth for login.
*
* If, however, they are already logged in and don't have access
* (for instance, a normal user requesting /admin), then display
* a normal error message.
*/
function webauth_error_page() {
global $_webauth_session, $user;
// @todo: Move this into a static getWebAuthSession() function within the class.
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
// If logged in.
if ($user->uid) {
// Get restrict message
$webauth_restrict_message = filter_xss_admin(t(variable_get('webauth_restrict_message',
'This content has been restricted by the author or by the site administrator.')));
// If a custom message exists, create 403, and print message.
if ($webauth_restrict_message) {
drupal_add_http_header('Status', '403 Forbidden');
drupal_set_title(t('Access denied'));
return $webauth_restrict_message;
}
// If a message doesn't exist display default access denied page
else {
return MENU_ACCESS_DENIED;
}
}
// If not logged in
else {
// If a redirect location doesn't exist
if (!$redirect = variable_get('webauth_destination', '')) {
// then get the current url
$redirect = drupal_get_destination();
$redirect = $redirect['destination'];
}
// Redirect to login
$_webauth_session->getWeblogin($redirect);
}
}
/**
* Function to return from webauth login from.
*
* This handles logging a user in and then redirecting them to the page they
* were previously on.
*/
function webauth_return() {
global $_webauth_session, $user;
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
if ($user->uid == 0) {
if ($_webauth_session->isValidSession()) {
$form_state = array();
$form_state['values']['name'] = $_webauth_session->getSessionData('wa_remote_user');
$form_state['values']['pass'] = 'dummy';
$form_state['weblogin']['server'] = variable_get('webauth_domain', WEBAUTH_DOMAIN);
drupal_form_submit('user_login', $form_state);
}
else {
session_destroy();
return $_webauth_session->getWeblogin();
}
}
if (!$_webauth_session->isValidSession()) {
drupal_set_message(t('Unknown error occurred.'));
}
$return = $_webauth_session->getReturnUrl(TRUE);
$login = variable_get('webauth_path', conf_path() . '/webauth') . '/login';
if (substr($return, 0, strlen($login)) == $login) {
$return = '';
}
drupal_goto($return);
}
/**
* Implements hook_theme().
*/
function webauth_theme($existing, $type, $theme, $path) {
return array(
'webauth_htaccess' => array(
'template' => 'webauth_htaccess',
'variables' => array(
'groups' => NULL,
'require_valid_user' => NULL,
'users' => NULL,
'privgroups' => NULL,
'rewrite_url' => NULL),
),
'webauth_login_block' => array(
'template' => 'webauth_login_block',
'variables' => array(
'login_url' => NULL,
'login_text' => NULL,
),
),
);
}
/**
* Implements hook_form_alter().
*
* This insures that user login elements are webauth-enabled.
*
*/
function webauth_form_alter(&$form, &$form_state, $form_id) {
global $user, $base_url, $_webauth_session;
switch ($form_id) {
case 'user_profile_form':
$account = $form['#user'];
if (!empty($account->roles)) {
if (in_array(variable_get('webauth_default_role', ''), array_keys($account->roles))) {
// Hide elements for SUNet Users.
$form['account']['name']['#type'] = 'hidden';
$form['account']['name']['#value'] = $account->name;
$form['account']['pass']['#type'] = 'hidden';
$form['account']['current_pass']['#type'] = 'hidden';
unset($form['account']['current_pass_required_values']['#value']['mail']);
}
}
break;
case 'user_login_block':
case 'user_login':
$form['name']['#title'] = t('Local Drupal Username');
$form['pass']['#title'] = t('Local Drupal Password');
if ($form_id === 'user_login') {
// create a WebAuth login link
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
$webauth_login = $_webauth_session->getLoginUrl($_GET['q']);
// create a wrapper for the webauth link so we can de-emphasize the local user login form
$form['webauth_login_wrapper']['#title'] = t('WebAuth Login');
$form['webauth_login_wrapper']['#type'] = 'fieldset';
$form['webauth_login_wrapper']['#collapsible'] = TRUE;
$form['webauth_login_wrapper']['#collapsed'] = FALSE;
$form['webauth_login_wrapper']['webauth_login_link']['#markup'] = theme('webauth_login_block',array('login_url' => $webauth_login, 'login_text' => variable_get('webauth_link_text', 'Log in with WebAuth')));
// create a wrapper for the form, so we can de-emphasize the local user login form
$form['local_login_wrapper']['#title'] = 'Local User Login';
$form['local_login_wrapper']['#type'] = 'fieldset';
$form['local_login_wrapper']['#collapsible'] = TRUE;
$form['local_login_wrapper']['#collapsed'] = TRUE;
// copy and move the form fields into the wrapper
$form['local_login_wrapper']['name'] = $form['name'];
$form['local_login_wrapper']['pass'] = $form['pass'];
$form['local_login_wrapper']['actions'] = $form['actions'];
unset($form['name']);
unset($form['pass']);
unset($form['actions']);
}
// Create a webauth session if needed and not already created.
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
if (isset($form_state['weblogin']['server'])) {
$form['#validate'] = array(
'user_login_name_validate',
// webauth_login_validate replaces user_login_authenticate_validate
'webauth_login_validate',
'user_login_final_validate',
);
}
// drupal_execute() for user_login comes here, and we can lose our login
// redirect context, so if we are on the auth path here, we should stop
// altering at this point.
//
// I don't love this fix, but it's necessary given how the $_webauth_session
// object is constructud at the moment.
$path = variable_get('webauth_path', conf_path() . '/webauth') . '/login';
if ($_GET['q'] == $path) {
return;
}
break;
}
}
/**
* Implements hook_user_login().
*/
function webauth_user_login(&$edit, &$account) {
// If this is a WebAuth account, check for roles and re-grant new roles.
if (db_query("SELECT * FROM {authmap} WHERE uid = :uid and module = :module", array(':uid' => $account->uid, ':module' => 'webauth'))->fetchField()) {
webauth_grant_roles($edit, $account);
}
}
/**
* Implements hook_user_insert().
*/
function webauth_user_insert(&$edit, &$account, $category) {
webauth_update_fields($edit, $account);
}
/**
* Implements hook_user_delete().
*/
function webauth_user_delete($account) {
db_delete('webauth_roles_history')
->condition('uid', $account->uid)
->execute();
}
/**
* Implements hook_user_logout().
*/
function webauth_user_logout($account) {
if (isset($_COOKIE['WMDsecureLogin'])) {
unset($_COOKIE['WMDsecureLogin']);
setcookie('WMDsecureLogin', '', REQUEST_TIME - 3600);
}
unset($_SESSION['wa_session_data']);
unset($_SESSION['wa_return_url']);
}
/**
* This is a helper function to store webauth-derived data for the user account.
*/
function webauth_update_fields(&$edit, &$account) {
// We only want to run these if the user is self-creating via webauth.
// Otherwise an admin user will transpose their own values onto any
// account they manually create.
global $_webauth_session;
global $user;
if ($user->uid == 0) {
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
$mail = $_webauth_session->getSessionData('wa_ldap_mail');
$mail = isset($mail) ? $mail : $account->name;
db_update('users')
->fields(array(
'mail' => $mail,
))
->condition('uid', $account->uid)
->execute();
}
}
/**
* This is a helper function to grant drupal roles based on webauth data.
*
* This is called when new users are created via webauth, or when "local"
* drupal users log in. It could also be invoked by other operations to
* sync up a users roles based on their webauth settings.
*/
function webauth_grant_roles(&$edit, &$account) {
global $_webauth_session;
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
if ($_webauth_session->isValidSession()) {
$groups = $_webauth_session->getLdapGroups();
$new = array('roles' => $account->roles);
// Add SUNet User role for all valid users.
$default_name = db_query("SELECT name FROM {role} WHERE rid = :rid", array(':rid' => variable_get('webauth_default_role', 0)))->fetchField();
if (variable_get('webauth_default_role', 0) != 0 && !isset($new['roles'][variable_get('webauth_default_role', 0)])) {
$new['roles'][variable_get('webauth_default_role', 0)] = $default_name;
}
// Unserialize data.
$data = unserialize($account->data);
$data = is_array($data) ? $data : array();
$current = array();
// Find all roles that are in the webauth_roles table and add any ones that user is in.
$result = db_query("SELECT r.rid, r.name, wr.wa_group AS `group`, wr.warid FROM {webauth_roles} wr INNER JOIN {role} r ON r.rid = wr.rid");
while ($role = $result->fetchObject()) {
if (in_array($role->group, $groups)) {
$new['roles'][$role->rid] = $role->name;
$data['webauth_assigned_roles'][$role->rid] = $role->name;
$current[$role->rid] = $role->rid;
db_delete('webauth_roles_history')
->condition('warid', $role->warid)
->condition('uid', $account->uid)
->execute();
$id = db_insert('webauth_roles_history')
->fields(array(
'warid' => $role->warid,
'uid' => $account->uid,
'rid' => $role->rid,
))
->execute();
}
}
// Close out any groups they shouldn't have access to.
$result = db_query("SELECT * FROM {webauth_roles_history} WHERE uid = :uid", array(':uid' => $account->uid));
while ($role = $result->fetchObject()) {
if (!isset($current[$role->rid])) {
unset($data['webauth_assigned_roles'][$role->rid]);
unset($new['roles'][$role->rid]);
db_delete('webauth_roles_history')
->condition('uid', $account->uid)
->condition('rid', $role->rid)
->execute();
db_delete('users_roles')
->condition('uid', $account->uid)
->condition('rid', $role->rid)
->execute();
}
}
$account->data = serialize($data);
user_save($account, $new);
}
}
/**
* Perform webauth validation on users who come in via the normal Drupal login
* form or block.
*/
function webauth_login_validate($form, &$form_state) {
global $_webauth_session;
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
if ($_webauth_session->isValidSession()) {
$name = $form_state['values']['name'] . '@' . $form_state['weblogin']['server'];
user_external_login_register($name, 'webauth');
// Replacement user_login_authenticate_validate() function must set $form_state['uid']
// for user_login_final_validate() not to set_message an error.
$account = user_external_load($name);
$form_state['uid'] = $account->uid;
user_login_finalize($form_state['values']);
}
}
/**
* Function to write out our .htaccess file.
*/
function webauth_write_htaccess() {
global $_webauth_session;
if (!$_webauth_session) {
$_webauth_session = new WebAuthSession();
}
$groups = array();
$user_list = '';
$rewrite_url = '';
// Get all the available groups
$result = db_query("SELECT DISTINCT(wa_group) AS `group` FROM {webauth_roles} WHERE rid > :rid", array(':rid' => 2));
while ($group = $result->fetchField()) {
$groups[] = $group;
}
$user_list = array();
$users = explode("\n", variable_get('webauth_require_users', ''));
foreach ($users as $u) {
$u = trim($u);
if ($u != '') {
$user_list[] = $u;
}
}
$privgroup_list = array();
$privgroups = explode("\n", variable_get('webauth_require_privgroups', ''));
foreach ($privgroups as $p) {
$p = trim($p);
if ($p != '') {
$privgroup_list[] = $p;
}
}
if (!variable_get('clean_url', 0)) {
$path = $_webauth_session->getLoginUrl();
$new_path = base_path() . '?q=' . variable_get('webauth_path', conf_path() . '/webauth') . '/login';
$rewrite_url .= 'RewriteRule login(.*)$ ' . $new_path . '$1 [L,R=301]';
}
// Theme contents of the .htaccess file.
$htaccess_file = theme('webauth_htaccess', array('groups' => $groups, 'require_valid_user' => variable_get('webauth_require_valid_user', 0), 'users' => $user_list, 'privgroups' => $privgroup_list, 'rewrite_url' => $rewrite_url));
// Get the path or create it inside the files dir.
$webauth_path = variable_get('webauth_path', conf_path() . '/webauth');
// Set .htaccess file location
$webauth_htaccess = $webauth_path . '/.htaccess';
// If webauth dir doesn't exist yet, create it.
if (@is_dir($webauth_path) === FALSE) {
// Create dir.
mkdir($webauth_path, 0755);
}
// Copy necessary check.php file over.
$default_check_file = drupal_get_path('module', 'webauth') . '/default/check.php';
copy($default_check_file, $webauth_path . '/check.php');
// Save .htaccess file to location.
$fp = fopen($webauth_htaccess, 'w');
fwrite($fp, $htaccess_file);
fclose($fp);
}