passport.js - Access fail message after 401 error

限于喜欢 提交于 2019-12-07 11:10:35

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/29662886/passport-js-access-fail-message-after-401-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!