簡體   English   中英

沿着node-express應用程序傳遞和更新數據

[英]Passing and updating data along node-express app

如何在不使用DB的情況下沿node-express app傳遞和更新數據。

所以我使用護照進行身份驗證(認為這是在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,我獲得了訪問令牌和刷新令牌 通常Google訪問令牌有效期為一小時。

所以我想存儲收到訪問令牌的時間,如果我的訪問令牌已過期,我想使用刷新令牌獲取新的訪問令牌,然后在生成新的訪問令牌后更新時間。

考慮api路線

app.get("/something", isTokenValid, (req, res) => {

其中isTokenValid是一個中間件函數,在我創建護照令牌我可以擁有該函數,然后我可以將它與當前時間進行比較。

另外,如果令牌已過期,我有一個函數可以發送刷新令牌以獲取新的訪問令牌,並將訪問令牌的先前數據/時間更新為新的日期/時間

問題:如何沿node-express app傳遞和更新數據

創建上下文對象

在您的示例中,我們添加了另一個為中間件管道創建上下文的中間件:

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對象一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM