-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrails.js
More file actions
60 lines (53 loc) · 1.32 KB
/
Copy pathrails.js
File metadata and controls
60 lines (53 loc) · 1.32 KB
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
/*!
* Rails integration helpers.
*/
var crypto = require('crypto');
/**
* Signs data in the same way as the default SignedCookieJar implementation in Rails.
*/
exports.sign = function(val, secret){
return val + '--' + crypto
.createHmac('sha1', secret)
.update(val)
.digest('hex');
};
/**
* Validates the signature of the signed data.
*/
exports.unsign = function(val, secret){
var str = val.slice(0,val.lastIndexOf('--'));
return exports.sign(str, secret) == val
? str
: false;
};
/**
* Parses and decodes Rails signed session store cookies.
*/
exports.parseSignedCookies = function(obj, secret){
var ret = {};
Object.keys(obj).forEach(function(key){
var val = obj[key]
, signed = exports.unsign(val, secret);
if (signed) {
var buffer = new Buffer(signed, 'base64');
ret[key] = JSON.parse(buffer.toString('utf8'));
delete obj[key];
}
});
return ret;
};
exports.signedCookieParser = function(secret){
return function signedCookieParser(req, res, next) {
var cookies = req.cookies;
if (req.signedRailsCookies) return next();
req.signedRailsCookies = {};
if (cookies && secret) {
try {
req.signedRailsCookies = exports.parseSignedCookies(cookies, secret);
} catch (err) {
return next(err);
}
}
next();
};
};