节点,会话存储删除过期的会话

时间:2011-09-22 12:35:41

标签: session node.js coffeescript express

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

  1. 如何删除具有浏览器会话生命周期的cookie(根据连接文档标记为expires = false)
  2. 我应该将会话数据存储为json字符串还是直接存储为对象
  3. 这是我到目前为止提出的咖啡脚本,使用猫鼬,因为我这是我为应用程序选择的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
    

1 个答案:

答案 0 :(得分:1)

我对节点很陌生,所以请稍等一下。

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

另外,我认为最好将JSON解析并存储为对象。如果您事先处理解析,应该更容易访问不同的cookie位。