I'm having some trouble with using Passport for authentication. I've defined my signup strategy as follows:
passport.use('local_signup', new localStrategy({
usernameField: 'username',
passwordField:'password',
passReqToCallback: true
},function(req,username, password,done){
User.findOne({username: username},function(err,user){
if(err){
console.log(err);
} else{
if(user){
console.log("user exists.")
}
else{
const newUser = new User();
newUser.email = req.body.email;
newUser.password =req.body.password;
newUser.username = req.body.user_name;
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.save(function(err){
if(err){
console.log(err);
}else{
console.log('success');
}
})
}
}
})
})
)
I've then called this strategy in my register route
app.post('/register', passport.authenticate('local_signup', {
successRedirect : '/drinks',
failureRedirect : '/register',
failureFlash : true
}));
If the authentication was successful it should trigger the drinks route
app.get('/drinks',function(req,res){
if(req.isAuthenticated()){
res.render('start');
} else {
res.redirect('/login')
}
})
successRedirect isn't redirecting to the desired page. It remains stuck on the register route. The populated users however are showing up on my database so at least my strategy is working. I don't know how to debug this. Any help would be appreciated. Thanks
You are not making use of done()
. From what I understand, it is an exit point from the strategy code and letting the flow go to success or failure based on the params you pass in it. It is a param in your callback in your strategy implementation code. It is something internal to passport.
Call it like this in case of success:
return done(null, newUser);
Call it like this in case of error:
done(err);