You are here

class TfaRecoveryCodeSetup in Two-factor Authentication (TFA) 8

TFA Recovery Code Setup Plugin.

Plugin annotation


@TfaSetup(
  id = "tfa_recovery_code_setup",
  label = @Translation("TFA Recovery Code Setup"),
  description = @Translation("TFA Recovery Code Setup Plugin"),
  setupMessages = {
   "saved" = @Translation("Recovery codes saved."),
   "skipped" = @Translation("Recovery codes not saved.")
  }
)

Hierarchy

Expanded class hierarchy of TfaRecoveryCodeSetup

File

src/Plugin/TfaSetup/TfaRecoveryCodeSetup.php, line 24

Namespace

Drupal\tfa\Plugin\TfaSetup
View source
class TfaRecoveryCodeSetup extends TfaRecoveryCode implements TfaSetupInterface {
  use TfaDataTrait;

  /**
   * {@inheritdoc}
   */
  public function ready() {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getOverview(array $params) {
    return [
      'heading' => [
        '#type' => 'html_tag',
        '#tag' => 'h2',
        '#value' => $this
          ->t('Recovery Codes'),
      ],
      'description' => [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this
          ->t('Generate one-time use codes for two-factor login. These are generally used to recover your account in case you lose access to another 2nd-factor device.'),
      ],
      'setup' => [
        '#theme' => 'links',
        '#links' => [
          'reset' => [
            'title' => !$params['enabled'] ? $this
              ->t('Generate codes') : $this
              ->t('Reset codes'),
            'url' => Url::fromRoute('tfa.plugin.reset', [
              'user' => $params['account']
                ->id(),
              'method' => $params['plugin_id'],
              'reset' => 1,
            ]),
          ],
        ],
      ],
      'show_codes' => [
        '#theme' => 'links',
        '#access' => $params['enabled'],
        '#links' => [
          'show' => [
            'title' => $this
              ->t('Show codes'),
            'url' => Url::fromRoute('tfa.validation.setup', [
              'user' => $params['account']
                ->id(),
              'method' => $params['plugin_id'],
            ]),
          ],
        ],
      ],
    ];
  }

  /**
   * Get the setup form for the validation method.
   *
   * @param array $form
   *   The configuration form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param int $reset
   *   Whether or not the user is resetting the application.
   *
   * @return array
   *   Form API array.
   */
  public function getSetupForm(array $form, FormStateInterface $form_state, $reset = 0) {
    $codes = $this
      ->getCodes();

    // If $reset has a value, we're setting up new codes.
    if (!empty($reset)) {
      $codes = $this
        ->generateCodes();

      // Make the human friendly.
      foreach ($codes as $key => $code) {
        $codes[$key] = implode(' ', str_split($code, 3));
      }
      $form['recovery_codes'] = [
        '#type' => 'value',
        '#value' => $codes,
      ];
    }
    $form['recovery_codes_output'] = [
      '#title' => $this
        ->t('Recovery Codes'),
      '#theme' => 'item_list',
      '#items' => $codes,
    ];
    $form['description'] = [
      '#type' => 'html_tag',
      '#tag' => 'p',
      '#value' => $this
        ->t('Print or copy these codes and store them somewhere safe before continuing.'),
    ];
    if (!empty($reset)) {
      $form['actions'] = [
        '#type' => 'actions',
      ];
      $form['actions']['save'] = [
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => $this
          ->t('Save codes to account'),
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateSetupForm(array $form, FormStateInterface $form_state) {
    if (!empty($form_state
      ->getValue('recovery_codes'))) {
      return TRUE;
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function submitSetupForm(array $form, FormStateInterface $form_state) {
    $this
      ->storeCodes($form_state
      ->getValue('recovery_codes'));
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getHelpLinks() {
    return [];
  }

  /**
   * {@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::submitForm public function Submit form. 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.
TfaRandomTrait::$allowedRandomLetters protected property Letters allowed during random string generation.
TfaRandomTrait::$allowedRandomNumbers protected property Numbers allowed during random string generation.
TfaRandomTrait::randomCharacters protected function Generate random characters of the given length and allowable characters.
TfaRandomTrait::randomInteger public function Generate a random integer of the given character length.
TfaRandomTrait::randomString public function Generate a random string of the given character length.
TfaRecoveryCode::$codeLimit protected property The number of recovery codes to generate.
TfaRecoveryCode::buildConfigurationForm public function Configuration form for the recovery code plugin.
TfaRecoveryCode::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
TfaRecoveryCode::deleteCodes protected function Delete existing codes.
TfaRecoveryCode::generateCodes public function Generate an array of secure recovery codes.
TfaRecoveryCode::getCodes public function Get unused recovery codes.
TfaRecoveryCode::getForm public function Get TFA process form from plugin. Overrides TfaValidationInterface::getForm
TfaRecoveryCode::storeCodes public function Save recovery codes for current account.
TfaRecoveryCode::validate protected function Validate code. Overrides TfaBasePlugin::validate
TfaRecoveryCode::validateForm public function Validate form. Overrides TfaValidationInterface::validateForm
TfaRecoveryCode::validateRequest public function Simple validate for web services.
TfaRecoveryCode::__construct public function Constructs a new Tfa plugin object. Overrides TfaBasePlugin::__construct
TfaRecoveryCodeSetup::getHelpLinks public function Returns a list of links containing helpful information for plugin use. Overrides TfaSetupInterface::getHelpLinks
TfaRecoveryCodeSetup::getOverview public function Plugin overview page. Overrides TfaSetupInterface::getOverview
TfaRecoveryCodeSetup::getSetupForm public function Get the setup form for the validation method. Overrides TfaSetupInterface::getSetupForm
TfaRecoveryCodeSetup::getSetupMessages public function Returns a list of messages for plugin step. Overrides TfaSetupInterface::getSetupMessages
TfaRecoveryCodeSetup::ready public function Determine if the plugin can run for the current TFA context. Overrides TfaRecoveryCode::ready
TfaRecoveryCodeSetup::submitSetupForm public function Submit the setup form. Overrides TfaSetupInterface::submitSetupForm
TfaRecoveryCodeSetup::validateSetupForm public function Validate the setup data. Overrides TfaSetupInterface::validateSetupForm