class UserPasswordForm
Same name in other branches
- 9 core/modules/user/src/Form/UserPasswordForm.php \Drupal\user\Form\UserPasswordForm
- 8.9.x core/modules/user/src/Form/UserPasswordForm.php \Drupal\user\Form\UserPasswordForm
- 11.x core/modules/user/src/Form/UserPasswordForm.php \Drupal\user\Form\UserPasswordForm
Provides a user password reset form.
Send the user an email to reset their password.
@internal
Hierarchy
- class \Drupal\Core\Form\FormBase implements \Drupal\Core\Form\FormInterface, \Drupal\Core\DependencyInjection\ContainerInjectionInterface uses \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Logger\LoggerChannelTrait, \Drupal\Core\Messenger\MessengerTrait, \Drupal\Core\Routing\RedirectDestinationTrait, \Drupal\Core\StringTranslation\StringTranslationTrait
- class \Drupal\user\Form\UserPasswordForm extends \Drupal\Core\Form\FormBase implements \Drupal\Core\Form\WorkspaceSafeFormInterface uses \Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait
Expanded class hierarchy of UserPasswordForm
1 string reference to 'UserPasswordForm'
- user.routing.yml in core/
modules/ user/ user.routing.yml - core/modules/user/user.routing.yml
File
-
core/
modules/ user/ src/ Form/ UserPasswordForm.php, line 27
Namespace
Drupal\user\FormView source
class UserPasswordForm extends FormBase implements WorkspaceSafeFormInterface {
use DeprecatedServicePropertyTrait;
/**
* The deprecated properties.
*/
protected array $deprecatedProperties = [
'typedDataManager' => 'typed_data_manager',
];
/**
* The user storage.
*
* @var \Drupal\user\UserStorageInterface
*/
protected $userStorage;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The flood service.
*
* @var \Drupal\Core\Flood\FloodInterface
*/
protected $flood;
/**
* The email validator service.
*
* @var \Drupal\Component\Utility\EmailValidatorInterface
*/
protected $emailValidator;
/**
* Constructs a UserPasswordForm object.
*
* @param \Drupal\user\UserStorageInterface $user_storage
* The user storage.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Config\ConfigFactory $config_factory
* The config factory.
* @param \Drupal\Core\Flood\FloodInterface $flood
* The flood service.
* @param \Drupal\user\UserNameValidator|\Drupal\Core\TypedData\TypedDataManagerInterface $userNameValidator
* The user validator service.
* @param \Drupal\Component\Utility\EmailValidatorInterface $email_validator
* The email validator service.
*/
public function __construct(UserStorageInterface $user_storage, LanguageManagerInterface $language_manager, ConfigFactory $config_factory, FloodInterface $flood, UserNameValidator|TypedDataManagerInterface $userNameValidator, EmailValidatorInterface $email_validator) {
$this->userStorage = $user_storage;
$this->languageManager = $language_manager;
$this->configFactory = $config_factory;
$this->flood = $flood;
$this->emailValidator = $email_validator;
if (!$userNameValidator instanceof UserNameValidator) {
@\trigger_error('Passing $userNameValidator as \\Drupal\\Core\\TypedData\\TypedDataManagerInterface to ' . __METHOD__ . ' () is deprecated in drupal:10.3.0 and is removed in drupal:11.0.0. Pass a Drupal\\user\\UserValidator instead. See https://www.drupal.org/node/3431205', E_USER_DEPRECATED);
$this->userNameValidator = \Drupal::service('user.name_validator');
}
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('entity_type.manager')
->getStorage('user'), $container->get('language_manager'), $container->get('config.factory'), $container->get('flood'), $container->get('user.name_validator'), $container->get('email.validator'));
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'user_pass';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['name'] = [
'#type' => 'textfield',
'#title' => $this->t('Username or email address'),
'#size' => 60,
'#maxlength' => max(UserInterface::USERNAME_MAX_LENGTH, Email::EMAIL_MAX_LENGTH),
'#required' => TRUE,
'#attributes' => [
'autocorrect' => 'off',
'autocapitalize' => 'off',
'spellcheck' => 'false',
'autofocus' => 'autofocus',
'autocomplete' => 'username',
],
];
// Allow logged in users to request this also.
$user = $this->currentUser();
if ($user->isAuthenticated()) {
$form['name']['#type'] = 'value';
$form['name']['#value'] = $user->getEmail();
$form['mail'] = [
'#prefix' => '<p>',
'#markup' => $this->t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the email.', [
'%email' => $user->getEmail(),
]),
'#suffix' => '</p>',
];
}
else {
$form['mail'] = [
'#prefix' => '<p>',
'#markup' => $this->t('Password reset instructions will be sent to your registered email address.'),
'#suffix' => '</p>',
];
$form['name']['#default_value'] = $this->getRequest()->query
->get('name');
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
$form['#cache']['contexts'][] = 'url.query_args';
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$flood_config = $this->configFactory
->get('user.flood');
if (!$this->flood
->isAllowed('user.password_request_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
$form_state->setErrorByName('name', $this->t('Too many password recovery requests from your IP address. It is temporarily blocked. Try again later or contact the site administrator.'));
return;
}
$this->flood
->register('user.password_request_ip', $flood_config->get('ip_window'));
// First, see if the input is possibly valid as a username.
$name = trim($form_state->getValue('name'));
$violations = $this->userNameValidator
->validateName($name);
// Usernames have a maximum length shorter than email addresses. Only print
// this error if the input is not valid as a username or email address.
if ($violations->count() > 0 && !$this->emailValidator
->isValid($name)) {
$form_state->setErrorByName('name', $this->t("The username or email address is invalid."));
return;
}
// Try to load by email.
$users = $this->userStorage
->loadByProperties([
'mail' => $name,
]);
if (empty($users)) {
// No success, try to load by name.
$users = $this->userStorage
->loadByProperties([
'name' => $name,
]);
}
$account = reset($users);
// Blocked accounts cannot request a new password.
if ($account && $account->id() && $account->isActive()) {
// Register flood events based on the uid only, so they apply for any
// IP address. This allows them to be cleared on successful reset (from
// any IP).
$identifier = $account->id();
if (!$this->flood
->isAllowed('user.password_request_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
return;
}
$this->flood
->register('user.password_request_user', $flood_config->get('user_window'), $identifier);
$form_state->setValueForElement([
'#parents' => [
'account',
],
], $account);
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$account = $form_state->getValue('account');
if ($account) {
// Mail one time login URL and instructions using current language.
$mail = _user_mail_notify('password_reset', $account);
if (!empty($mail)) {
$this->logger('user')
->info('Password reset instructions mailed to %name at %email.', [
'%name' => $account->getAccountName(),
'%email' => $account->getEmail(),
]);
}
}
else {
$this->logger('user')
->info('Password reset form was submitted with an unknown or inactive account: %name.', [
'%name' => $form_state->getValue('name'),
]);
}
// Make sure the status text is displayed even if no email was sent. This
// message is deliberately the same as the success message for privacy.
$this->messenger()
->addStatus($this->t('If %identifier is a valid account, an email will be sent with instructions to reset your password.', [
'%identifier' => $form_state->getValue('name'),
]));
$form_state->setRedirect('<front>');
}
}
Members
Title Sort descending | Modifiers | Object type | Summary | Overriden Title | Overrides |
---|---|---|---|---|---|
DependencySerializationTrait::$_entityStorages | protected | property | |||
DependencySerializationTrait::$_serviceIds | protected | property | |||
DependencySerializationTrait::__sleep | public | function | 1 | ||
DependencySerializationTrait::__wakeup | public | function | 2 | ||
DeprecatedServicePropertyTrait::__get | public | function | Allows to access deprecated/removed properties. | ||
FormBase::$configFactory | protected | property | The config factory. | 3 | |
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. | 3 | |
FormBase::container | private | function | Returns the service container. | ||
FormBase::currentUser | protected | function | Gets the current user. | 2 | |
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. | ||
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. | ||
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. | 16 | |
MessengerTrait::messenger | public | function | Gets the messenger. | 16 | |
MessengerTrait::setMessenger | public | function | Sets the messenger. | ||
RedirectDestinationTrait::$redirectDestination | protected | property | The redirect destination service. | 2 | |
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. | 3 | |
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. | ||
UserPasswordForm::$deprecatedProperties | protected | property | The deprecated properties. | ||
UserPasswordForm::$emailValidator | protected | property | The email validator service. | ||
UserPasswordForm::$flood | protected | property | The flood service. | ||
UserPasswordForm::$languageManager | protected | property | The language manager. | ||
UserPasswordForm::$userStorage | protected | property | The user storage. | ||
UserPasswordForm::buildForm | public | function | Form constructor. | Overrides FormInterface::buildForm | |
UserPasswordForm::create | public static | function | Instantiates a new instance of this class. | Overrides FormBase::create | |
UserPasswordForm::getFormId | public | function | Returns a unique string identifying the form. | Overrides FormInterface::getFormId | |
UserPasswordForm::submitForm | public | function | Form submission handler. | Overrides FormInterface::submitForm | |
UserPasswordForm::validateForm | public | function | Form validation handler. | Overrides FormBase::validateForm | |
UserPasswordForm::__construct | public | function | Constructs a UserPasswordForm object. |
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.