Currently I can access messages set in done(null, user, {message: 'ok'})
inside post request via req.authInfo
like 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
.
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());
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With