2

Is there an easy way to add a password reset button to the user page in drupal 8? For user management I need the admin to be able to send password recovery link to users AFTER the user account is created. This button should only be visible to admins.

1 Answer 1

3

You can create a custom module for that.

resetpassword.info.yml

name: 'Reset Password'
type: module
description: 'Reset Password link for administrators'
core: 8.x

resetpassword.module

<?php

/**
 * @file
 * Hook implementations for the Reset Password module.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Component\Utility\Html;
    
/**
 * Alter the user edit form
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function resetpassword_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $user = \Drupal::currentUser()->getRoles();
  if (in_array("administrator", $user)) {
    $form['actions']['sendresetlink'] = [
      '#type' => 'submit',
      '#weight' => 999,
      '#limit_validation_errors' => [],
      '#button_type' => 'danger',
      '#submit' => [
        'resetpassword_send_reset_link_to_account_submit'
      ],
      '#value' => t('Sent reset link to account email'),
    ];
  }
}

/**
 * Submission handler for the password reset button.
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function resetpassword_send_reset_link_to_account_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // Load the user entity of the form.
  $account = $form_state->getFormObject()->getEntity();

  // Create a timestamp.
  $timestamp = \Drupal::time()->getRequestTime();
  // Set the redirect location after the user of the one time login.
  $path = '';

  // Create the login link from the route.
  $link = Url::fromRoute(
    'user.reset.login', ['uid' => $account->id(),
      'timestamp' => $timestamp,
      'hash' => user_pass_rehash($account, $timestamp),
    ],
    ['absolute' => true,
      'query' => $path ? ['destination' => $path] : [],
      'language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()),
    ]
  )->toString();

  // Genereate mail.
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'resetpassword';
  $key = 'user_reset_links';
  $to = $account->getEmail();
  $langcode = \Drupal::currentUser()->getPreferredLangcode();

  // Set the message and the subject.
  $params['message'] = $link;
  $params['title'] = t("One time login link");

  // Send mail and collect the result.
  $result = $mailManager->mail($module, $key, $to, $langcode, $params);
  if (!$result['result']) {
    \Drupal::messenger()->addError(t('There was a problem sending your email notification to @email.', array('@email' => $to)));
    \Drupal::logger('mail-log')->error('There was a problem sending your email notification to @email.', array('@email' => $to));
    return;
  }

  \Drupal::messenger()->addMessage(t('An email notification has been sent to @email ', array('@email' => $to)));
  \Drupal::logger('mail-log')->notice('An email notification has been sent to @email ', array('@email' => $to));
}

/**
 * Implements hook_mail().
 */
function resetpassword_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  );

  if ($key == 'user_reset_links') {
    $message['from'] = \Drupal::config('system.site')->get('mail');
    $message['subject'] = t('Your mail subject Here: @title', array('@title' => $params['title']), $options);
    $message['body'][] = Html::escape($params['message']);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.