gpt4 book ai didi

javascript - 这些在创建模型之前加密密码的方法之间有区别吗?它们都是异步的吗?

转载 作者:行者123 更新时间:2023-12-03 22:37:44 25 4
gpt4 key购买 nike

我第一次使用 sequelize 并尝试使用钩子(Hook),另外我只是在学习 JS 中的 Promise。我有两种实现函数的方法,但我想知道一种是异步的,另一种不是?

// METHOD 1
User.addHook("beforeCreate", (user) => {
user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(8), null);
});

// METHOD 2
User.addHook("beforeCreate", (user, options) => {
return bcrypt.hashSync(user.password, bcrypt.genSaltSync(8), null)
.then(hashedPw => {
user.password = hashedPw;
});
});

另外,如果有人知道'options'参数的用途会有所帮助,方法2基本上取自Sequelize docs并且它具有'options'参数但我看不到它的使用位置......

编辑

评论让我明白上述方法不是异步的,因为它们使用 hashSync,所以我做了一个新的实现,但这仍然导致未散列的密码被保存到 db...
const saltRounds = 8;
User.addHook("beforeCreate", (user) => {
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(user.password, salt, null, function(err, hash) {
user.password = hash;
});
});
});

最佳答案

@WillCowan 如 Bcrypt hasSync() 文档中所述,方法 2 将不起作用不返回 promise 。

选项作为第二个参数传递,通常用于更改方法的默认行为并根据 sequelize doc 传递一些额外的设置。

您在实现中遇到任何问题吗?

编辑

我已经编写并测试了以下代码,请您检查一下:

const saltRounds = 8;
User.addHook('beforeCreate',(user,options)=>{
var salt = bcrypt.genSaltSync(saltRounds);
var hash = bcrypt.hashSync(user.password, salt);
user.password = hash
})

User.create({
username: "shi",
birthday: new Date(),
password:"hello123"
}).then((user) => {
console.log("user detail \n", user.userInfo);
})

正在打印 shi_Fri Jun 07 2019 14:05:07 GMT+0530 (IST)_$2b$10$os4R7AALhNfYW2namfw0GOGn0hDd0ugEE2hOuoJVzDxL6qNxnG7G2

关于javascript - 这些在创建模型之前加密密码的方法之间有区别吗?它们都是异步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56475835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com