在 meanjs 中散列密码

hashing password in meanjs

我正在阅读 meanjs 的源代码,我的问题是带有代码的 hashPassword 方法:

UserSchema.methods.hashPassword = function(password) {
   if (this.salt && password) {
        return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
    } else {
        return password;
    }
};

这里我不明白为什么要返回密码,万一this.salt && password 是假的呢?据我了解,这是一个问题,也许它应该停止保存用户,对吧?

在 hashPassword 函数定义之前,您应该看到这个块:

    /**
     * Hook a pre save method to hash the password
     */
    UserSchema.pre('save', function(next) {
      if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
      }

      next();
    });

如您所见,在调用 hashPassword 之前生成了盐。如果您正确使用 meanjs,将永远不会返回明文密码。如果由于任何原因未定义 salt,它不会抛出错误,而是继续并以纯文本形式保存密码。

我对这个方法有些问题,改成了这个

if (this.password && this.password.length > 6) {
    if (!this.salt || this.salt.length === 0) {
        this.salt = crypto.randomBytes(16).toString('base64');
        this.password = this.hashPassword(this.password);
    }
}

错误在于,如果您在初始保存后再次尝试保存用户,您将无法使用该用户详细信息登录。 如果使用盐来加密已经加密的密码会发生什么,我认为这是错误的。

所以有两个选项可以解决这个问题,一个是您总是在调用保存之前将用户密码设置为空字符串,或者您按照我所做的或类似的方式进行操作。