网站搜索

javascript - 在 Meteor JS 中检查用户密码


在我的 Meteor 应用程序中,我想更改另一个用户的密码。我想知道在更改密码之前是否有办法获取旧密码。

这是我的服务器端方法:

 updateuser(id,password, options) {
    try {
        Meteor.users.update({ _id: id }, { $set: options })
        Accounts.setPassword(id, password, options)
    }
    catch (e) {
        return false;
        throw new Meteor.Error(500, 'updateUser error', e);
    }
}

我想知道旧密码是否正确。

答案#1

你无法获取旧密码,因为它是哈希的,但如果你拥有明文密码,你可以检查它是否正确。

你可以使用 Accounts._checkPassword(user, password) 方法来检查旧密码是否正确。它在这里实现。

user 应该是用户对象,password 应该是明文密码字符串。

如果结果(这是一个对象)不包含 error 属性,那么密码是正确的。

你也可以看看用于处理对 Accounts.changePassword(oldPassword, newPassword, [callback]) 调用的方法的实现(以获取灵感),该方法会更改当前用户的密码。

如果你不想将明文密码发送到服务器(通常最好不要发送明文版本),你可以在客户端使用 SHA256 对其进行哈希,通过将其传递给 Accounts._hashPassword(plainTextPassword)(在 accounts-password 包中实现)。

// on the client
>>> Accounts._hashPassword("foobar");

{
  "digest":"c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2",
  "algorithm":"sha-256"
}

使用此函数的结果调用你的服务器方法。假设你在方法中有 SHA256 哈希后的密码作为 oldPassword:

//on the server
const user = Meteor.users.findOne(userId);
Accounts._checkPassword(user, "wrongPassword");
// results in:
{ userId: 'theuserid',
  error: 
   { [Error: Incorrect password [403]]
     error: 403,
     reason: 'Incorrect password',
     details: undefined,
     message: 'Incorrect password [403]',
     errorType: 'Meteor.Error' } }

Accounts._checkPassword(user, oldPassword);
// results in the following if the password is correct
{ userId: 'theuserid' }