You are here

class TfaTrustedBrowser in TFA Basic plugins 7

Class TfaTrustedBrowser

Hierarchy

Expanded class hierarchy of TfaTrustedBrowser

1 string reference to 'TfaTrustedBrowser'
tfa_basic_tfa_api in ./tfa_basic.module
Implements hook_tfa_api().

File

includes/tfa_trusted_browser.inc, line 10
classes for TFA basic plugin

View source
class TfaTrustedBrowser extends TfaBasePlugin implements TfaLoginPluginInterface {

  /**
   * @var bool
   */
  protected $trustBrowser;

  /**
   * @var string
   */
  protected $cookieName;

  /**
   * @var string
   */
  protected $domain;

  /**
   * @var string
   */
  protected $expiration;
  public function __construct(array $context) {
    parent::__construct($context);
    $this->cookieName = variable_get('tfa_basic_cookie_name', 'TB');
    $this->domain = variable_get('tfa_basic_cookie_domain', '');

    // Expiration defaults to 30 days.
    $this->expiration = variable_get('tfa_basic_trust_cookie_expiration', 3600 * 24 * 30);
  }

  /**
   * @return bool
   */
  public function loginAllowed() {
    if (isset($_COOKIE[$this->cookieName]) && ($did = $this
      ->trustedBrowser($_COOKIE[$this->cookieName])) !== FALSE) {
      $this
        ->setUsed($did);
      return TRUE;
    }
    return FALSE;
  }

  /**
   * @copydoc TfaValidationPluginInterface::getForm()
   */
  public function getForm(array $form, array &$form_state) {
    $form['trust_browser'] = array(
      '#type' => 'checkbox',
      '#title' => t('Remember this browser for @interval?', array(
        '@interval' => format_interval($this->expiration),
      )),
      '#description' => t('Not recommended if you are on a public or shared computer.'),
    );
    return $form;
  }

  /**
   * @copydoc TfaBasePlugin::submitForm()
   */
  public function submitForm(array $form, array &$form_state) {
    if (isset($form_state['values']['trust_browser']) && $form_state['values']['trust_browser']) {
      $this->trustBrowser = TRUE;
    }
    else {
      $this->trustBrowser = FALSE;
    }
  }

  /**
   *
   */
  public function finalize() {
    if ($this->trustBrowser) {
      $name = $this
        ->getAgent();
      $this
        ->setTrusted($this
        ->generateBrowserId(), $name);
    }
  }

  /**
   * Generate a random value to identify the browser.
   *
   * @return string
   */
  protected function generateBrowserId() {
    $id = base64_encode(drupal_random_bytes(32));
    return strtr($id, array(
      '+' => '-',
      '/' => '_',
      '=' => '',
    ));
  }

  /**
   * Store browser value and issue cookie for user.
   *
   * @param string $value
   * @param string $name
   */
  protected function setTrusted($value, $name = '') {

    // Store id for account.
    $record = array(
      'uid' => $this->context['uid'],
      'value' => $value,
      'created' => REQUEST_TIME,
      'ip' => ip_address(),
      'name' => $name,
    );
    drupal_write_record('tfa_trusted_browser', $record);

    // Issue cookie with ID.
    $cookie_secure = ini_get('session.cookie_secure');
    $expiration = REQUEST_TIME + $this->expiration;
    setcookie($this->cookieName, $value, $expiration, '/', $this->domain, empty($cookie_secure) ? FALSE : TRUE, TRUE);
    $name = empty($name) ? $this
      ->getAgent() : $name;
    watchdog('tfa_basic', 'Set trusted browser for user UID !uid, browser @name', array(
      '@name' => $name,
      '!uid' => $this->context['uid'],
    ), WATCHDOG_INFO);
  }

  /**
   * Updated browser last used time.
   *
   * @param int $did
   *   Internal browser ID to update.
   */
  protected function setUsed($did) {
    $record = array(
      'did' => $did,
      'last_used' => REQUEST_TIME,
    );
    drupal_write_record('tfa_trusted_browser', $record, 'did');
  }

