首页 > 解决方案 > 沿 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 应用程序传递和更新数据

标签: node.jsexpress

解决方案


创建上下文对象

与您的示例一样,我们添加了另一个为中间件管道创建上下文的中间件:

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 对象。


推荐阅读