node.js - Node.js bcrypt比较问题只返回false
问题描述
我想用 Node.js 和 MongoDB 做我的登录 API,当我比较我的输入和数据库中的那个时,我总是得到错误,我读了 StackOverFlow 上的其他帖子,但没有帮助我。
我想我也发现了问题:当我在密码输入上使用哈希值来手动检查它时,每次请求都来自 db 是 onatherone。
所以也许这就是问题,但我不知道如何解决。我读了很多关于这个但仍然无法解决这里是我的代码:
const match = await bcrypt.compare(password, user.password, (res) => {console.log(res)}) //false
我的登录 api
router.post('/login', body('email').isEmail(), body('password').exists(), async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
const { email, password } = req.body
const user = await User.findOne({ email })
if (!user) {
return res.status(401).json({ "err": "invalid credentials" })
}
// const match = await bcrypt.compare(password, user.password).then(function (res) { console.log(res) })
const match = await bcrypt.compare(password, user.password);
console.log(match)
})
这是注册API
router.post("/register", body("email").isEmail(), body("password").isLength({ min: 5 }), body("username").isLength({ min: 1 }), async (req, res) => {
const { email, username, password } = req.body
const errors = validationResult(req);
const saltRounds = 10;
try {
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
//check if the user exist
const duplicated = await User.findOne({ email })
if (duplicated) { return res.status(401).json({ "err": "Email is taken" }) }
const user = new User({ username, email, password })
//crypt pass
user.password = bcrypt.hashSync(process.env.secret, saltRounds);
//generate token with jwt
const payload = {
id: user.id
}
jwt.sign({
payload,
}, process.env.jwtSecret, { expiresIn: '999h' }, (err, token) => { console.log(token) });
//save the user
await user.save()
res.status(200).send("User Stored")
} catch (error) {
res.status(500).send(error.body)
}
})
解决方案
您的问题是您bcrypt.hash
以错误的方式使用。似乎您提供了这种方法的密钥,您不应提供。此方法接受要散列的值,并且saltRounds
.
因此,您基本上需要将您的注册 API 代码更改为:
router.post("/register", body("email").isEmail(), body("password").isLength({ min: 5 }), body("username").isLength({ min: 1 }), async (req, res) => {
const { email, username, password } = req.body
const errors = validationResult(req);
const saltRounds = 10;
try {
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
//check if the user exist
const duplicated = await User.findOne({ email })
if (duplicated) { return res.status(401).json({ "err": "Email is taken" }) }
const user = new User({ username, email, password })
//crypt pass
user.password = bcrypt.hashSync(password, saltRounds);
//generate token with jwt
const payload = {
id: user.id
}
jwt.sign({
payload,
}, process.env.jwtSecret, { expiresIn: '999h' }, (err, token) => { console.log(token) });
//save the user
await user.save()
res.status(200).send("User Stored")
} catch (error) {
res.status(500).send(error.body)
}
}
更具体地说,您将密码存储在:
user.password = bcrypt.hashSync(password, saltRounds);
推荐阅读
- reactjs - React - 测试当 Jest 和 Enzyme 状态改变时组件中的条件渲染元素是否被渲染
- firebase - React-native firebase 远程配置缓存刷新
- javascript - Dynamic TreeView of a directory in React
- python - 使用 Selenium (Python) 从元素中获取文本
- python - manim 条形图中的条形值
- python-3.x - 如何访问数据集中列中的列表值列表
- google-sheets - 如何使用谷歌表格转置一组与特定输入日期相对应的单元格?
- javascript - 如何在 p5.js 中为游戏创建小地图?
- typescript - 如何做一个深型后卫?
- c++ - 无法识别的命令行选项“-Zc:__cplusplus”和无法识别的命令行选项“-permissive-”