node.js - session
**redisストレージと組み合わせて、ユーザー情報の検証を追加したいため、ログインモジュールでユーザー情報をクッキーに割り当てるのではなく、sessionにuserIDを付与します**
**次のコードは黄華丹のNodeを抜粋したものです.js開発実戦詳細**
**次のコードは黄華丹のNodeを抜粋したものです.js開発実戦詳細**
/**
*
* @type @exp;session
* @description session
*/
var sessions = {};
var start = function (res, req) {
var conn = {response: res, request: req};
var cookies = {};
if (typeof conn.request.headers.cookie !== 'undefined') { // cookie
conn.request.headers.cookie.split(';').forEach(function(cookie) {
var part = cookie.split('=');
cookies[part[0].trim()] = (part[1] || '').trim();
})
}
else {
cookies.SESSID = 0;
}
var SESSID = cookies.SESSION;
if (typeof sessions[SESSID] !== 'undefined') {
session = sessions[SESSID];
if (session.expires < Date()) {
delete sessions[SESSID];
return newSession(conn.response);
}
else {
var dt = new Date();
dt.setMinutes(dt.getMinutes + 30);
session.expires = dt;
return session[SESSID];
}
}
else {
return newSession(conn.response);
}
}
/**
* @description session
* @param {type} res
* @returns {newSession.session}
*/
function newSession(res) {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz";
var SESSID = '';
for (var i = 0; i < 40; i++) {
var num = Math.floor(Math.random() * chars.length); // 0-39
SESSID += chars.substring(num, num + 1);
}
if (typeof sessions[SESSID] !== 'undefined') { // session ,
return newSession(res);
}
var dt = new Date();
dt.setMinutes(dt.getMinutes() + 30);
var session = {
SESSID: SESSID,
expires: dt
};
sessions[SESSID] = session;
res.setHeader('Set-Cookie', 'SESSID=' + SESSID);
return session;
}
function cleanSession() {
for (sess in sessions) {
if (sess.expires < Date()) {
delete sessions[sess.SESSID];
}
}
}
exports.start = start;