[英]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.