node.js - 沿 node-express 应用程序传递和更新数据
问题描述
如何在不使用 DB 的情况下沿 node-express 应用程序传递和更新数据。
所以我使用护照进行身份验证(认为这是在src/google-passport.js),
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL,
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
accessType: 'offline'
}, (accessToken, refreshToken, params, profile, cb) => {
let profileSort = extractProfile(profile)
mongooeHelperFunction.findUserByEmail(profileSort.email).then(response => {
if (!response) {
mongooeHelperFunction.createNewUser(profileSort)
.then(res => {
let newRes = {...res._doc}
newRes["accessToken"] = accessToken
cb(null, newRes)
})
.catch(error => { throw error })
} else {
let newRes = {...response._doc}
newRes["accessToken"] = accessToken
cb(null, newRes)
}
})
.catch(error => { throw error })
}
))
从 Passport,我得到一个access token 和 refresh token。通常谷歌访问令牌有效期为一个小时。
所以我想存储我收到访问令牌的时间,如果我的访问令牌过期,我想使用刷新令牌来获取新的访问令牌,然后在生成新的访问令牌后更新时间。
考虑一个 api 路由
app.get("/something", isTokenValid, (req, res) => {
中间件函数在哪里,在创建护照令牌时isTokenValid
我可以在该函数内部,然后我可以将它与当前时间进行比较。
此外,如果令牌已过期,我有一个函数可以发送刷新令牌以获取新的访问令牌并将访问令牌的先前数据/时间更新为新的日期/时间
问题:如何通过 node-express 应用程序传递和更新数据
解决方案
创建上下文对象
与您的示例一样,我们添加了另一个为中间件管道创建上下文的中间件:
const initCtx = (req,res,next) => {
req.ctx = {};
next();
}
然后在您的中间件声明中:
app.get("/something", [initCtx, isTokenValid], (req, res) => {
通常,这可以作为管道中的第一个中间件完成,位于整个应用程序中的中间件声明之上:
const initCtx = (req,res,next) => {
req.ctx = {};
next();
}
app.use(initCtx);
将价值传递给ctx
在isTokenValid
你检索的中间件中accessToken
,它的到期时间,最后你可以通过它。访问令牌到期的地方是tokenExpiration
:
req.ctx.tokenExpiration = tokenExpiration;
使用价值
在负责刷新令牌的中间件中:
app.get("/something", [initCtx, isTokenValid], (req, res) => {
const tokenExpiration = req.ctx.tokenExpiration; // you have token expiration time that you can compare and apply required logic in refreshing token middleware
原始回复及说明
您可以分配属性ctx
(上下文对象)来表达req
对象并在中间件之间传递信息。然后,您将能够在下游中间件中检查此对象中的特定键并应用所需的逻辑。
ctx
对象可以由管道中的第一个中间件创建(这个中间件通常还检查requestId
标头并将其分配给ctx
,因此可以轻松跟踪同一请求上下文中的所有操作)
如果令牌有效,您可以分配req.ctx.tokenExpiration
,然后在另一个中间件中检查是否需要刷新它。
顺便说一句,Koa 和 Loopback 框架开箱即用地使用 ctx 对象。
推荐阅读
- angular - 将局部变量传递给 html 标签
- node.js - 如何从 indiexpo 中提取有关节点 js 中用户的数据?
- python - 查找播放列表的所有视频标题的 Python 程序
- database - 位图索引与 b-tree 时间复杂度
- html - 表格不会使用 flexbox 垂直居中
- r - R 子集向量以替换 NA
- php - 将 Jquery Array 发送到 PHP,然后插入 mySQL 数据库
- android - CountDownLatch 冻结 Android 上的线程
- arrays - 替换数组的前“m”个元素
- java - 如何一次嵌入所有 FXML 嵌套控制器?