【问题标题】:Observing session create-destroy events in nodejs在 nodejs 中观察会话创建-销毁事件
【发布时间】:2021-02-20 04:20:07
【问题描述】:

我正在使用“express-session”和“memorystore”。我想记录会话创建和销毁活动。我的解决方案是,拍摄当前“sessionStorage”的快照,稍后将其与当前“sessionStorage”进行比较,并根据差异报告会话创建、销毁的活动。

let sessionSnapshot;
app.get('/',
function (req, res, next) {
    let currentSnapshot = req.sessionStore;
    let difference = sessionSnapshot.filter(x => !currentSnapshot.includes(x));
    // Report create/destroy activities based on difference.
});

是否有任何其他地方/回调可以跟踪会话创建和销毁事件? 我也在使用“护照”。

【问题讨论】:

    标签: javascript node.js express-session


    【解决方案1】:

    你可以修改这个函数https://github.com/expressjs/session/blob/master/session/memory.js#L93-L96

    const MemoryStore = require('./node_modules/express-session/session/memory.js');
    
    const originalSet = MemoryStore.prototype.set;
    MemoryStore.prototype.set = function set(sessionId, session, callback) {
      console.log('saving session with id %s and parameters', sessionId, session);
      return originalSet.call(this, sessionId, session, callback);
    }
    
    // for destroy
    const original = MemoryStore.prototype.destroy;
    // patched function
    MemoryStore.prototype.destroy = function(sessionId, callback) {
      console.log('destroying session with id %s', sessionId);
      return original.call(this, sessionId, callback)
    }
    
    

    然后,您可以在应用程序中使用这个修补过的内存存储

    app.use(session({
        cookie: { maxAge: 86400000 },
        store: new MemoryStore({
          checkPeriod: 86400000 // prune expired entries every 24h
        }),
        resave: false,
        secret: 'keyboard cat'
    }))
    

    UPD:可能,以类似的方式修补 MemoryStore.prototype.touch 也可能有用

    【讨论】:

    • "set" 不是捕捉会话创建事件的好方法。它被多次调用。但是,当插入会话时,可以将其与唯一缓存进行比较,以查看其是否为新会话。谢谢!
    猜你喜欢
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    相关资源
    最近更新 更多