NodeJs :- Getting "missing credentials" error while using local passport
I have made changes to the code. You have used passport-local-mongoose
wrongly here.
//register
if (errors.length > 0) {
res.render('register', {
errors,
name,
username,
password,
password2
});
} else {
User.findOne({ username: username }).then(user => {
if (user) {
errors.push({ msg: 'username already exists' });
res.render('register', {
errors,
name,
username,
password,
password2
});
} else {
const newUser = new User({
name,
username,
password
});
User.register(newUser, req.body.password, function(err, user){
console.log(req.body)
if(err){
console.log(err);
return res.render("register", {error: err.message});
}
passport.authenticate("local")(req, res, function(){
req.flash("success", "Successfully Signed Up! Nice to meet you " + req.body.name);
res.redirect('/users/login');
});
});
}
});
}
// forgot password
router.post('/forgot', function(req, res, next) {
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ username: req.body.username }, function(err, user) {
if (!user) {
req.flash('error', 'No account with that username address exists.');
return res.redirect('/users/forgot');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
//reset token
async.waterfall([
function(done) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('back');
}
if(req.body.password === req.body.confirm) {
user.setPassword(req.body.password, function(err) {
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
req.logIn(user, function(err) {
done(err, user);
});
});
})
} else {
req.flash("error", "Passwords do not match.");
return res.redirect('back');
}
});
},