2012-04-24 23 views
5

我有一個使用Redis作爲會話存儲的Rails 3.2應用程序。現在我將在Node.js中編寫一部分新功能,並且希望能夠在兩個應用程序之間共享會話信息。是否有一種簡單的方法可以在Rails和Node.js應用程序之間共享存儲在Redis中的會話數據?

我可以手動執行的操作是讀取_session_id cookie,然後從名爲rack:session:session_id的Redis密鑰中讀取,但看起來有點像黑客解決方案。

有沒有更好的方式來共享Node.js和Rails之間的會話?

+0

Rails/ruby​​有時使用編組來對對象進行序列化。如果是這樣,你將無法輕鬆地在節點中檢索它們... – sailor 2012-04-24 17:19:25

+0

@sailor如果發生這種情況,我可以保存JSON :) – 2012-04-24 23:11:31

回答

2

我已經做到這一點,但它確實需要使自己的東西

叉首先你需要做的會話密鑰相同的名稱。這是最簡單的工作。

接下來,我創建了redis-store gem的叉子,並修改了編組的位置。我需要在兩邊討論json,因爲爲javascript找到一個ruby樣式元帥模塊並不容易。 The file where I alter marshalling

我還需要更換連接的會話中間件部分。創建的哈希值非常具體,並且與創建的一個軌道不匹配。我需要留下這個給你,因爲可能有更好的方法。我可以分叉連接,但我提取了連接>中間件>會話的副本,並且需要我自己的。

您會注意到原始版本在基本變量中添加了哪些不存在於rails版本中。另外,當rails創建會話而不是節點時,您需要處理這種情況,這就是generateCookie函數的作用。

/***** ORIGINAL *****/ 
// session hashing function 
store.hash = function(req, base) { 
    return crypto 
    .createHmac('sha256', secret) 
    .update(base + fingerprint(req)) 
    .digest('base64') 
    .replace(/=*$/, ''); 
}; 

// generates the new session 
store.generate = function(req){ 
    var base = utils.uid(24); 
    var sessionID = base + '.' + store.hash(req, base); 
    req.sessionID = sessionID; 
    req.session = new Session(req); 
    req.session.cookie = new Cookie(cookie); 
}; 

/***** MODIFIED *****/ 
// session hashing function 
store.hash = function(req, base) { 
    return crypto 
    .createHmac('sha1', secret) 
    .update(base) 
    .digest('base64') 
    .replace(/=*$/, ''); 
}; 

// generates the new session 
store.generate = function(req){ 
    var base = utils.uid(24); 
    var sessionID = store.hash(req, base); 
    req.sessionID = sessionID; 
    req.session = new Session(req); 
    req.session.cookie = new Cookie(cookie); 
}; 

// generate a new cookie for a pre-existing session from rails without session.cookie 
// it must not be a Cookie object (it breaks the merging of cookies) 
store.generateCookie = function(sess){ 
    newBlankCookie = new Cookie(cookie); 
    sess.cookie = newBlankCookie.toJSON(); 
}; 

//... at the end of the session.js file 
    // populate req.session 
    } else { 
    if ('undefined' == typeof sess.cookie) store.generateCookie(sess); 
    store.createSession(req, sess); 
    next(); 
    } 

我希望這對你有效。我花了很多時間來挖掘他們的話題。

我發現一個問題以及在json中存儲的flash消息。希望你找不到那一個。 Flash消息有一個特殊的對象結構,在序列化時json會吹走它。從會話中恢復閃光燈消息時,您可能沒有正確的閃光燈對象。我也需要補丁。

相關問題