You are here

class TfaTrustedBrowserSetup in Two-factor Authentication (TFA) 8

TFA Trusted Browser Setup Plugin.

Plugin annotation


@TfaSetup(
  id = "tfa_trusted_browser_setup",
  label = @Translation("TFA Trusted Browser Setup"),
  description = @Translation("TFA Trusted Browser Setup Plugin"),
  setupMessages = {
   "saved" = @Translation("Browser saved."),
   "skipped" = @Translation("Browser not saved.")
  }
)

Hierarchy

Expanded class hierarchy of TfaTrustedBrowserSetup

File

src/Plugin/TfaSetup/TfaTrustedBrowserSetup.php, line 25

Namespace

Drupal\tfa\Plugin\TfaSetup
View source
class TfaTrustedBrowserSetup extends TfaTrustedBrowser implements TfaSetupInterface {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function getSetupForm(array $form, FormStateInterface $form_state) {
    $existing = $this
      ->getTrustedBrowsers();
    $time = $this->expiration / 86400;
    $form['info'] = [
      '#type' => 'markup',
      '#markup' => '<p>' . $this
        ->t("Trusted browsers are a method for\n      simplifying login by avoiding verification code entry for a set amount of\n      time, @time days from marking a browser as trusted. After @time days, to\n      log in you'll need to enter a verification code with your username and\n      password during which you can again mark the browser as trusted.", [
        '@time' => $time,
      ]) . '</p>',
    ];