  /**
   * Check if browser value matches user's saved browser.
   *
   * @param string $value
   * @return int|FALSE
   *   Browser ID if trusted or else FALSE.
   */
  protected function trustedBrowser($value) {

    // Check if $id has been saved for this user.
    $result = db_query("SELECT did FROM {tfa_trusted_browser} WHERE value = :value AND uid = :uid", array(
      ':value' => $value,
      ':uid' => $this->context['uid'],
    ))
      ->fetchAssoc();
    if (!empty($result)) {
      return $result['did'];
    }
    return FALSE;
  }

  /**
   * Delete users trusted browsers.
   *
   * @param int $did
   *   Optional trusted browser id to delete.
   *
   * @return int
   */
  protected function deleteTrusted($did = NULL) {
    $query = db_delete('tfa_trusted_browser')
      ->condition('uid', $this->context['uid']);
    if (is_int($did)) {
      $query
        ->condition('did', $did);
    }
    return $query
      ->execute();
  }

  /**
   * Get simplified browser name from user agent.
   *
   * @param string $name Default name.
   *
   * @return string
   */
  protected function getAgent($name = '') {
    if (isset($_SERVER['HTTP_USER_AGENT'])) {

      // Match popular user agents.
      $agent = $_SERVER['HTTP_USER_AGENT'];
      if (preg_match("/like\\sGecko\\)\\sChrome\\//", $agent)) {
        $name = 'Chrome';
      }
      elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== FALSE) {
        $name = 'Firefox';
      }
      elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
        $name = 'Internet Explorer';
      }
      elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== FALSE) {
        $name = 'Safari';
      }
      else {

        // Otherwise filter agent and truncate to column size.
        $name = substr($agent, 0, 255);
      }
    }
    return $name;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
TfaBasePlugin::$code protected property TFA code.
TfaBasePlugin::$codeLength protected property Code Length.
TfaBasePlugin::$context protected property Context of current TFA process.
TfaBasePlugin::$encryptionKey protected property Encryption key.
TfaBasePlugin::$errorMessages protected property Error messages.
TfaBasePlugin::$isValid protected property Code is valid.
TfaBasePlugin::CRYPT_VERSION constant
TfaBasePlugin::decrypt protected function Decrypt a encrypted string.
TfaBasePlugin::decryptLegacyDataWithMcrypt protected function Decrypt using the deprecated Mcrypt extension.
TfaBasePlugin::decryptLegacyDataWithOpenSSL protected function Use OpenSSL to decrypt data that was originally encrypted with Mcrypt.
TfaBasePlugin::encrypt protected function Encrypt a plaintext string.
TfaBasePlugin::encryptWithMcrypt protected function Encrypt using the deprecated Mcrypt extension.
TfaBasePlugin::generate protected function Generate a random string of characters of length $this->codeLength.
TfaBasePlugin::getErrorMessages public function Get error messages suitable for form_set_error().
TfaBasePlugin::ready public function Determine if the plugin can run for the current TFA context. 2
TfaBasePlugin::timingSafeEquals private function A timing safe equals comparison.
TfaBasePlugin::validate protected function Validate code.
TfaTrustedBrowser::$cookieName protected property
TfaTrustedBrowser::$domain protected property
TfaTrustedBrowser::$expiration protected property
TfaTrustedBrowser::$trustBrowser protected property
TfaTrustedBrowser::deleteTrusted protected function Delete users trusted browsers.
TfaTrustedBrowser::finalize public function
TfaTrustedBrowser::generateBrowserId protected function Generate a random value to identify the browser.
TfaTrustedBrowser::getAgent protected function Get simplified browser name from user agent.
TfaTrustedBrowser::getForm public function @copydoc TfaValidationPluginInterface::getForm()
TfaTrustedBrowser::loginAllowed public function Overrides TfaLoginPluginInterface::loginAllowed
TfaTrustedBrowser::setTrusted protected function Store browser value and issue cookie for user.
TfaTrustedBrowser::setUsed protected function Updated browser last used time.
TfaTrustedBrowser::submitForm public function @copydoc TfaBasePlugin::submitForm() Overrides TfaBasePlugin::submitForm
TfaTrustedBrowser::trustedBrowser protected function Check if browser value matches user's saved browser.
TfaTrustedBrowser::__construct public function Plugin constructor. Overrides TfaBasePlugin::__construct 1