passport.js - Access fail message after 401 error

你离开我真会死。 提交于 2019-12-05 16:13:57

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.

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