forked from gapple/drupal-persistent_login
-
Notifications
You must be signed in to change notification settings - Fork 0
/
persistent_login.module
executable file
·528 lines (481 loc) · 19.9 KB
/
persistent_login.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
<?php
/**
* @file
* Provide a "Remember Me" checkbox in the login form.
*/
define('PERSISTENT_LOGIN_SECURE_PATHS', "user/*/*
user/*/address
cart/checkout
admin/settings/persistent_login
");
define('PERSISTENT_LOGIN_MAXLIFE', 30);
/**
* Implementation of hook_help().
*/
function persistent_login_help($path, $arg) {
if ($path == 'admin/help#persistent_login') {
return t('Provide a "Remember Me" checkbox in the login form.');
}
}
/**
* Implementation of hook_perm().
*/
function persistent_login_perm() {
return array('administer Persistent Login');
}
/**
* Implementation of hook_boot(). Before a cached page is served,
* perform a Persistent Login if appropriate. Persistent Login must
* operate during boot because if page caching is enabled, other hooks
* are never invoked unless the user is already logged in.
*/
function persistent_login_boot() {
_persistent_login_check();
}
/**
* Implementation of hook_init(). Before the menu system takes
* control, perform a Persistent Login if appropriate.
*/
function persistent_login_init() {
global $user;
// If the user is logged in only via Persistent Login, then don't let them
// visit restricted pages.
if (isset($_SESSION['persistent_login_login']) && _persistent_login_match($_GET['q'])) {
$_SESSION['persistent_login_default_user'] = $user->name;
$user = user_load(array('uid' => 0));
unset($_SESSION['persistent_login_check']);
unset($_SESSION['persistent_login_login']);
$_SESSION['persistent_login_reauth'] = TRUE;
unset($_REQUEST['destination']);
drupal_set_message(t('Please verify your username and password to access this page.'), 'error');
drupal_goto('user/login', drupal_get_destination());
}
}
/**
* Implementation of hook_menu().
*/
function persistent_login_menu() {
$items = array();
$items['persistent_login/erase'] = array(
'title' => 'Erase persistent logins',
'page callback' => 'persistent_login_erase',
'access callback' => 'persistent_login_erase_access',
'access arguments' => array(2),
'type' => MENU_CALLBACK,
'file' => 'persistent_login.pages.inc',
);
$items['admin/settings/persistent_login'] = array(
'title' => 'Persistent Login',
'description' => 'Control Persistent Login session lifetime and restricted pages.',
'page callback' => 'drupal_get_form',
'page arguments' => array('persistent_login_admin_settings'),
'access arguments' => array('administer Persistent Login'),
'type' => MENU_NORMAL_ITEM,
'file' => 'persistent_login.pages.inc',
);
return $items;
}
/**
* Access callback to check permission to erase user's Persistent Login records.
*/
function persistent_login_erase_access($uid = NULL) {
global $user;
if ($user->uid) {
if (empty($uid)) {
$uid = $user->uid;
}
if ($user->uid == $uid || user_access('administer Persistent Login')) {
return TRUE;
}
}
return FALSE;
}
/**
* Implementation of hook_form_alter().
*/
function persistent_login_form_alter(&$form, $form_state, $form_id) {
$alter_form = FALSE;
if (substr($form_id, 0, 10) == 'user_login') {
// This is a login form that we want to alter.
$alter_form = TRUE;
}
elseif (substr($form_id, 0, 13) == 'user_register') {
// This is a user register form, but we only want to alter this if
// - Visitors can create accounts and no administrator approval is required.
// - E-mail verification is not required when a visitor creates an account.
// - The form is not being executed by a user administrator.
if (!variable_get('user_email_verification', 1) && variable_get('user_register', 1) == 1 && !user_access('administer users')) {
$alter_form = TRUE;
}
}
if (!$alter_form) {
return;
}
// If the user is reauthenticating, then fill in the name element with the
// user name provided by persistent_login_init().
if (isset($_SESSION['persistent_login_default_user'])) {
// Make sure we still have a 'name' element on this form. Note that someone
// else could have removed it from its own hook_form_alter() implementation.
if (isset($form['name'])) {
$form['name']['#default_value'] = $_SESSION['persistent_login_default_user'];
}
unset($_SESSION['persistent_login_default_user']);
}
// Don't show Remember Me checkbox if we're reauthenticating to
// access a protected page unless I change the code to delete the PL
// session if the user does not check the box.
//
// This variable is not unset until login succeeds so if the user
// mistypes the password Remember Me will stay hidden. Since this
// can only get set within a valid PL session, there is no risk of
// it hiding Remember Me for a non-logged-in user.
//
if (!empty($_SESSION['persistent_login_reauth'])) {
return;
}
// Let's add the "Remember me" checkbox to the login/user register form.
if (isset($form['account']) && is_array($form['account'])) {
$form['account']['persistent_login'] = array(
'#type' => 'checkbox',
'#title' => t('Remember me'),
);
}
else {
$form['persistent_login'] = array(
'#type' => 'checkbox',
'#title' => t('Remember me'),
);
}
// Add an after_build callback that we'll use to adjust the weight
// and tabindex attributes of the "Remember me" checkbox.
if (!isset($form['#after_build'])) {
$form['#after_build'] = array();
}
$form['#after_build'][] = 'persistent_login_form_after_build_proxy';
}
/**
* Proxy function to call persistent_login_form_after_build(), because it might
* not be included yet when the form is processed and invokes the callback.
*/
function persistent_login_form_after_build_proxy($form, &$form_state) {
module_load_include('inc', 'persistent_login', 'persistent_login.pages');
return persistent_login_form_after_build($form, $form_state);
}
/**
* Implementation of hook_user().
*/
function persistent_login_user($op, &$edit, &$account, $category = NULL) {
global $user;
switch ($op) {
case 'login':
// If we are coming from a login form, $edit['persistent_login']
// is set if the user checked it. If we are coming from
// persistent_login_check(), $edit['persistent_login'] is also
// set along with pl_series and pl_expiration. Either way, issue a
// new PL cookie, preserving series and expiration if present.
if (!empty($edit['persistent_login'])) {
_persistent_login_create_cookie($account, $edit);
}
// Assume this is a non-PL login; clear persistent_login_login.
// If this is a PL login, it will be set again by
// _persistent_login_check (our caller).
unset($_SESSION['persistent_login_login']);
// see comment in _form_alter()
unset($_SESSION['persistent_login_reauth']);
break;
case 'logout':
$cookie_name = _persistent_login_get_cookie_name();
if (!empty($_COOKIE[$cookie_name])) {
_persistent_login_setcookie($cookie_name, '', time() - 86400);
unset($_SESSION['persistent_login_check']);
unset($_SESSION['persistent_login_login']);
unset($_SESSION['persistent_login_reauth']);
list($uid, $series, $token) = explode(':', $_COOKIE[$cookie_name]);
_persistent_login_invalidate('logout', "uid = %d AND series = '%s'", $uid, $series);
}
break;
case 'view':
if ($user->uid == $account->uid || user_access('administer Persistent Login')) {
$n = db_result(db_query('SELECT COUNT(*) FROM {persistent_login} WHERE uid = %d AND (expires = 0 OR expires > %d)', $account->uid, time()));
if ($n > 0) {
if (!isset($account->content['security'])) {
$account->content['security'] = array();
}
$account->content['security'] += array(
'#type' => 'user_profile_category',
'#title' => t('Security'),
'#weight' => 10,
);
$account->content['security']['persistent_login'] = array(
'#type' => 'user_profile_item',
'#title' => t('Remembered logins'),
'#value' => t('@acct %n persistent login session(s) created with the "Remember Me" login option on this site. If you no longer trust the computer(s) on which these remembered sessions were created or think your account has been compromised for any reason, you can !erase_link. This will not log you out of your current session but you will have to provide your username and password to log in the next time you visit this site.',
array(
'@acct' => (($user->uid == $account->uid) ? t('You have') : t('User @user has', array('@user' => $account->name))),
'%n' => $n,
'!erase_link' => l(t('erase persistent logins now'), 'persistent_login/erase/'. $account->uid, array(), drupal_get_destination()),
)
),
'#attributes' => array('class' => 'logins'),
);
}
}
break;
case 'update':
if (empty($edit['pass'])) {
break;
}
// If the password is modified, fall through to wipe all persistent logins.
case 'delete':
_persistent_login_invalidate($op, 'uid = %d', $account->uid);
unset($_SESSION['persistent_login_check']);
unset($_SESSION['persistent_login_login']);
break;
}
}
/**
* Implementation of hook_cron().
*/
function persistent_login_cron() {
_persistent_login_invalidate('cron', 'expires > 0 AND expires < %d', time());
}
/**
* _persistent_login_check(). Do the real work. Note that we may be
* in BOOTSTRAP_PAGE_CACHE mode with few modules loaded.
*
* If a non-logged in user has a valid Persistent Login cookie, log her in,
* disable the old cookie, and issue a new one for next time. Then
* reload the current page so the user is logged in from the
* beginning.
*
* If a non-logged in user has an invalid PL cookie that indicates an
* attack has occurred, panic.
*
* If a user logged in by Persistent Login tries to access a protected
* page, redirect them to the login page. Their remembered login is
* preserved, though, so they can skip the login and keep browsing
* non-protected pages.
*/
function _persistent_login_check() {
global $user;
$path = isset($_GET['q']) ? $_GET['q'] : '';
// Do not interfere with login/logout pages. Note that we're performing this
// check during hook_boot(), Drupal has not already normalized the path, so
// we need to take care of the path prefix defined for language negotiation.
$mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
if ($mode == LANGUAGE_NEGOTIATION_PATH_DEFAULT || $mode == LANGUAGE_NEGOTIATION_PATH) {
foreach (array_keys(language_list('prefix')) as $prefix) {
if (!empty($prefix) && preg_match('`^(?:'. preg_quote($prefix) .'/){0,1}(?:user/login|logout)$`', $path)) {
return;
}
}
}
elseif ($path == 'user/login' || $path == 'logout') {
return;
}
$now = time();
$cookie_name = _persistent_login_get_cookie_name();
if ($user->uid == 0 && isset($_COOKIE[$cookie_name]) && !isset($_SESSION['persistent_login_check'])) {
// For efficiency, only check once per session unless something changes.
$_SESSION['persistent_login_check'] = TRUE;
list($uid, $series, $token) = explode(':', $_COOKIE[$cookie_name]);
// Determine if the token is valid by looking for it in the db.
$res = db_query("SELECT u.name, pl.uid, pl.series as pl_series, pl.token as pl_token, pl.expires as pl_expires FROM {persistent_login} pl INNER JOIN {users} u USING (uid) WHERE u.status = 1 AND pl.uid = %d AND pl.series = '%s'", $uid, $series);
$r = db_fetch_array($res);
if (!is_array($r) || count($r) == 0) {
// $uid:$series is invalid
return;
}
else if ($r['pl_expires'] > 0 && $r['pl_expires'] < time()) {
// $uid:$series has expired
return;
}
// now, any outcome requires this
require_once './includes/common.inc';
require_once './includes/path.inc';
require_once './includes/theme.inc';
if ($r['pl_token'] === $token) {
// Delete the one-time use persistent login cookie.
_persistent_login_invalidate('used', "uid = %d AND series = '%s'", $uid, $series);
// The Persistent Login cookie is valid. $r is a 'user form'
// that contains only name, uid, pl_series, pl_token, and
// pl_expires. Add persistent_login so we and other modules can
// tell what is going on.
//
$r['persistent_login'] = 1;
// Log in the user. Use user_external_login() so all the right
// things happen. Be sure to override persistent_login_login to
// TRUE afterwards (our hook_user sets it to FALSE).
//
// user_external_login() requires user.module and
// drupal_get_form() which needs system.module... just finish booting.
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$account = user_load(array('uid' => $r['uid']));
if (!user_external_login($account, $r)) {
return;
}
$_SESSION['persistent_login_login'] = TRUE;
// Only welcome the user back once per session.
if (empty($_SESSION['persistent_login_welcomed']) && variable_get('persistent_login_welcome', TRUE)) {
drupal_set_message(t('Welcome back, %name.', array('%name' => $r['name'])));
}
$_SESSION['persistent_login_welcomed'] = TRUE;
// Reload this page as the user. If page caching is enabled,
// the user was not logged in until now and so the page may have
// come from the cache. Also, some other init hook may care.
// Also, note that we prevent redirections to front page path.
if (empty($_POST)) {
if (!isset($_REQUEST['destination']) && drupal_is_front_page()) {
drupal_goto('');
}
else {
$_REQUEST['destination'] = substr(drupal_get_destination(), 12);
drupal_goto();
}
}
// Only reached if POST data available.
return;
}
else {
// The Persistent Login cookie is NOT valid, but $uid:$series
// was right. This means two browsers are sharing the cookie,
// so someone is cheating. Panic.
// watchdog() needs a module that is not loaded yet during hook_boot(),
// and t() needs the language initialized... just finish booting.
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Reset PL state in $_SESSION.
$d = array();
_persistent_login_invalidate('stolen', 'uid = %d', $uid);
persistent_login_user('logout', $d, $user);
// Delete all open sessions for this user. Use $uid from the
// PL cookie, not $user->uid which is still 0. No need to
// regenerate the session, user will be anonymous on next visit.
sess_destroy_uid($uid);
// Log the event, warn the user.
watchdog('security', 'Stolen Persistent Login session for user %user detected.', array('%user' => $r['name']), WATCHDOG_ERROR);
drupal_set_message(t('<p><b>SECURITY ALERT!</b></p><p>You previously logged in to this site and checked the <em>Remember me</em> box. At that time, this site stored a "login cookie" on your web browser that it uses to identify you each time you return. However, the login cookie that your browser just provided is incorrect. One possible cause of this error is that your web browser cookies have been stolen and used by someone else to impersonate you at this site.</p><p>As a precaution, we logged out all of your current sessions and deactivated all your remembered logins to this site. You can log in again now.</p>'), 'error');
drupal_goto();
return;
}
}
}
/**
* Create a Persistent Login cookie.
*
* We're about to set a new PL cookie. If the user already has a PL
* but $edit['pl_series'] does not exist, they got here because they
* tried to access a protected page and had to reauthenticate
* (because $edit['pl_series'] is added by _persistent_login_check(),
* not by any login form). Clean up the old PL series to avoid junk
* in the db.
*/
function _persistent_login_create_cookie($acct, $edit = array()) {
$cookie_name = _persistent_login_get_cookie_name();
if (isset($_COOKIE[$cookie_name]) && !isset($edit['pl_series'])) {
list($uid, $series, $token) = explode(':', $_COOKIE[$cookie_name]);
_persistent_login_invalidate('cleanup', "uid = %d AND series = '%s'", $uid, $series);
}
$token = drupal_get_token(uniqid(mt_rand(), TRUE));
$days = variable_get('persistent_login_maxlife', PERSISTENT_LOGIN_MAXLIFE);
$expires = (isset($edit['pl_expires']) ? $edit['pl_expires'] : (($days > 0) ? time() + $days * 86400 : 0));
$series = (isset($edit['pl_series']) ? $edit['pl_series'] : drupal_get_token(uniqid(mt_rand(), TRUE)));
_persistent_login_setcookie($cookie_name, $acct->uid .':'. $series .':'. $token, $expires > 0 ? $expires : 2147483647);
db_query("INSERT INTO {persistent_login} (uid, series, token, expires) VALUES (%d, '%s', '%s', %d)", $acct->uid, $series, $token, $expires);
if (db_affected_rows() != 1) {
watchdog('security', 'Persistent Login FAILURE: could not insert (%user, %series, %tok, %expires)', array(
'%user' => $acct->name,
'%series' => $series,
'%tok' => $token,
'%expires' => $expires,
), WATCHDOG_ERROR);
}
else {
// Make sure we only remember the specified number of Persistent Logins per user.
$maxlogins = variable_get('persistent_login_maxlogins', 10);
$expires = (int)db_result(db_query_range('SELECT expires FROM {persistent_login} WHERE uid = %d ORDER BY expires DESC', $acct->uid, $maxlogins, 1));
if ($expires > 0) {
_persistent_login_invalidate('too many', 'uid = %d AND expires <= %d', $acct->uid, $expires);
}
}
}
/**
* Set a cookie with the same options as the session cookie.
*
* @param $name
* The name of the cookie.
* @param $value
* The value to store in the cookie.
* @param $expire
* The time the cookie expires. This is a Unix timestamp so is in number of seconds
* since the epoch. By default expires when the browser is closed.
*/
function _persistent_login_setcookie($name, $value, $expire = 0) {
$params = session_get_cookie_params();
setcookie($name, $value, $expire, $params['path'], $params['domain'], $params['secure']);
}
/**
* Get the name of the Persistent Login cookie.
*
* Include $base_path in PERSISTENT_LOGIN so a user can be logged in
* to more than one Drupal site per domain.
*/
function _persistent_login_get_cookie_name() {
static $cookie_name;
if (!isset($cookie_name)) {
// Derive the PL cookie name from the Drupal session name.
// See conf_init() in Drupal includes/bootstrap.inc.
$cookie_name = variable_get('persistent_login_cookie_prefix', 'PERSISTENT_LOGIN_') . substr(session_name(), 4);
}
return $cookie_name;
}
/**
* _persistent_login_match()
*
* check the page past and see if it should be secure or insecure.
*
* @param $path
* the path of the page to check.
*
* @return
* 0 - page should be insecure.
* 1 - page should be secure.
*/
function _persistent_login_match($path) {
$secure = variable_get('persistent_login_secure', 1);
$pages = trim(variable_get('persistent_login_pages', PERSISTENT_LOGIN_SECURE_PATHS));
if ($pages) {
$front = variable_get('site_frontpage', 'node');
$regexp = ('/^(?:'.
preg_replace(
array(
'/(\r\n?|\n)/',
'/\\\\\*/',
'/(^|\|)\\\\<front\\\\>($|\|)/',
),
array(
'|',
'.*',
'\1'. preg_quote($front, '/') .'\2',
),
preg_quote($pages, '/')
)
.')$/'
);
return !($secure xor preg_match($regexp, $path));
}
else {
return 0;
}
}
function _persistent_login_invalidate($why, $where) {
$vals = func_get_args();
array_shift($vals);
array_shift($vals);
// This is currently only for debugging but could be an audit log.
if (FALSE) {
$vals2 = $vals;
array_unshift($vals2, time(), $why);
db_query("INSERT INTO {persistent_login_history} (uid, series, token, expires, at, why) SELECT uid, series, token, expires, %d, '%s' FROM {persistent_login} WHERE ". $where, $vals2);
}
db_query('DELETE FROM {persistent_login} WHERE '. $where, $vals);
}