如何以编程方式更改Drupal用户密码?

问题描述 投票:9回答:5

我们将在公司内部网中部署一个Drupal站点。用户需要重置密码。我们有一个集中的密码重置机制(用于单点登录):

  • user在系统中提交密码更改请求
  • 请求被发送到密码服务器
  • 密码服务器将使用新密码重置所有系统中的用户密码
  • 密码服务器将通过短信将新密码发送到用户的手机

现在我们要将Drupal站点添加到所有系统。请建议一种通过外部程序更改Drupal登录密码的方法(假设系统可以在Drupal主机上运行脚本并编辑Drupal MySQL数据库)。

drupal authentication drupal-modules
5个回答
4
投票

如果你使用的是Drupal 6,那么存储在系统中的密码就是密码的简单md5。如果您使用php脚本触发密码重置,请使用http://php.net/manual/en/function.md5.php函数。

用户名和密码存储在users表中。 md5哈希存储在pass列中。


7
投票

对于Drupal 7 - 希望这个自定义功能代码解析匿名用户的更改密码。

function password_reset(){
    global $user;
    $hashthepass = 'password'; /* Your password value*/
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
    $hashthepass = user_hash_password(trim($hashthepass));
    // Abort if the hashing failed and returned FALSE.
    if (!$hashthepass) {
      return FALSE;
    }
    else {
      db_update('users')
        ->fields(array(
          'pass' => $hashthepass
        ))
        ->condition('uid', $user->uid)       
        ->execute();
    }
 }

1
投票

Drupal 7的另一种可能性是:

$user = user_load($GLOBALS['user']->uid);
$user->pass = 'the new password';
user_save((object) array('uid' => $user->uid), (array) $user);

这将自动散列密码,而无需直接写入数据库。


1
投票

这是基于给定的$username的另一种更复杂的Drupal 7方法。它还支持用作用户名的电子邮件地址。

$users = user_load_multiple(array(), array('mail' => $username, 'status' => '1'));
$account = reset($users);
if (!$account) {
  // No success, try to load by name.
  $users = user_load_multiple(array(), array('name' => $username, 'status' => '1'));
  $account = reset($users);
}

if ($account) {
  $account->pass = 'new password';
  user_save($account);
}
else {
  watchdog('user', 'Cannot load user: %user', array('%user' => $username), array(), WATCHDOG_ERROR);
}

1
投票

这里已经有很多很好的答案了,但我相信我添加了一个我觉得容易找到的答案。

// ID of the user whose password you wish to change.
$uid = 1;

// Load the user account.
$account = user_load($uid);

// Load hashing libraries.
// You can use module_load_include() if you want to make it cleaner.
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

// Generate new password hash.
$password_hash = user_hash_password('enter-new-password-here');
if (!$password_hash) {
  // Password could not be hashed. Handle the error.
  exit('Password could not be hashed.');
}

$account->pass = $password_hash;
user_save($account);

如果一切设置正确,您的用户密码将被更新。

注意:如果您忘记了root密码,可以放心地忽略错误处理等。在menu_execute_active_handler()之前在index.php中添加这些行。并打开任何页面以重置密码。完成后不要忘记删除线条!

© www.soinside.com 2019 - 2024. All rights reserved.