You are here

class BasicDisable in Two-factor Authentication (TFA) 8

TFA disable form router.

Hierarchy

Expanded class hierarchy of BasicDisable

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

File

src/Form/BasicDisable.php, line 19

Namespace

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

  /**
   * The plugin manager to fetch plugin information.
   *
   * @var \Drupal\Component\Plugin\PluginManagerInterface
   */
  protected $manager;

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

  /**
   * BasicDisable 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\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, PasswordInterface $password_checker, MailManagerInterface $mail_manager, UserStorageInterface $user_storage) {
    $this->manager = $manager;
    $this->userData = $user_data;
    $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.validation'), $container
      ->get('user.data'), $container
      ->get('password'), $container
      ->get('plugin.manager.mail'), $container
      ->get('entity_type.manager')
      ->getStorage('user'));
  }

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

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

    /** @var \Drupal\user\Entity\User $account */
    $account = $this->userStorage
      ->load($this
      ->currentUser()
      ->id());
    $storage = $form_state
      ->getStorage();
    $storage['account'] = $user;

    // @todo Check require permissions and give warning about being locked out.
    if ($account
      ->id() != $user
      ->id() && $account
      ->hasPermission('administer users')) {
      $preamble_desc = $this
        ->t('Are you sure you want to disable TFA for user %name?', [
        '%name' => $user
          ->getDisplayName(),
      ]);
      $notice_desc = $this
        ->t('TFA settings and data will be lost. %name can re-enable TFA again from their profile.', [
        '%name' => $user
          ->getDisplayName(),
      ]);
    }
    else {
      $preamble_desc = $this
        ->t('Are you sure you want to disable your two-factor authentication setup?');
      $notice_desc = $this
        ->t("Your settings and data will be lost. You can re-enable two-factor authentication again from your profile.");
    }
    $form['preamble'] = [
      '#prefix' => '<p class="preamble">',
      '#suffix' => '</p>',
      '#markup' => $preamble_desc,
    ];
    $form['notice'] = [
      '#prefix' => '<p class="preamble">',
      '#suffix' => '</p>',
      '#markup' => $notice_desc,
    ];
    $form['account']['current_pass'] = [
      '#type' => 'password',
      '#title' => $this
        ->t('Confirm your current password'),
      '#description_display' => 'before',
      '#size' => 25,
      '#weight' => -5,
      '#attributes' => [
        'autocomplete' => 'off',
      ],
      '#required' => TRUE,
    ];
    $form['account']['mail'] = [
      '#type' => 'value',
      '#value' => $user
        ->getEmail(),
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this
        ->t('Disable'),
    ];
    $form['actions']['cancel'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Cancel'),
      '#limit_validation_errors' => [],
      '#submit' => [
        '::cancelForm',
      ],
    ];
    $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();
    $account = $storage['account'];

    // Allow administrators to disable TFA for another account.
    if ($account
      ->id() != $user
      ->id() && $user
      ->hasPermission('administer users')) {
      $account = $user;
    }

    // Check password.
    $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."));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $storage = $form_state
      ->getStorage();
    $values = $form_state
      ->getValues();
    $account = $storage['account'];
    if ($values['op'] === $values['cancel']) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('TFA disable cancelled.'));
      $form_state
        ->setRedirect('tfa.overview', [
        'user' => $account
          ->id(),
      ]);
      return;
    }

    // Delete all user data.
    $this
      ->deleteUserData('tfa', NULL, $account
      ->id(), $this->userData);
    $this
      ->logger('tfa')
      ->notice('TFA disabled for user @name UID @uid', [
      '@name' => $account
        ->getAccountName(),
      '@uid' => $account
        ->id(),
    ]);

    // E-mail account to inform user that it has been disabled.
    $params = [
      'account' => $account,
    ];
    $this->mailManager
      ->mail('tfa', 'tfa_disabled_configuration', $account
      ->getEmail(), $account
      ->getPreferredLangcode(), $params);
    $this
      ->messenger()
      ->addStatus($this
      ->t('TFA has been disabled.'));
    $form_state
      ->setRedirect('tfa.overview', [
      'user' => $account
        ->id(),
    ]);
  }

  /**
   * 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) {
    $this
      ->messenger()
      ->addWarning($this
      ->t('TFA Disable cancelled.'));
    $form_state
      ->setRedirect('tfa.overview', [
      'user' => $this
        ->currentUser()
        ->id(),
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BasicDisable::$mailManager protected property The mail manager.
BasicDisable::$manager protected property The plugin manager to fetch plugin information.
BasicDisable::$passwordChecker protected property The password hashing service.
BasicDisable::$userData protected property Provides the user data service object.
BasicDisable::$userStorage protected property The user storage.
BasicDisable::buildForm public function Form constructor. Overrides FormInterface::buildForm
BasicDisable::cancelForm public function Form cancel handler.
BasicDisable::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BasicDisable::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BasicDisable::submitForm public function Form submission handler. Overrides FormInterface::submitForm
BasicDisable::validateForm public function Form validation handler. Overrides FormBase::validateForm
BasicDisable::__construct public function BasicDisable 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.