2015-01-07 27 views
0

我正在使用护照本地策略对我的nodeJs应用程序进行身份验证。一切工作正常。但是,如何向用户显示他已输入无效登录凭证的适当消息。我现在的代码只是在屏幕上发送401未经授权的错误如何处理护照身份验证响应并将其显示给用户

这里是我的代码

passport.use(new LocalStrategy(function(username, password, callback) { 
    User.findOne({ 
     username : username 
    }, function(err, user) { 
     if (err) { 
      return callback(err); 
     } 

     // No user found with that username 
     if (!user) { 
      return callback(null, false); 
     } 

     // Make sure the password is correct 
     user.verifyPassword(password, function(err, isMatch) { 
      if (err) { 
       return callback(err); 
      } 

      // Password did not match 
      if (!isMatch) { 
       return callback(null, false); 
      } 

      // Success 
      return callback(null, user); 
     }); 
    }); 
})); 

exports.isLocalAuthenticated = passport.authenticate('local', { 
    session : true 
}); 

router.post('/', authController.isLocalAuthenticated, function(req, res) { 
    //here I want to show the error message to user 

}); 

回答

1

documentation已经清楚地描述了下自定义回调节你的情况。

您需要添加自定义的回调是这样的:

exports.isLocalAuthenticated = function(req, res, next) { 
    passport.authenticate('local', function(err, user, info) { 
     if (err) { return next(err); } //error exception 

     // user will be set to false, if not authenticated 
     if (!user) { 
      res.status(401).json(info); //info contains the error message 
     } else { 
      // if user authenticated maintain the session 
      req.logIn(user, function() { 
       // do whatever here on successful login 
      }) 
     }  
    })(req, res, next); 
} 

你并不需要指定后者回调。

+0

需求,水库在这里没有定义!根据文档,唯一的方法是我们需要在路由本身中调用这个身份验证功能。 –

+0

@ShivaMothkuri更新时间。 –