You are here

persistent_login.module in Persistent Login 6

Provide a "Remember Me" checkbox in the login form.

File

persistent_login.module
View source
<?php

/**
 * @file
 * Provide a "Remember Me" checkbox in the login form.
 */
define('PERSISTENT_LOGIN_SECURE_PATHS', "user/*/*\nuser/*/address\ncart/checkout\nadmin/settings/persistent_login\n");
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;
}

/**
 * Implementation of hook_menu_alter().
 */
function persistent_login_menu_alter(&$items) {
  $items['user/password']['access callback'] = 'persistent_login_user_password_access';
  $items['user/register']['access callback'] = 'persistent_login_user_register_access';
}

/**
 * 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());

  // Remove old login invalidation history
  if (0 < ($history_days = variable_get('persistent_login_history', 0))) {
    db_query('DELETE FROM {persistent_login_history} WHERE at < %d', time() - 86400 * $history_days);
  }
}

/**
 * _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 (variable_get('persistent_login_history', 0)) {
    $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);
}

/**
 * Return the warning message to be displayed via hook_requirements() or on the
 * Persistent Login settings page as a message.
 */
function _persistent_login_get_config_warning_msg() {
  return t('Your site\'s <em>session.cookie_lifetime</em> PHP setting is %life.  When using Persistent Login, it should be 0 so that PHP sessions end when the user closes his/her browser.  You can change this setting by editing <strong>%file</strong>.', array(
    '%life' => ini_get('session.cookie_lifetime'),
    '%file' => conf_path() . '/settings.php',
  ));
}

/**
 * Disable 'Create Account' page if a user is logged in via PL and trying to
 * access a PL restricted page.
 */
function persistent_login_user_register_access() {
  return user_register_access() && empty($_SESSION['persistent_login_reauth']);
}

/**
 * Disable 'Request New Password' page if a user is logged in via PL and trying
 * to access a PL restricted page.
 */
function persistent_login_user_password_access() {
  return user_is_anonymous() && empty($_SESSION['persistent_login_reauth']);
}

Functions

Namesort descending Description
persistent_login_boot 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.
persistent_login_cron Implementation of hook_cron().
persistent_login_erase_access Access callback to check permission to erase user's Persistent Login records.
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.
persistent_login_form_alter Implementation of hook_form_alter().
persistent_login_help Implementation of hook_help().
persistent_login_init Implementation of hook_init(). Before the menu system takes control, perform a Persistent Login if appropriate.
persistent_login_menu Implementation of hook_menu().
persistent_login_menu_alter Implementation of hook_menu_alter().
persistent_login_perm Implementation of hook_perm().
persistent_login_user Implementation of hook_user().
persistent_login_user_password_access Disable 'Request New Password' page if a user is logged in via PL and trying to access a PL restricted page.
persistent_login_user_register_access Disable 'Create Account' page if a user is logged in via PL and trying to access a PL restricted page.
_persistent_login_check _persistent_login_check(). Do the real work. Note that we may be in BOOTSTRAP_PAGE_CACHE mode with few modules loaded.
_persistent_login_create_cookie Create a Persistent Login cookie.
_persistent_login_get_config_warning_msg Return the warning message to be displayed via hook_requirements() or on the Persistent Login settings page as a message.
_persistent_login_get_cookie_name Get the name of the Persistent Login cookie.
_persistent_login_invalidate
_persistent_login_match _persistent_login_match()
_persistent_login_setcookie Set a cookie with the same options as the session cookie.

Constants

Namesort descending Description
PERSISTENT_LOGIN_MAXLIFE
PERSISTENT_LOGIN_SECURE_PATHS @file Provide a "Remember Me" checkbox in the login form.