forked from wcamarao/session.socket.io
-
Notifications
You must be signed in to change notification settings - Fork 4
/
session.socket.io.js
44 lines (38 loc) · 1.32 KB
/
session.socket.io.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
module.exports = function(io, sessionStore, cookieParser, key) {
key = key || 'connect.sid';
this.of = function(namespace) {
return {
on: function(event, callback) {
return bind.call(this, event, callback, io.of(namespace));
}.bind(this)
};
};
this.on = function(event, callback) {
return bind.call(this, event, callback, io.sockets);
};
this.getSession = function(socket, callback) {
cookieParser(socket.handshake, {}, function (parseErr){
sessionStore.get(findCookie(socket.handshake), function (storeErr, session) {
var err = resolve(parseErr, storeErr, session);
callback(err, session);
});
});
};
function bind(event, callback, namespace) {
namespace.on(event, function (socket) {
this.getSession(socket, function (err, session) {
callback(err, socket, session);
});
}.bind(this));
}
function findCookie(handshake) {
return (handshake.secureCookies && handshake.secureCookies[key])
|| (handshake.signedCookies && handshake.signedCookies[key])
|| (handshake.cookies && handshake.cookies[key]);
}
function resolve(parseErr, storeErr, session) {
if (parseErr) return parseErr;
if (!storeErr && !session) return new Error ('could not look up session by key: ' + key);
return storeErr;
}
};