javascript - 如何为 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。
解决方案
包装成一个承诺:
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()
});
推荐阅读
- python - Python - 从实时 youtube 视频中每 n 秒提取一帧而不下载视频序列
- c# - 目录存在时 ZipFile.ExtractToDirectory 会抛出异常吗?
- javascript - React:如何在输入的 onChange 事件上更改路由
- visual-studio - 为什么 Visual Studio 生成后事件会阻止应用程序运行(调试)?
- python - 使用xpath同时选择:(p元素中的文本)和(img中的属性'src',它是p的子元素)
- tensorflow - pipenv - 由于“找不到与 keras-nightly~=2.5.0.dev 匹配的版本”错误,未生成 Pipfile.lock
- excel - 不同数据类型的 Excel 格式
- html - 如何将角度材料步进器放入角度?
- json - Jmeter提取并在If Controller上使用
- java - Java SFTP :: Apache Camel RemoteFileProducer 忽略异常