You are here

class BasicOverview in Two-factor Authentication (TFA) 8

TFA Basic account setup overview page.

Hierarchy

Expanded class hierarchy of BasicOverview

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

File

src/Form/BasicOverview.php, line 21

Namespace

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

  /**
   * The setup plugin manager to fetch setup information.
   *
   * @var \Drupal\tfa\TfaLoginPluginManager
   */
  protected $tfaSetup;

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

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

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

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

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * BasicOverview constructor.
   *
   * @param \Drupal\user\UserDataInterface $user_data
   *   The user data service.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   * @param \Drupal\tfa\TfaSetupPluginManager $tfa_setup_manager
   *   The setup plugin manager.
   * @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.
   */
  public function __construct(UserDataInterface $user_data, DateFormatterInterface $date_formatter, TfaSetupPluginManager $tfa_setup_manager, TfaValidationPluginManager $tfa_validation_manager, TfaLoginPluginManager $tfa_login_manager, TfaSendPluginManager $tfa_send_manager) {
    $this->userData = $user_data;
    $this->dateFormatter = $date_formatter;
    $this->tfaSetup = $tfa_setup_manager;
    $this->tfaValidation = $tfa_validation_manager;
    $this->tfaLogin = $tfa_login_manager;
    $this->tfaSend = $tfa_send_manager;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {
    $output['info'] = [
      '#type' => 'markup',
      '#markup' => '<p>' . $this
        ->t('Two-factor authentication (TFA) provides
      additional security for your account. With TFA enabled, you log in to
      the site with a verification code in addition to your username and
      password.') . '</p>',
    ];

    // $form_state['storage']['account'] = $user;.
    $configuration = $this
      ->config('tfa.settings')
      ->getRawData();
    $user_tfa = $this
      ->tfaGetTfaData($user
      ->id(), $this->userData);
    $enabled = isset($user_tfa['status']) && $user_tfa['status'];
    if (!empty($user_tfa)) {
      if ($enabled && !empty($user_tfa['data']['plugins'])) {
        if ($this
          ->currentUser()
          ->hasPermission('disable own tfa')) {
          $status_text = $this
            ->t('Status: <strong>TFA enabled</strong>, set
          @time. <a href=":url">Disable TFA</a>', [
            '@time' => $this->dateFormatter
              ->format($user_tfa['saved']),
            ':url' => Url::fromRoute('tfa.disable', [
              'user' => $user
                ->id(),
            ])
              ->toString(),
          ]);
        }
        else {
          $status_text = $this
            ->t('Status: <strong>TFA enabled</strong>, set @time.', [
            '@time' => $this->dateFormatter
              ->format($user_tfa['saved']),
          ]);
        }
      }
      else {
        $status_text = $this
          ->t('Status: <strong>TFA disabled</strong>, set @time.', [
          '@time' => $this->dateFormatter
            ->format($user_tfa['saved']),
        ]);
      }
      $output['status'] = [
        '#type' => 'markup',
        '#markup' => '<p>' . $status_text . '</p>',
      ];
    }
    if ($configuration['enabled']) {
      $enabled = isset($user_tfa['status'], $user_tfa['data']) && !empty($user_tfa['data']['plugins']) && $user_tfa['status'];
      $enabled_plugins = isset($user_tfa['data']['plugins']) ? $user_tfa['data']['plugins'] : [];
      $validation_plugins = $this->tfaValidation
        ->getDefinitions();
      foreach ($validation_plugins as $plugin_id => $plugin) {
        if (!empty($configuration['allowed_validation_plugins'][$plugin_id])) {
          $output[$plugin_id] = $this
            ->tfaPluginSetupFormOverview($plugin, $user, !empty($enabled_plugins[$plugin_id]));
        }
      }
      if ($enabled) {
        $login_plugins = $this->tfaLogin
          ->getDefinitions();
        foreach ($login_plugins as $plugin_id => $plugin) {
          if (!empty($configuration['login_plugins'][$plugin_id])) {
            $output[$plugin_id] = $this
              ->tfaPluginSetupFormOverview($plugin, $user, TRUE);
          }
        }
        $send_plugins = $this->tfaSend
          ->getDefinitions();
        foreach ($send_plugins as $plugin_id => $plugin) {
          if (!empty($configuration['send_plugins'][$plugin_id])) {
            $output[$plugin_id] = $this
              ->tfaPluginSetupFormOverview($plugin, $user, TRUE);
          }
        }
      }
    }
    else {
      $output['disabled'] = [
        '#type' => 'markup',
        '#markup' => '<b>Currently there are no enabled plugins.</b>',
      ];
    }
    if ($configuration['enabled']) {
      $output['validation_skip_status'] = [
        '#type' => 'markup',
        '#markup' => $this
          ->t('Number of times validation skipped: @skipped of @limit', [
          '@skipped' => isset($user_tfa['validation_skipped']) ? $user_tfa['validation_skipped'] : 0,
          '@limit' => $configuration['validation_skip'],
        ]),
      ];
    }
    if ($this
      ->canPerformReset($user)) {
      $output['actions'] = [
        '#type' => 'actions',
      ];
      $output['actions']['reset_skip_attempts'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Reset skip validation attempts'),
        '#submit' => [
          '::resetSkipValidationAttempts',
        ],
      ];
      $output['account'] = [
        '#type' => 'value',
        '#value' => $user,
      ];
    }
    return $output;
  }

  /**
   * Get TFA basic setup action links for use on overview page.
   *
   * @param array $plugin
   *   Plugin definition.
   * @param object $account
   *   Current user account.
   * @param bool $enabled
   *   Tfa data for current user.
   *
   * @return array
   *   Render array
   */
  protected function tfaPluginSetupFormOverview(array $plugin, $account, $enabled) {
    $params = [
      'enabled' => $enabled,
      'account' => $account,
      'plugin_id' => $plugin['id'],
    ];
    try {
      return $this->tfaSetup
        ->createInstance($plugin['setupPluginId'], [
        'uid' => $account
          ->id(),
      ])
        ->getOverview($params);
    } catch (\Exception $e) {
      return [];
    }
  }

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

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

  /**
   * Resets TFA attempts for the given user account.
   *
   * @param array $form
   *   The form definition.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function resetSkipValidationAttempts(array $form, FormStateInterface $form_state) {
    $account = $form_state
      ->getValue('account');
    $tfa_data = $this
      ->tfaGetTfaData($account
      ->id(), $this->userData);
    $tfa_data['validation_skipped'] = 0;
    $this
      ->tfaSaveTfaData($account
      ->id(), $this->userData, $tfa_data);
    $this
      ->messenger()
      ->addMessage($this
      ->t('Validation attempts have been reset for user @name.', [
      '@name' => $account
        ->getDisplayName(),
    ]));
    $this
      ->logger('tfa')
      ->notice('Validation attempts reset for @account by @current_user.', [
      '@account' => $account
        ->getAccountName(),
      '@current_user' => $this
        ->currentUser()
        ->getAccountName(),
    ]);
  }

  /**
   * Determine if the current user can perform a TFA attempt reset.
   *
   * @param \Drupal\user\UserInterface $account
   *   The account that TFA is for.
   *
   * @return bool
   *   Whether the user can perform a TFA reset.
   */
  protected function canPerformReset(UserInterface $account) {
    $current_user = $this
      ->currentUser();
    return $current_user
      ->hasPermission('administer users') && $current_user
      ->id() != $account
      ->id();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BasicOverview::$dateFormatter protected property The date formatter service.
BasicOverview::$tfaLogin protected property Login plugin manager.
BasicOverview::$tfaSend protected property Send plugin manager.
BasicOverview::$tfaSetup protected property The setup plugin manager to fetch setup information.
BasicOverview::$tfaValidation protected property Validation plugin manager.
BasicOverview::$userData protected property Provides the user data service object.
BasicOverview::buildForm public function Form constructor. Overrides FormInterface::buildForm
BasicOverview::canPerformReset protected function Determine if the current user can perform a TFA attempt reset.
BasicOverview::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BasicOverview::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BasicOverview::resetSkipValidationAttempts public function Resets TFA attempts for the given user account.
BasicOverview::submitForm public function Form submission handler. Overrides FormInterface::submitForm
BasicOverview::tfaPluginSetupFormOverview protected function Get TFA basic setup action links for use on overview page.
BasicOverview::validateForm public function Form validation handler. Overrides FormBase::validateForm
BasicOverview::__construct public function BasicOverview 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.