[英]bcrypt.compare always return false
I want to create a login with jwt but bcrypt compare does not work. 我想用jwt创建一个登录名,但是bcrypt比较不起作用。 I connected node to my db and put the db object in the req.
我将节点连接到数据库,并将数据库对象放入请求中。 The type of req.body.password and user.passwordHash is in bouth cases string.
在所有情况下,req.body.password和user.passwordHash的类型都是字符串。
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jwt-simple');
const joi = require('joi');
const authHelper = require('./authHelper');
const router = express.Router();
router.post('/', (req, res, next) => {
const schema = {
email: joi.string().email().min(7).max(50).required(),
password: joi.string().regex(/^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{7,15}$/).required()
};
joi.validate(req.body, schema, (err) => {
if(err)
return next(new Error('Invalid field: password 7 to 15 (one number, one specail character)'));
req.db.collection.findOne({ type: 'USER_TYPE', email: req.body.email }, (err, user) => {
if(err)
return next(err);
if(!user)
return next(new Error('User was not found'));
bcrypt.compare(user.passwordHash, req.body.password, (err, match) => {
if(match) {
try {
const token = jwt.encode({
authorized: true,
sessionIP: req.ip,
sessionUA: req.headers['user-agent'],
userId: user._id.toHexString(),
displayName: user.displayName
}, process.env.JWT_SECRET);
res.status(201).json({
displayName: user.displayName,
userId: user._id,
token: token,
msg: 'Authorized'
});
}
catch(err) {
return next(err);
}
}
else {
return next(new Error('Wrong password'));
}
});
});
});
});
I hope you can solve my problem :) 我希望你能解决我的问题:)
bcrypt.compare
的第一个参数是用户未修饰的密码,第二个参数是哈希。
bcrypt.compare(req.body.password, user.passwordHash, (err, match) => {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.