waffle
Version:
シンプルなWEBアプリケーションフレームワークです。(ALL YOUR NODE ARE BELONG TO US)
141 lines (120 loc) • 3.51 kB
JavaScript
/*
* Copyright 2012 Katsunori Koyanagi
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* @overview クッキーにセッションを保存するストアです。
*/
;
var SessionStore = require("../utils/SessionStore");
function createSessionStore(options) {
var options = options || {};
var key = options.key || "wafflesess";
var password = options.password;
var salt = options.salt || "wafflesess";
var handler = {
clear : function(session) {
if (!password) {
password = session.context.app.name;
}
var cookies = session.context.cookies;
cookies.set(key);
},
store : function(session, values) {
if (!password) {
password = session.context.app.name;
}
var cookies = session.context.cookies;
cookies.set(key, encrypt(password, salt, values));
},
restore : function(session, callback) {
if (!password) {
password = session.context.app.name;
}
var cookies = session.context.cookies;
var data = cookies.get(key);
var values = null;
if (data) {
values = decrypt(password, salt, data);
}
callback(values);
}
};
return new SessionStore(handler, true);
}
function encrypt(password, salt, values) {
var cipher = require("crypto").createCipher("blowfish", password);
var data = "";
data += cipher.update(salt, "UTF-8", "base64");
data += cipher.update(values, "UTF-8", "base64");
data += cipher.final("base64");
return data;
}
function decrypt(password, salt, data) {
var decipher = require("crypto").createDecipher("blowfish", password);
var result = "";
var len = salt.length;
result += decipher.update(data, "base64", "UTF-8");
result += decipher.final("UTF-8");
var s = result.substr(0, len);
if (s === salt) {
return result.substr(len);
}
return null;
}
/**
* クッキーにセッションを保存するストアです。
* <p>
* 関数として使用することも可能です。関数として使用する場合のオプションは以下のとおりです。
* </p>
* <table>
* <tr>
* <th>名前</th>
* <th>値</th>
* <th>デフォルト値</th>
* </tr>
* <tr>
* <td>salt</td>
* <td>暗号化の補助として使用される値</td>
* <td>"wafflesess"</td>
* </tr>
* <tr>
* <td>password</td>
* <td>暗号化のパスワード</td>
* <td>アプリケーション名(この場合アプリケーションを跨いでセッションを共有することはできません。)</td>
* </tr>
* <tr>
* <td>key</td>
* <td>クッキーの名前</td>
* <td>"wafflesess"</td>
* </tr>
* </table>
*
*
* @function
* @name Extensions#cookieStore
* @param {Object}
* options オプション
* @see Filters#session
*/
var store = function(options) {
return {
instance : createSessionStore(options)
};
};
store.instance = createSessionStore(null);
//
// expose
//
module.exports = store;