Thian Kian Phin Thian Kian Phin - 5 months ago 51
Node.js Question

passport register success callback

router.post('/register', function(req, res, next){
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;

req.checkBody('name', 'Name field is required').notEmpty();
req.checkBody('email', 'Email field is required').notEmpty();
req.checkBody('email', 'Email must be a valid email address').isEmail();
req.checkBody('username', 'Username field is required').notEmpty();
req.checkBody('password', 'Password field is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

var errors = req.validationErrors();

if(errors){
res.render('register');

} else {

passport.authenticate('local-register',{
successRedirect: '/dashboard',
failureRedirect: '/register'
})(req, res, next)
}
});


I want to do some more operation after the user registered, like pumping in related data in db. But I've no idea where is the success callback in passport

Answer

Looking at the passport documentation you should be able to achieve this by redirecting the response yourself.

Example:

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

So your code can potentially be modified to something like this...

router.post('/register', function(req, res, next){
    var name            = req.body.name;
    var email           = req.body.email;
    var username        = req.body.username;
    var password        = req.body.password;
    var password2       = req.body.password2;

    req.checkBody('name', 'Name field is required').notEmpty();
    req.checkBody('email', 'Email field is required').notEmpty();
    req.checkBody('email', 'Email must be a valid email address').isEmail();
    req.checkBody('username', 'Username field is required').notEmpty();
    req.checkBody('password', 'Password field is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors){
        res.render('register');
    } else {
        passport.authenticate('local-register',{ })(req, res, function(returnCode) {
            // Yay successfully registered user
            // Do more stuff
            console.log(returnCode);     // Check what this value is and redirect accordingly.
            res.redirect('/dashboard/'); // How redirect can potentially be done
       })
    }
});

I'm not sure what the returnCode value would be because that will depend on the implementation for local-register strategy.

Anyway, returnCode can potentially be used for checking whether a registration was successful or not, and depending on its value - redirect the user accordingly.