被难住了..。我的代码与我在本节中遵循的教程完全相同。但是,bcryptjs.compare总是返回false。
数据库是mongodb,我读到的字符串长度限制设置为16mb,所以我不认为这与此有关。
userModel.js
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
isAdmin: {
type: Boolean,
required: true,
default: false
}
},{
timestamps: true
})
userSchema.methods.comparePW = async function(password) {
console.log(await bcrypt.compare(password, this.password))
return await bcrypt.compare(password, this.password)
}
module.exports = mongoose.model('User', userSchema)userController.js
const userModel = require('../models/userModel')
const asyncHandler = require('express-async-handler')
const userAuth = asyncHandler(async(req, res) => {
const { email, password } = req.body
// check if reqbody pw and email matches userModel pw/email
const user = await userModel.findOne({ email })
if (user && (await user.comparePW(password))) {
res.send('match')
} else {
res.send('no match')
}
})
module.exports = { userAuth }dummy user filler data in the database
const bcrypt = require('bcryptjs')
const users = [
{
name: 'Admin',
email: 'admin@test.com',
password: bcrypt.hashSync('admin123, 10'),
isAdmin: 'true',
},
{
name: 'Max Smith',
email: 'Max@test.com',
password: bcrypt.hashSync('admin123, 10'),
},
{
name: 'Jennifer Garnett',
email: 'Jen@test.com',
password: bcrypt.hashSync('admin123, 10'),
},
]
module.exports = users使用console.log时,bcrypt.compare方法总是返回false。
奇怪的是,本教程就是这么做的,而且似乎对讲师也很有效。
当我使用电子邮件"admin@test.com“和密码"admin123”运行post请求时,每次都返回false。
我尝试重新导入虚拟数据,并在mongodb compass上重新加载数据。
不确定在这一点上该如何解决此问题?有什么想法?
发布于 2021-10-04 12:17:37
在对密码进行哈希处理时,您将密码和盐强度组合到一个字符串中,该字符串应该是这个bcrypt.hashSync('admin123', 10)的bcrypt.hashSync('admin123, 10')。如果你想处理当前的情况,你需要输入密码"admin123,10"而不是"admin123"。
https://stackoverflow.com/questions/69185461
复制相似问题