首页 > 解决方案 > 如何为 passport.authenticate 创建可重复使用的代码?

问题描述

我有多个控制器,每个控制器都有多种方法。在每种方法中,我都对用户进行身份验证,并使用身份验证返回的用户 ID 从数据库中获取数据。我正在尝试创建可重用的身份验证代码,因为代码是重复的。

在控制器中:

const authenticate = require('../utils/user-authenticate');

exports.getData = async (req, res, next) => {
    const userId = await authenticate.user(req, res, next);
    console.log(userId);
};

在身份验证中,我有:

exports.user = (req, res, next) => passport.authenticate('jwt', async (error, result) => {
    if (error) {
      // Send response using res.status(401);
    } else {
      return result;
    }
})(req, res, next);

console.log(userId);版画undefined总是。这是护照完成前的打印。看起来不像async/await我在这里想要的那样工作。

如果我使用await authenticate.user(req, res, next).then()它可以工作,但不能将结果直接分配给userId变量吗?

如果我使用return next('1'): 第一次undefined但第二次打印 1。

标签: javascriptnode.jspassport.js

解决方案


包装成一个承诺:

exports.user = (req, res, next) => new Promise((resolve, reject) => {
  passport.authenticate('jwt', async (error, result) => {
    if (error) {
      // reject(error)
      // Send response using res.status(401);
    } else {

      resolve(result);
    }
  })(req, res, next);
})

但想想:

//app.use or something similar
addMiddleware(authJWT);
// later in the chain
useMiddleware((req, res, next)=>{
   // test auth or end chain
   if(!req.JWT_user) return; 
   req.customField = 'one for the chain'
   // process next middleware
   next()
});

推荐阅读