forked from bmeck/session-web-sockets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsws.js
96 lines (93 loc) · 2.97 KB
/
sws.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
96
//exposes a verifier for sessions
//first request an access token over xhr
//then connect the socket with the x-access-token returned as the first message
module.exports = function verifier(options)
{
var defaults = {
ttl: 30*1000//30 seconds before token is invalid
};
for (var k in options) {
defaults[k] = options[k];
}
var session_jar = {};
return {
http:function give_token(req, res, next) {
//x-access-request-token: simple
// -- one time use token for alternative sessions
// -- must be secure connection
//
//returns body with json {
// x-access-token: key ';' time
//}
if (req.headers["x-access-request-token"]) {
if (req.headers["x-access-request-token"].toLowerCase()==="simple") {
var token = Math.random();
while (session_jar[token]) {
token = Math.random();
}
var tmp = Date.now();
session_jar[token] = {
session: req.session,
date: tmp,
id: req.sessionID
};
res.writeHead(200);
res.end('{"x-access-token": "'+token+';'+tmp+'"}');
return;
}
}
//for connect
if (next) {
next();
}
}
, ws: function attach_client(cb) {
return function route_client(client) {
// new client is here!
// verify session or default to none
function verify(token) {
var tmp = session_jar[token];
//if we have a session and the session is not stale
if (tmp && tmp.date > Date.now() - defaults.ttl) {
var session = tmp;
//do a little cleanup for logged in sessions
//TODO: figure out secure cleanup for stale sessions?
delete session_jar[token];
return session;
}
return false;
}
//the first message will send out secret token
//if it does emit("secure")
//otherwise, emit("insecure") and fire emit("message")
client.once('message', function first_verify(msg) {
var session = verify(msg) || false;
if (session) {
client._session = session;
client.session = session.session;
client.emit("secure");
// bind original listeners
client.on = oldon;
for (var i = 0, l = onmsgs.length; i < l; i++) {
client.on('message', onmsgs[i]);
}
}
else {
//insecure does not stop the first message!
client.emit("insecure");
client.connection.end();
}
});
//our mask of functions to add at/after the first message
var onmsgs = [];
var oldon = client.on;
client.on = function(name, fn) {
if (name === "message") onmsgs[onmsgs.length] = fn;
else oldon.apply(this, arguments);
};
//hand over the client to w/e is going on
cb(client);
};
}
};
};