Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passport.js - Access fail message after 401 error

Currently I can access messages set in done(null, user, {message: 'ok'}) inside post request via req.authInfolike this:

app.post('/reg', passport.authenticate('local-reg', { session: false }), function (req, res) {        
        console.log(req.authInfo.message); --> 'ok'         
});

Which is very useful.
But how can i access message like this done(null, false, {message: 'username taken'}) in the same fashion, as it seems that passing done(null, false) in passport.authenticate makes it throw 401 unathorised, therefore not forwarding to the route handler itself.
Maybe i misunderstood something?

P.S.: I'm posting through jQuery.post.

like image 930
Max Yari Avatar asked Mar 17 '23 10:03

Max Yari


2 Answers

You should use custom callback where you have info accessible:

app.post('/req', function(req, res, next) {
  passport.authenticate('local-reg', {session: false}, function(err, user, info) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.json(info);
    }
    req.logIn(user, function(err) {
      if (err) {
        return next(err);
      }
      return res.json(info);
    });
  })(req, res, next);
});

req.authInfo gets set only after successful login. If you were using sessions you could use flash messages with redirects, eg:

app.post('/reg', passport.authenticate('local-reg', {
  successRedirect: '/',
  failureRedirect: '/',
  failureFlash: true,
  successFlash: true
}));

app.get('/', function(req, res) {
  res.json(req.flash());
});
like image 117
vesse Avatar answered Mar 29 '23 16:03

vesse


Everyone has their own way of implementing it. In my implementation if there are no errors and login is successful then :

return done(null, {type : true, data: {email: <some email>, role : <some role>, name: <some name>}, token : <some token>});

Whereas if any error or unsuccessful login then i do either

return done(null, {type : false, data: 'Email is already taken.'});

or

return done(null,{type:false, data: err}) 

So this makes my job simpler, i only check the type value and i can use it to pass values as well as error messages.

like image 26
NarendraSoni Avatar answered Mar 29 '23 18:03

NarendraSoni