Gor February 2016

Node.js passport custom callback

I am using passport for my node.js app. When I want to authenticate users local, I can simply do it

function local(req, res) {
    req._passport.instance.authenticate('local', function(err, user, info) {
        if(err) {
            return workflow.emit('exception', err);
        }
        // and so on
        res.end('some data');
    }
}

But when I want to use facebook strategy, I must use redirectUrls like this.

function signinFacebook(req, res, next) {
    req._passport.instance.authenticate('facebook')(req, res, next);
}

function facebookCallback(req, res, next) {
    req._passport.instance.authenticate('facebook', {
        successRedirect: '/',
        failureRedirect: '/'
    })(req, res, next);
}

This way I cant send with response data, that I am sending on local strategy.

Can anyone help me to fix it. I want not give success and failure Redirects, I want to call some function if all goes well like on local strategy.

Answers


Gunar C. Gessner February 2016

I've found this in Passport's documentation, it may help.

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.

Post Status

Asked in February 2016
Viewed 2,352 times
Voted 14
Answered 1 times

Search




Leave an answer