我有密码作为用户身份验证中间件,我也实现了JWT,因此我想比较帖子密码是否与数据库中的密码相同(保存为哈希和盐(。但是这个
console.log(bcrypt.compareSync(req.body.password, user.hash));
始终返回我错误。
我应该如何修改它以纠正此问题?有没有办法在不使用bcrypt的情况下修改代码?
非常感谢。
用于用户注册并登录:
router.route('/register')
.get(function(req, res) {
res.render('register', { });
})
.post(function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', {info: 'Sorry. That username already exists. Try again.'});
}
passport.authenticate('local')(req, res, function() {
res.redirect('/');
});
});
});
router.route('/login')
.get(function(req, res) {
res.render('login', { user: req.user });
})
.post(passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
对于JWT身份验证,我有:
router.post('/authenticate', function(req, res) {
var collection = db.get('accounts');
// find the user
collection.findOne({
username: req.body.username
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.' });
} else if (user) {
// check if password matches
console.log(bcrypt.compareSync(req.body.password, user.hash));
if (!bcrypt.compareSync(req.body.password, user.hash)) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
} else {
// if user is found and password is right
// create a token
var payload = {
admin: user.admin
}
var token = jwt.sign(payload, app.get('superSecret'), {
expiresIn: 86400 // expires in 24 hours
});
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
});
我找到了答案,实际上要回忆起护照,我需要致电Passport.authenticate:
router.post('/auth', function(req, res,next) {
passport.authenticate('local', {
session: false
}, function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
console.log("Error");
//But here how do I know username invalid or password invalid?????
}
console.log("Success");
})(req, res, next);
});
});
如果(!用户(我怎么知道用户名无效或密码无效?如果有人知道答案欢迎发布,谢谢。