You are here

class ChangePasswordForm in Password Separate Form 8

Provides a user password reset form.

Hierarchy

Expanded class hierarchy of ChangePasswordForm

1 string reference to 'ChangePasswordForm'
change_pwd_page.routing.yml in ./change_pwd_page.routing.yml
change_pwd_page.routing.yml

File

src/Form/ChangePasswordForm.php, line 16

Namespace

Drupal\change_pwd_page\Form
View source
class ChangePasswordForm extends FormBase {

  /**
   * The Password Hasher.
   *
   * @var \Drupal\Core\Password\PasswordInterface
   */
  protected $passwordHasher;

  /**
   * The user.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $userProfile;

  /**
   * Constructs a UserPasswordForm object.
   *
   * @param \Drupal\Core\Password\PasswordInterface $password_hasher
   *   The password service.
   */
  public function __construct(PasswordInterface $password_hasher) {
    $this->passwordHasher = $password_hasher;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('password'));
  }

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

  /**
   * {@inheritdoc}
   *
   * @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.
   * @param \Drupal\user\UserInterface $user
   *   The user object.
   */
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {

    /** @var \Drupal\user\UserInterface $account */
    $this->userProfile = $account = $user;
    $user = $this
      ->currentUser();
    $config = \Drupal::config('user.settings');
    $form['#cache']['tags'] = $config
      ->getCacheTags();
    $register = $account
      ->isAnonymous();

    // Account information.
    $form['account'] = [
      '#type' => 'container',
      '#weight' => -10,
    ];

    // Display password field only for existing users or when user is allowed to
    // assign a password during registration.
    if (!$register) {
      $form['account']['pass'] = [
        '#type' => 'password_confirm',
        '#size' => 25,
        '#description' => $this
          ->t('To change the current user password, enter the new password in both fields.'),
        '#required' => TRUE,
      ];

      // To skip the current password field, the user must have logged in via a
      // one-time link and have the token in the URL. Store this in $form_state
      // so it persists even on subsequent Ajax requests.
      if (!$form_state
        ->get('user_pass_reset') && ($token = $this
        ->getRequest()
        ->get('pass-reset-token'))) {
        $session_key = 'pass_reset_' . $account
          ->id();
        $user_pass_reset = isset($_SESSION[$session_key]) && hash_equals($_SESSION[$session_key], $token);
        $form_state
          ->set('user_pass_reset', $user_pass_reset);
      }

      // The user must enter their current password to change to a new one.
      if ($user
        ->id() == $account
        ->id()) {
        $form['account']['current_pass'] = [
          '#type' => 'password',
          '#title' => $this
            ->t('Current password'),
          '#size' => 25,
          '#access' => !$form_state
            ->get('user_pass_reset'),
          '#weight' => -5,
          // Do not let web browsers remember this password, since we are
          // trying to confirm that the person submitting the form actually
          // knows the current one.
          '#attributes' => [
            'autocomplete' => 'off',
          ],
          '#required' => TRUE,
        ];
        $form_state
          ->set('user', $account);

        // The user may only change their own password without their current
        // password if they logged in via a one-time login link.
        if (!$form_state
          ->get('user_pass_reset')) {
          $form['account']['current_pass']['#description'] = $this
            ->t('Required if you want to change the %pass below. <a href=":request_new_url" title="Send password reset instructions via email.">Reset your password</a>.', [
            '%pass' => $this
              ->t('Password'),
            ':request_new_url' => Url::fromRoute('user.pass')
              ->toString(),
          ]);
        }
      }

      // This should never show. The data is needed by other modules.
      $roles = array_map([
        '\\Drupal\\Component\\Utility\\Html',
        'escape',
      ], user_role_names(TRUE));
      $form['account']['roles'] = [
        '#type' => 'checkboxes',
        '#title' => $this
          ->t('Roles'),
        '#default_value' => !$register ? $account
          ->getRoles() : [],
        '#options' => $roles,
        '#access' => FALSE,
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $current_pass_input = trim($form_state
      ->getValue('current_pass'));
    if ($current_pass_input) {
      $user = User::load(\Drupal::currentUser()
        ->id());
      if (!$this->passwordHasher
        ->check($current_pass_input, $user
        ->getPassword())) {
        $form_state
          ->setErrorByName('current_pass', $this
          ->t('The current password you provided is incorrect.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $user = User::load($this->userProfile
      ->id());
    $user
      ->setPassword($form_state
      ->getValue('pass'));
    $user
      ->save();
    $this
      ->messenger()
      ->addStatus($this
      ->t('Your password has been changed.'));
  }

  /**
   * Returns the user.
   *
   * @return \Drupal\user\UserInterface
   *   The User profile for the current user.
   */
  public function getEntity() {
    return $this->userProfile;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ChangePasswordForm::$passwordHasher protected property The Password Hasher.
ChangePasswordForm::$userProfile protected property The user.
ChangePasswordForm::buildForm public function Overrides FormInterface::buildForm
ChangePasswordForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ChangePasswordForm::getEntity public function Returns the user.
ChangePasswordForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ChangePasswordForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ChangePasswordForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ChangePasswordForm::__construct public function Constructs a UserPasswordForm object.
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.
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.