gpt4 book ai didi

session - Node 、 session 存储删除过期 session

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:11 29 4
gpt4 key购买 nike

我正在尝试为express.js Node 应用程序实现 session 存储我的问题是:

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

这是我到目前为止想出的 CoffeeScript ,使用 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

最佳答案

我对 Node 还很陌生,所以对此持保留态度。

虽然不直接面向 session remember me tutorial on dailyjs我想会有一点帮助。特别是他验证登录 token 的最后一段代码。

此外,我认为最好解析 JSON 并存储为对象。如果您预先进行解析,应该更容易以这种方式访问​​不同的 cookie 位。

关于session - Node 、 session 存储删除过期 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7514798/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com