You are here

class BasicSetup in Two-factor Authentication (TFA) 8

TFA setup form router.

Hierarchy

Expanded class hierarchy of BasicSetup

1 string reference to 'BasicSetup'
tfa.routing.yml in ./tfa.routing.yml
tfa.routing.yml

File

src/Form/BasicSetup.php, line 26

Namespace

Drupal\tfa\Form
View source
class BasicSetup extends FormBase {
  use TfaDataTrait;
  use StringTranslationTrait;

  /**
   * The TfaSetupPluginManager.
   *
   * @var \Drupal\Component\Plugin\PluginManagerInterface
   */
  protected $manager;

  /**
   * The validation plugin manager.
   *
   * @var \Drupal\tfa\TfaValidationPluginManager
   */
  protected $tfaValidation;

  /**
   * The login plugin manager.
   *
   * @var \Drupal\tfa\TfaLoginPluginManager
   */
  protected $tfaLogin;

  /**
   * The send plugin manager.
   *
   * @var \Drupal\tfa\TfaSendPluginManager
   */
  protected $tfaSend;

  /**
   * Provides the user data service object.
   *
   * @var \Drupal\user\UserDataInterface
   */
  protected $userData;

  /**
   * The password hashing service.
   *
   * @var \Drupal\Core\Password\PasswordInterface
   */
  protected $passwordChecker;

  /**
   * The mail manager.
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected $mailManager;

  /**
   * The user storage.
   *
   * @var \Drupal\user\UserStorageInterface
   */
  protected $userStorage;

