[英]my result from using bcryptjs compare returns false. When comparing plaintext to hashed password from database (mongodb).(node-js)
不幸的是,比较 function 的结果总是错误的? 即使发布了正确的数据。 认为这可能与比较 Bcrypt 的 function 有关吗?
注册 hash 并加盐密码
module.exports.signupPost = async (req, res) => {
const { email, password } = req.body;
//create a user with hashed password
try {
const newUser = await User.create({ email, password });
newUser.password = await bcrypt.hash(newUser.password, 12);
newUser.save();
res.status(200).json({ user: newUser._id });
} catch (err) {
errors = handlerErr(err);
res.status(400).json({ errors });
}
};
登录将密码与哈希密码进行比较
module.exports.loginPost = async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
res.status(404).json({ email: "No user found" });
}
//if user exist check password is a match
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ email: "No user found" });
}
try {
const match = await bcrypt.compare(
password.toString(),
user.password,
function (err, res) {
console.log(res);// returns false
}
);
} catch (err) {}
};
user schema
数据库用户模式
const userSchema = new mongoose.Schema({
email: {
type: String,
required: [true, "Please enter a email"],
unique: true,
lowercase: true,
},
password: {
type: String,
required: [true, "Please enter a password"],
lowercase: true,
},
});
从密码架构中删除lowercase: true
。
您在散列密码之前和保存 hash 时都将密码转换为小写。
您应该通过删除lowercase: true
。 此设置会导致所有字符串在存储到数据库之前转换为小写。
当前的实现有 2 个错误:
newUser
时,输入密码将在 DB 中转换为小写字母,然后您可以使用它来生成 hash。根据文档,您必须通过这种方式检查结果:
bcrypt.compareSync(password, user.password); // result true or false
const userSchema = new mongoose.Schema({
email: {
type: String,
required: [true, "Please enter a email"],
unique: true,
lowercase:true,
},
password: {
type: String,
required: [true, "Please enter a password"],
},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.