    // Present option to trust this browser if its not currently trusted.
    if (isset($_COOKIE[$this->cookieName]) && $this
      ->trustedBrowser($_COOKIE[$this->cookieName]) !== FALSE) {
      $current_trusted = $_COOKIE[$this->cookieName];
    }
    else {
      $current_trusted = FALSE;
      $form['trust'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Trust this browser?'),
        '#default_value' => empty($existing) ? 1 : 0,
      ];

      // Optional field to name this browser.
      $form['name'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Name this browser'),
        '#maxlength' => 255,
        '#description' => $this
          ->t('Optionally, name the browser on your browser (e.g.
        "home firefox" or "office desktop windows"). Your current browser user
        agent is %browser', [
          '%browser' => $_SERVER['HTTP_USER_AGENT'],
        ]),
        '#default_value' => $this
          ->getAgent(),
        '#states' => [
          'visible' => [
            ':input[name="trust"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
    }
    if (!empty($existing)) {
      $form['existing'] = [
        '#type' => 'fieldset',
        '#title' => $this
          ->t('Existing browsers'),
        '#description' => $this
          ->t('Leave checked to keep these browsers in your trusted log in list.'),
        '#tree' => TRUE,
      ];
      foreach ($existing as $browser_id => $browser) {
        $date_formatter = \Drupal::service('date.formatter');
        $vars = [
          '@set' => $date_formatter
            ->format($browser['created']),
        ];
        if (isset($browser['last_used'])) {
          $vars['@time'] = $date_formatter
            ->format($browser['last_used']);
        }
        if ($current_trusted == $browser_id) {
          $name = '<strong>' . $this
            ->t('@name (current browser)', [
            '@name' => $browser['name'],
          ]) . '</strong>';
        }
        else {
          $name = Html::escape($browser['name']);
        }
        if (empty($browser['last_used'])) {
          $message = $this
            ->t('Marked trusted @set', $vars);
        }
        else {
          $message = $this
            ->t('Marked trusted @set, last used for log in @time', $vars);
        }
        $form['existing']['trusted_browser_' . $browser_id] = [
          '#type' => 'checkbox',
          '#title' => $name,
          '#description' => $message,
          '#default_value' => 1,
        ];
      }
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['save'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this
        ->t('Save'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateSetupForm(array $form, FormStateInterface $form_state) {

    // Do nothing, no validation required.
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function submitSetupForm(array $form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    if (isset($values['existing'])) {
      $count = 0;
      foreach ($values['existing'] as $element => $value) {
        $id = str_replace('trusted_browser_', '', $element);
        if (!$value) {
          $this
            ->deleteTrusted($id);
          $count++;
        }
      }
      if ($count) {
        \Drupal::logger('tfa')
          ->notice('Removed @num TFA trusted browsers during trusted browser setup', [
          '@num' => $count,
        ]);
      }
    }
    if (!empty($values['trust']) && $values['trust']) {
      $name = '';
      if (!empty($values['name'])) {
        $name = $values['name'];
      }
      elseif (isset($_SERVER['HTTP_USER_AGENT'])) {
        $name = $this
          ->getAgent();
      }
      $this
        ->setTrusted($this
        ->generateBrowserId(), $name);
    }
    return TRUE;
  }

  /**
   * Get list of trusted browsers.
   *
   * @return array
   *   List of current trusted browsers.
   */
  public function getTrustedBrowsers() {
    return $this
      ->getUserData('tfa', 'tfa_trusted_browser', $this->uid, $this->userData) ?: [];
  }

  /**
   * Delete a trusted browser by its ID.
   *
   * @param int $id
   *   ID of the browser to delete.
   *
   * @return bool
   *   TRUE if successful otherwise FALSE.
   */
  public function deleteTrustedId($id) {
    return $this
      ->deleteTrusted($id);
  }

  /**
   * Delete all trusted browsers.
   *
   * @return bool
   *   TRUE if successful otherwise FALSE.
   */
  public function deleteTrustedBrowsers() {
    return $this
      ->deleteTrusted();
  }

  /**
   * {@inheritdoc}
   */
  public function getOverview(array $params) {
    $trusted_browsers = [];
    foreach ($this
      ->getTrustedBrowsers() as $device) {
      $date_formatter = \Drupal::service('date.formatter');
      $vars = [
        '@set' => $date_formatter
          ->format($device['created']),
        '@browser' => $device['name'],
      ];
      if (empty($device['last_used'])) {
        $message = $this
          ->t('@browser, set @set', $vars);
      }
      else {
        $vars['@time'] = $date_formatter
          ->format($device['last_used']);
        $message = $this
          ->t('@browser, set @set, last used @time', $vars);
      }
      $trusted_browsers[] = $message;
    }
    $output = [
      'heading' => [
        '#type' => 'html_tag',
        '#tag' => 'h3',
        '#value' => $this
          ->t('Trusted browsers'),
      ],
      'description' => [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this
          ->t('Browsers that will not require a verification code during login.'),
      ],
    ];
    if (!empty($trusted_browsers)) {
      $output['list'] = [
        '#theme' => 'item_list',
        '#items' => $trusted_browsers,
        '#title' => $this
          ->t('Browsers that will not require a verification code during login.'),
      ];
    }
    $output['link'] = [
      '#theme' => 'links',
      '#links' => [
        'admin' => [
          'title' => 'Configure Trusted Browsers',
          'url' => Url::fromRoute('tfa.validation.setup', [
            'user' => $params['account']
              ->id(),
            'method' => $params['plugin_id'],
          ]),
        ],
      ],
    ];
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function getHelpLinks() {
    return $this->pluginDefinition['helpLinks'] ?: '';
  }

  /**
   * {@inheritdoc}
   */
  public function getSetupMessages() {
    return $this->pluginDefinition['setupMessages'] ?: '';
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TfaBasePlugin::$alreadyAccepted protected property Whether the code has been used before.
TfaBasePlugin::$code protected property The user submitted code to be validated.
TfaBasePlugin::$codeLength protected property The allowed code length.
TfaBasePlugin::$encryptionProfile protected property Encryption profile.
TfaBasePlugin::$encryptService protected property Encryption service.
TfaBasePlugin::$errorMessages protected property The error for the current validation.
TfaBasePlugin::$isValid protected property Whether the validation succeeded or not.
TfaBasePlugin::$uid protected property The user id.
TfaBasePlugin::$userData protected property Provides the user data service object.
TfaBasePlugin::alreadyAcceptedCode protected function Whether code has already been used.
TfaBasePlugin::decrypt protected function Decrypt a encrypted string.
TfaBasePlugin::encrypt protected function Encrypt a plaintext string.
TfaBasePlugin::getErrorMessages public function Get error messages suitable for form_set_error().
TfaBasePlugin::getLabel public function Get the plugin label.
TfaBasePlugin::storeAcceptedCode protected function Store validated code to prevent replay attack.
TfaBasePlugin::validate protected function Validate code. 1
TfaDataTrait::deleteUserData protected function Deletes data stored for the current validated user account.
TfaDataTrait::getUserData protected function Returns data stored for the current validated user account.
TfaDataTrait::setUserData protected function Store user specific information.
TfaDataTrait::tfaGetTfaData protected function Get TFA data for an account.
TfaDataTrait::tfaSaveTfaData public function Save TFA data for an account.
TfaTrustedBrowser::$cookieName protected property The cookie name.
TfaTrustedBrowser::$expiration protected property Cookie expiration time.
TfaTrustedBrowser::$trustBrowser protected property Trust browser.
TfaTrustedBrowser::deleteTrusted protected function Delete users trusted browser.
TfaTrustedBrowser::finalize public function Finalize the browser setup.
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 Get TFA process form from plugin. Overrides TfaValidationInterface::getForm
TfaTrustedBrowser::loginAllowed public function Whether login is allowed. Overrides TfaLoginInterface::loginAllowed
TfaTrustedBrowser::ready public function Determine if the plugin can run for the current TFA context. Overrides TfaBasePlugin::ready
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 Submit form. Overrides TfaBasePlugin::submitForm
TfaTrustedBrowser::trustedBrowser protected function Check if browser id matches user's saved browser.
TfaTrustedBrowser::validateForm public function Validate form. Overrides TfaValidationInterface::validateForm
TfaTrustedBrowser::__construct public function Constructs a new Tfa plugin object. Overrides TfaBasePlugin::__construct
TfaTrustedBrowserSetup::deleteTrustedBrowsers public function Delete all trusted browsers.
TfaTrustedBrowserSetup::deleteTrustedId public function Delete a trusted browser by its ID.
TfaTrustedBrowserSetup::getHelpLinks public function Returns a list of links containing helpful information for plugin use. Overrides TfaSetupInterface::getHelpLinks
TfaTrustedBrowserSetup::getOverview public function Plugin overview page. Overrides TfaSetupInterface::getOverview
TfaTrustedBrowserSetup::getSetupForm public function Get the setup form for the validation method. Overrides TfaSetupInterface::getSetupForm
TfaTrustedBrowserSetup::getSetupMessages public function Returns a list of messages for plugin step. Overrides TfaSetupInterface::getSetupMessages
TfaTrustedBrowserSetup::getTrustedBrowsers public function Get list of trusted browsers.
TfaTrustedBrowserSetup::submitSetupForm public function Submit the setup form. Overrides TfaSetupInterface::submitSetupForm
TfaTrustedBrowserSetup::validateSetupForm public function Validate the setup data. Overrides TfaSetupInterface::validateSetupForm