-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsessions.js
95 lines (87 loc) · 2.05 KB
/
sessions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* @description Session Management
* WALNUT NodeJS MVC framework
*
* Copy right 2011, [email protected] (XU Kai)
* Date 2011.11.28
*/
var parse = require('querystring').parse;
/**
* @description 设置session过期时间
*/
var EXPIRE_TIME = 3 * 60 * 1000;
/**
* @description 存放服务器端所有session
*/
var _sessions = {};
function genSID(pre) {
pre = (pre)?pre : 'SESSION';
var time = new Date().getTime() + '';
var id = pre + '_' + (time).substring(time.length - 6) + '_' + (Math.round(Math.random() * 1000));
return id;
}
/**
* @description 定时清理过期的session
*/
setInterval(function(){
for (var id in _sessions) {
if (!_sessions.hasOwnProperty(id))
continue;
if (new Date() - _sessions[id].timestamp > EXPIRE_TIME)
delete _sessions[id];
}
}, 1000);
var createSession = function(sID) {
var session = {
SID: sID,
timestamp: new Date()
}
return session;
}
/**
* @description 维护了对session的引用,可进行增删查改操作
* @param {string} sID 当前用户的session ID
* @param {object} _sessions
*/
var context = function(_sessions, sID) {
this.poke = function() {
_sessions[sID].timestamp = new Date();
};
this.destory = function() {
delete _sessions[sID];
};
this.del = function(key) {
this.poke();
delete _sessions[sID][key];
}
this.set = function(key, value) {
this.poke();
_sessions[sID][key] = value;
};
this.get = function(key) {
this.poke();
return _sessions[sID][key];
};
}
/**
* @description 开始session
* @param {object} request
* @param {object} response
* @param {function} process 回调函数
*/
exports.startSession = function(request, response, process) {
var cookies = parse(request.headers.cookie, '; ');
var sID;
for (var i in cookies) {
if (i == 'NODESESSID') {
sID = cookies[i];
break;
}
}
if (!sID || typeof _sessions[sID] == 'undefined') {
var sID = genSID();
_sessions[sID] = createSession(sID);
}
response.setHeader('Set-Cookie', ['NODESESSID=' + sID]);
process.call(new context(_sessions, sID), request, response);
}