【问题标题】:Saving hashed password to Sequelize is defying my simple wish to save a hashed password将散列密码保存到 Sequelize 违背了我保存散列密码的简单愿望
【发布时间】:2021-02-12 21:54:44
【问题描述】:

这是我使用 Sequelize 和 postgreql 的第一天,所以请原谅我的幼稚问题。 我有一个简单的模型可以试用:

var User = sequelize.define("user", {
username: Sequelize.STRING,
password: Sequelize.STRING

})

我使用 expressjs/node 和 passportJS 供用户注册/注册:

passport.use('local-register', new LocalStrategy({
   passReqToCallback: true
}, function (req, username, password, done) {

User.findOne({ where: { username: username } }).then(function (user) {
    if (user) {   
        return done(null, false, { message: "enter  email that belongs to you please..." }, 
       console.log('That email is already taken'));
    } else {
       
         //use bcrypt to salt and hash the password
         let saltRounds = 2;
         let hashedpass = bcrypt.hash(password, saltRounds);           

        var data = {
            username: username,
            password: hashedpass  //password
        };
        User.create(data).then(function (newUser, created) {
            if (!newUser) {
                return done(null, false);
            }
            if (newUser) {
                return done(null, newUser);
            }
        });
    }
}).catch(err => { console.log("catch error :", err) });
}));

现在,在我尝试以用户身份注册后,出现错误:

UnhandledPromiseRejectionWarning: SequelizeValidationError: string violation: password cannot be an array or an object
at InstanceValidator._validate (D:\mycode\postegresql\postee1\node_modules\sequelize\lib\instance-validator.js:78:13)
at processTicksAndRejections (internal/process/next_tick.js:81:5)

我知道这是对密码 STRING 的续集验证,但我没有添加任何验证以及什么类型的续集数据类型可以接受散列密码?

我了解如何在我的模型中添加挂钩,并且在保存到数据库之前它会正确地散列密码:

   hooks: {
        beforeCreate: (user) => {
            const salt = bcrypt.genSaltSync(2);
            user.password = bcrypt.hashSync(user.password, salt);
        }
    },
    instanceMethods: {
        validPassword: function (password) {
            return bcrypt.compareSync(password, this.password);
        }
    }

但是我想在我的服务器代码中散列密码,就像我在上面尝试做的那样。如何修复上面的验证错误?我只想在我的护照句柄中使用 Bycrpt。数据类型错了吗? 如何在不触摸我的模型的情况下修复此错误?这应该不是问题,因为我已经对密码进行了哈希处理,我只需要保存它,但似乎 Sequelize 正在强制使用特定的方式来执行此操作,所以对于所有续集 NINJAS,我该如何解决这个问题?

【问题讨论】:

标签: node.js sequelize.js


【解决方案1】:

你调用了hash 没有传递回调。

您需要使用同步版本hashSync 而不是hash

let hashedpass = bcrypt.hashSync(password, saltRounds);

或使用异步版本hash

let hashedpass = await bcrypt.hash(password, saltRounds);
// OR
bcrypt.hash(password, saltRounds).then(hash => {
  hashedpass = hash
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 2019-12-12
    • 2023-04-06
    • 2017-06-26
    • 2013-10-15
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多