I am working on doing passport authentication in my node application and I cannot understand why it is necessary to redirect before I can access the response attribute (res)?
app.get('/api/loginFailure', function(req, res) {
res.status(401).json({message: 'Login Failed', success: true});
});
app.get('/api/loginSuccess', function(req, res) {
res.status(200).json({message:'Welcome!', success: true});
});
app.post('/api/login', passport.authenticate('local-login', {
successRedirect: '/api/loginSuccess',
failureRedirect: '/api/loginFailure'}));
As you can see, I am using successRedirect to access another route to send a json response. I do not want the node api to redirect the actual application, as the intention is to be agnostic for the external interface.
The local login strategy is as follows. I suspect that my difficulties may be in how I return from the method;
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done) {
User.findOne({
'local.email': email
},
function(err, user) {
if (err)
return done(err);
if (!user) {
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
if (!user.validPassword(password)) {
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
}
return done(null, user);
});
}));
I intend to remove all flashdata and what not, but for now it’s just possible to roll up two additional api routes to / api / login, it would be great.