在节点js中执行post请求之前,我需要一种比较两个散列密码的方法。散列密码存储在mongoDB数据库中。我把我的错误缩小到了这些可能的范围。
//Part 1
router.post('/signIn', function (req, res) {
if(errors){
console.log(errors);
res.render('signIn', {
errors: errors
});
}else {
module.exports = function (passport) {
passport.authenticate('local',{successRedirect: '/dashboard', failureRedirect: '/', failureFlash: true})
},
module.exports = function (passport) {
passport.use(new LocalStrategy(
function (username, password, done) {
User.getUserByUsername(inputUser, function (err, user) {
if (err) throw err;
if (!user) {
req.flash('error_msg','Unknown Username');
return done(null, false);
}
User.comparePassword(inputPwd, user, hash, function (err, isMatch) {
if (err) throw err;
if (isMatch) {
req.flash('error_msg','Unknown Password');
return done(null, user);
} else {
return done(null, false);
}
})
})
}))
},
module.exports = function (passport) {
passport.serializeUser( function (user, done) {
done(null, user.id());
});
},
module.exports = function (passport) {
passport.deserializeUser( function (id, done) {
User.getUserById(id, function (err, user) {
done(err, user);
});
});
};
res.redirect('/users/dashboard');
}
});
这些部分来自不同的文件。
//Part 2:
module.exports.createUser = function (newUser, callback) {
bcrypt.hash(newUser.password, 10, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
}
module.exports.getUserByUsername = function (username, callback) {
var query = {username: username};
User.findOne(query, callback);
}
module.exports.comparePassword = function (password, hash, callback ) {
bcrypt.compare(password, hash, function(err, isMatch) {
if (err) throw err;
callback(null, isMatch);
console.log(isMatch);
});
}
答案 0 :(得分:0)
好的,你犯了一些错误,我希望我找到了所有的错误。我将通过代码中的注释来浏览它们:
function (username, password, done) {
// inputUser is undefined, shouldn't that be username?
User.getUserByUsername(inputUser, function (err, user) {
if (err) throw err; // you should never throw in async callbacks! use done(err) instead
if (!user) {
req.flash('error_msg','Unknown Username');
return done(null, false);
}
// all your input arguments are undefined! Where does inputPwd, user and has coe from?
// inputPassword should be password i guess, hash idk, maybe user.hash?
// also your arguments are wrong
User.comparePassword(inputPwd, user, hash, function (err, isMatch) {
if (err) throw err; // again, don't throw!
if (isMatch) {
req.flash('error_msg','Unknown Password');
return done(null, user);
} else {
return done(null, false);
}
})
})
}));
现在已更正版本:
function (username, password, done) {
User.getUserByUsername(username, function (err, user) {
if (err) return done(err);
if (!user) {
req.flash('error_msg','Unknown Username');
return done(null, false);
}
User.comparePassword(password, user.password, function (err, isMatch) {
if (err) return done(err);
if (isMatch) {
req.flash('error_msg','Unknown Password');
return done(null, user);
} else {
return done(null, false);
}
})
})
}));