Express-Session - 有没有办法在 ExpressJS 路由之外的会话中存储数据?

Express-Session - Is there a way to store data in a session outside of an ExpressJS route?

我有一个 passportJS 回调,当新用户尝试进行身份验证时,我不希望将新用户数据存储在数据库中,而是希望存储在快速会话中以便稍后访问,这可能吗?

目前我的代码是:

function facebookAuthenticate(accessToken, refreshToken, profile, done) {
    User.findOne({ facebookID: profile._json.id }, (err, foundUser) => {
        if (foundUser) {
            done(err, foundUser);
        } else {
            global.authenticationID = { facebookID: profile._json.id };
            done(err, null)
        }
    });
}

但由于全局变量不是特定于用户的,因此一次只能用于一种身份验证。

理想情况下,我想要按照这些思路工作的东西,但当然我无法访问路由之外的 req 变量:

function facebookAuthenticate(accessToken, refreshToken, profile, done) {
    User.findOne({ facebookID: profile._json.id }, (err, foundUser) => {
        if (foundUser) {
            done(err, foundUser);
        } else {
            req.session.authenticationID = { facebookID: profile._json.id };
            done(err, null)
        }
    });
}

非常感谢。

没错,全局变量超出了路由范围。一个非常硬核的方法是将会话数据存储在磁盘上的一个文件中,并在需要时读取它。但是有一些限制。使用 jwt auth,您可以将数据存储在浏览器会话和 cookie 上。

一个简单的想法是先在 express 上创建一个会话,

var sessions    = require("client-sessions");
app.use(sessions({
      cookieName: 'expSessions', // cookie name dictates the key name added to the request object
      secret: 'somesuperSecret', // should be a large unguessable string
      duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
      activeDuration: 1000 * 60 * 5, // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
        cookie: {
            path: '/', // cookie will only be sent to requests under '/api'
            maxAge: 60000, // duration of the cookie in milliseconds, defaults to duration above
            ephemeral: false, // when true, cookie expires when the browser closes
            httpOnly: true, // when true, cookie is not accessible from javascript
            secure: true // when true, cookie will only be sent over SSL. use key 'secureProxy' instead if you handle SSL not in your node process
        }
    }));

或者,有许多 npm 包可用于会话处理,例如 'express-session'。周围看看。祝你好运!