Passport node authenticate success

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});

});


// process the login form
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({
        // by default, local strategy uses username and password, we will override with email
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true // allows us to pass back the entire request to the callback
    },

    function(req, email, password, done) { // callback with email and password from our form

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({
                'local.email': email
            },

            function(err, user) {
                // if there are any errors, return the error before anything else
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user) {
                    return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
                }

                // if the user is found but the password is wrong
                if (!user.validPassword(password)) {
                    return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
                }

                // all is well, return successful user
                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.

+4
1

, , response (res)?

, , , , .

:

app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    res.redirect('/users/' + req.user.username);
  }
);
+3

All Articles