  /**
   * BasicSetup constructor.
   *
   * @param \Drupal\Component\Plugin\PluginManagerInterface $manager
   *   The plugin manager to fetch plugin information.
   * @param \Drupal\user\UserDataInterface $user_data
   *   The user data object to store user information.
   * @param \Drupal\tfa\TfaValidationPluginManager $tfa_validation_manager
   *   The validation plugin manager.
   * @param \Drupal\tfa\TfaLoginPluginManager $tfa_login_manager
   *   The login plugin manager.
   * @param \Drupal\tfa\TfaSendPluginManager $tfa_send_manager
   *   The send plugin manager.
   * @param \Drupal\Core\Password\PasswordInterface $password_checker
   *   The password service.
   * @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
   *   The mail manager.
   * @param \Drupal\user\UserStorageInterface $user_storage
   *   The user storage.
   */
  public function __construct(PluginManagerInterface $manager, UserDataInterface $user_data, TfaValidationPluginManager $tfa_validation_manager, TfaLoginPluginManager $tfa_login_manager, TfaSendPluginManager $tfa_send_manager, PasswordInterface $password_checker, MailManagerInterface $mail_manager, UserStorageInterface $user_storage) {
    $this->manager = $manager;
    $this->userData = $user_data;
    $this->tfaValidation = $tfa_validation_manager;
    $this->tfaLogin = $tfa_login_manager;
    $this->tfaSend = $tfa_send_manager;
    $this->passwordChecker = $password_checker;
    $this->mailManager = $mail_manager;
    $this->userStorage = $user_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.tfa.setup'), $container
      ->get('user.data'), $container
      ->get('plugin.manager.tfa.validation'), $container
      ->get('plugin.manager.tfa.login'), $container
      ->get('plugin.manager.tfa.send'), $container
      ->get('password'), $container
      ->get('plugin.manager.mail'), $container
      ->get('entity_type.manager')
      ->getStorage('user'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'tfa_setup';
  }

  /**
   * Find the correct plugin that is being setup.
   *
   * @param string $plugin_id
   *   Plugin ID.
   *
   * @return array|null
   *   Plugin definitions.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function findPlugin($plugin_id) {
    $plugin = $this->tfaValidation
      ->getDefinition($plugin_id, FALSE);
    if (empty($plugin)) {
      $plugin = $this->tfaLogin
        ->getDefinition($plugin_id, FALSE);
    }
    if (empty($plugin)) {
      $plugin = $this->tfaSend
        ->getDefinition($plugin_id, FALSE);
    }
    if (empty($plugin)) {
      throw new PluginNotFoundException($plugin_id, sprintf('The "%s" plugin does not exist.', $plugin_id));
    }
    return $plugin;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, User $user = NULL, $method = 'tfa_totp', $reset = 0) {

    /** @var \Drupal\user\Entity\User $account */
    $account = $this->userStorage
      ->load($this
      ->currentUser()
      ->id());
    $form['account'] = [
      '#type' => 'value',
      '#value' => $user,
    ];
    $tfa_data = $this
      ->tfaGetTfaData($user
      ->id(), $this->userData);
    $enabled = isset($tfa_data['status'], $tfa_data['data']) && !empty($tfa_data['data']['plugins']) && $tfa_data['status'];
    $storage = $form_state
      ->getStorage();

    // Always require a password on the first time through.
    if (empty($storage)) {

      // Allow administrators to change TFA settings for another account.
      if ($account
        ->id() == $user
        ->id() && $account
        ->hasPermission('administer users')) {
        $current_pass_description = $this
          ->t('Enter your current password to
        alter TFA settings for account %name.', [
          '%name' => $user
            ->getAccountName(),
        ]);
      }
      else {
        $current_pass_description = $this
          ->t('Enter your current password to continue.');
      }
      $form['current_pass'] = [
        '#type' => 'password',
        '#title' => $this
          ->t('Current password'),
        '#size' => 25,
        '#required' => TRUE,
        '#description' => $current_pass_description,
        '#attributes' => [
          'autocomplete' => 'off',
        ],
      ];
      $form['actions'] = [
        '#type' => 'actions',
      ];
      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => $this
          ->t('Confirm'),
      ];
      $form['actions']['cancel'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Cancel'),
        '#limit_validation_errors' => [],
        '#submit' => [
          '::cancelForm',
        ],
      ];
    }
    else {
      if (!$enabled && empty($storage['steps'])) {
        $storage['full_setup'] = TRUE;
        $steps = $this
          ->tfaFullSetupSteps();
        $storage['steps_left'] = $steps;
        $storage['steps_skipped'] = [];
      }
      if (isset($storage['step_method'])) {
        $method = $storage['step_method'];
      }

      // Record methods progressed.
      $storage['steps'][] = $method;
      $plugin = $this
        ->findPlugin($method);
      $setup_plugin = $this->manager
        ->createInstance($plugin['setupPluginId'], [
        'uid' => $account
          ->id(),
      ]);
      $tfa_setup = new TfaSetup($setup_plugin);
      $form = $tfa_setup
        ->getForm($form, $form_state, $reset);
      $storage[$method] = $tfa_setup;
      $form['actions']['#type'] = 'actions';
      if (isset($storage['full_setup']) && count($storage['steps']) > 1) {
        $count = count($storage['steps_left']);
        $form['actions']['skip'] = [
          '#type' => 'submit',
          '#value' => $count > 0 ? $this
            ->t('Skip') : $this
            ->t('Skip and finish'),
          '#limit_validation_errors' => [],
          '#submit' => [
            '::cancelForm',
          ],
        ];
      }
      else {
        $form['actions']['cancel'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Cancel'),
          '#limit_validation_errors' => [],
          '#submit' => [
            '::cancelForm',
          ],
        ];
      }

      // Record the method in progress regardless of whether in full setup.
      $storage['step_method'] = $method;
    }
    $form_state
      ->setStorage($storage);
    return $form;
  }

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

    /** @var \Drupal\user\Entity\User $user */
    $user = $this->userStorage
      ->load($this
      ->currentUser()
      ->id());
    $storage = $form_state
      ->getStorage();
    $values = $form_state
      ->getValues();
    $account = $form['account']['#value'];
    if (isset($values['current_pass'])) {

      // Allow administrators to change TFA settings for another account using
      // their own password.
      if ($account
        ->id() != $user
        ->id()) {
        if ($user
          ->hasPermission('administer users')) {
          $account = $user;
        }
        else {
          throw new NotFoundHttpException();
        }
      }
      $current_pass = $this->passwordChecker
        ->check(trim($form_state
        ->getValue('current_pass')), $account
        ->getPassword());
      if (!$current_pass) {
        $form_state
          ->setErrorByName('current_pass', $this
          ->t("Incorrect password."));
      }
      return;
    }
    elseif (!empty($storage['step_method'])) {
      $method = $storage['step_method'];
      $tfa_setup = $storage[$method];

      // Validate plugin form.
      if (!$tfa_setup
        ->validateForm($form, $form_state)) {
        foreach ($tfa_setup
          ->getErrorMessages() as $element => $message) {
          $form_state
            ->setErrorByName($element, $message);
        }
      }
    }
  }

  /**
   * Form cancel handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function cancelForm(array &$form, FormStateInterface $form_state) {
    $account = $form['account']['#value'];
    $this
      ->messenger()
      ->addWarning($this
      ->t('TFA setup canceled.'));
    $form_state
      ->setRedirect('tfa.overview', [
      'user' => $account
        ->id(),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $account = $form['account']['#value'];
    $storage = $form_state
      ->getStorage();
    $values = $form_state
      ->getValues();

    // Password validation.
    if (isset($values['current_pass'])) {
      $storage['pass_confirmed'] = TRUE;
      $form_state
        ->setRebuild();
      $form_state
        ->setStorage($storage);
      return;
    }
    elseif (!empty($storage['step_method'])) {
      $method = $storage['step_method'];
      $skipped_method = FALSE;

      // Support skipping optional steps when in full setup.
      if (isset($values['skip']) && $values['op'] === $values['skip']) {
        $skipped_method = $method;
        $storage['steps_skipped'][] = $method;
        unset($storage[$method]);
      }
      if (!empty($storage[$method])) {

        // Trigger multi-step if in full setup.
        if (!empty($storage['full_setup'])) {
          $this
            ->tfaNextSetupStep($form_state, $method, $storage[$method], $skipped_method);
        }

        // Plugin form submit.
        $setup_class = $storage[$method];
        if (!$setup_class
          ->submitForm($form, $form_state)) {
          $this
            ->messenger()
            ->addError($this
            ->t('There was an error during TFA setup. Your settings have not been saved.'));
          $form_state
            ->setRedirect('tfa.overview', [
            'user' => $account
              ->id(),
          ]);
          return;
        }
      }

      // Return if multi-step.
      if ($form_state
        ->getRebuildInfo()) {
        return;
      }

      // Else, setup complete and return to overview page.
      $this
        ->messenger()
        ->addStatus($this
        ->t('TFA setup complete.'));
      $form_state
        ->setRedirect('tfa.overview', [
        'user' => $account
          ->id(),
      ]);

      // Log and notify if this was full setup.
      if (!empty($storage['step_method'])) {
        $data = [
          'plugins' => $storage['step_method'],
        ];
        $this
          ->tfaSaveTfaData($account
          ->id(), $this->userData, $data);
        $this
          ->logger('tfa')
          ->info('TFA enabled for user @name UID @uid', [
          '@name' => $account
            ->getAccountName(),
          '@uid' => $account
            ->id(),
        ]);
        $params = [
          'account' => $account,
        ];
        $this->mailManager
          ->mail('tfa', 'tfa_enabled_configuration', $account
          ->getEmail(), $account
          ->getPreferredLangcode(), $params);
      }
    }
  }

  /**
   * Steps eligible for TFA setup.
   */
  private function tfaFullSetupSteps() {
    $config = $this
      ->config('tfa.settings');
    $steps = [
      $config
        ->get('default_validation_plugin'),
    ];
    $login_plugins = $config
      ->get('login_plugins');
    foreach ($login_plugins as $login_plugin) {
      $steps[] = $login_plugin;
    }

    // @todo Add send plugins.
    return $steps;
  }

  /**
   * Set form rebuild, next step, and message if any plugin steps left.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   * @param string $this_step
   *   The current setup step.
   * @param \Drupal\tfa\TfaSetup $step_class
   *   The setup instance of the current step.
   * @param bool $skipped_step
   *   Whether the step was skipped.
   */
  private function tfaNextSetupStep(FormStateInterface &$form_state, $this_step, TfaSetup $step_class, $skipped_step = FALSE) {
    $storage = $form_state
      ->getStorage();

    // Remove this step from steps left.
    $storage['steps_left'] = array_diff($storage['steps_left'], [
      $this_step,
    ]);
    if (!empty($storage['steps_left'])) {

      // Contextual reporting.
      if ($output = $step_class
        ->getSetupMessages()) {
        $output = $skipped_step ? $output['skipped'] : $output['saved'];
      }
      $count = count($storage['steps_left']);
      $output .= ' ' . $this
        ->formatPlural($count, 'One setup step remaining.', '@count TFA setup steps remain.', [
        '@count' => $count,
      ]);
      if ($output) {
        $this
          ->messenger()
          ->addStatus($output);
      }

      // Set next step and mark form for rebuild.
      $next_step = array_shift($storage['steps_left']);
      $storage['step_method'] = $next_step;
      $form_state
        ->setRebuild();
    }
    $form_state
      ->setStorage($storage);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BasicSetup::$mailManager protected property The mail manager.
BasicSetup::$manager protected property The TfaSetupPluginManager.
BasicSetup::$passwordChecker protected property The password hashing service.
BasicSetup::$tfaLogin protected property The login plugin manager.
BasicSetup::$tfaSend protected property The send plugin manager.
BasicSetup::$tfaValidation protected property The validation plugin manager.
BasicSetup::$userData protected property Provides the user data service object.
BasicSetup::$userStorage protected property The user storage.
BasicSetup::buildForm public function Form constructor. Overrides FormInterface::buildForm
BasicSetup::cancelForm public function Form cancel handler.
BasicSetup::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BasicSetup::findPlugin protected function Find the correct plugin that is being setup.
BasicSetup::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BasicSetup::submitForm public function Form submission handler. Overrides FormInterface::submitForm
BasicSetup::tfaFullSetupSteps private function Steps eligible for TFA setup.
BasicSetup::tfaNextSetupStep private function Set form rebuild, next step, and message if any plugin steps left.
BasicSetup::validateForm public function Form validation handler. Overrides FormBase::validateForm
BasicSetup::__construct public function BasicSetup constructor.
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.