react-koa-sbase
Version:
fullstack framework, superproject base.
81 lines (74 loc) • 1.7 kB
JavaScript
// Generated by CoffeeScript 1.10.0
var EXPIRES, KEY, cache, handler, session
KEY = 's_id'
EXPIRES = 1000 * 60 * 20
cache = null
session = {
__nowTime: function () {
return (new Date()).getTime()
},
__uuid: function () {
return this.__nowTime() + Math.random()
},
init: function () {
if (!cache) {
return cache = {}
}
},
get: function (id) {
return cache[id]
},
create: function (opt) {
var expire, id, ip, s
if (opt == null) {
opt = {}
}
id = this.__uuid()
ip = opt.ip
expire = this.__nowTime() + EXPIRES
s = {
id: id,
ip: ip,
cookie: {
expire: expire
}
}
return cache[s.id] = s
},
'delete': function (id) {
return delete cache[id]
},
expireUpdate: function (id) {
if (cache[id]) {
return cache[id].cookie.expire = this.__nowTime() + EXPIRES
}
}
}
handler = function (ctx, next) {
var generate, s, sid
session.init()
generate = function (ctx) {
var s
s = session.create()
ctx.cookies.set(KEY, s.id)
return ctx.session = s
}
sid = ctx.cookies.get(KEY)
if (sid) {
s = session.get(sid)
if (s) {
if (s.cookie.expire > session.__nowTime()) {
session.expireUpdate(sid)
ctx.session = s
} else {
generate(ctx)
}
} else {
generate(ctx)
}
} else {
generate(ctx)
}
return next()
}
module.exports = handler