【问题标题】:node, session store remove expired sessions节点,会话存储删除过期会话
【发布时间】:2011-11-22 19:24:38
【问题描述】:

我正在尝试为 express.js 节点应用程序实现会话存储 我的问题是:

  1. 如何删除具有浏览器会话生命周期的 cookie(根据连接文档标记为 expires = false)
  2. 我应该将会话数据存储为 json 字符串还是直接存储为对象

这是我目前想出的咖啡脚本,使用 mongoose,因为这是我为应用程序选择的 orm

    express  = require 'express'
    mongoose = require "mongoose"
    util     = require "util"

    # define session schema
    SessionSchema = new mongoose.Schema
      sid     : { type: String, required: true, unique: true }
      data    : { type: String, default: '{}' }
      expires : { type: Date, index: true }

    module.exports =
    class SessionStore extends express.session.Store
      constructor: (options) ->

        console.log "creating new session store"

        options ?= {}

        # refresh interval
        options.interval ?= 60000 

        options.url ?= "mongodb://localhost/session" 

        # create dedicated session connection
        connection = mongoose.createConnection options.url

        # create session model
        @Session = connection.model 'Session', SessionSchema

        # remove expired session every cycles
        removeExpires = => @Session.remove expires: { '$lte': new Date() }

        setInterval removeExpires, options.interval

      get: (sid, fn) ->
        @Session.findOne sid: sid, (err, session) ->
          if session?
            try
              fn null, JSON.parse session.data
            catch err
              fn err
          else
              fn err, session

      set: (sid, data, fn) ->

        doc =
            sid: sid
            data: JSON.stringify data
            expires:  data.cookie.expires 
        try
          @Session.update sid: sid, doc, upsert: true, fn
        catch err
          fn err

      destroy: (sid, fn) ->
        @Session.remove { sid: sid }, fn

      all: (fn) ->
        @Session.find { expires: { '$gte': new Date() } }, [ 'sid' ], (err, sessions) ->
          if sessions?
            fn null, (session.sid for session in sessions)
          else
            fn err

      clear: (fn) -> @Session.drop fn

      length: (fn) -> @Session.count {}, fn

【问题讨论】:

  • 你见过connect-mongo吗?它总是通过它的 ID 从数据库中获取会话数据,并在需要时在客户端销毁它 (if !expires or Date.now() < expires),这看起来是一个合理的解决方案。

标签: session node.js coffeescript express


【解决方案1】:

我对 node 还很陌生,所以请注意这一点。

虽然不是直接面向会话,但我认为remember me tutorial on dailyjs 会有所帮助。特别是他验证登录令牌的最后一段代码。

另外,我认为解析 JSON 并将其存储为对象会更好。如果您预先处理好解析,应该更容易以这种方式访问​​不同的 cookie 位。

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 2014-07-20
    • 2017-03-16
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多