2
1
mirror of https://github.com/Thream/socketio-jwt.git synced 2024-07-21 09:38:31 +02:00
socketio-jwt/lib/index.js

90 lines
2.2 KiB
JavaScript
Raw Normal View History

2013-06-05 13:38:33 +02:00
var xtend = require('xtend');
function parseCookie(auth, cookieHeader) {
var cookieParser = auth.cookieParser(auth.secret);
var req = {
headers:{
cookie: cookieHeader
}
};
var result;
cookieParser(req, {}, function (err) {
if (err) throw err;
result = req.signedCookies;
});
return result;
}
function authorize(options) {
var defaults = {
2013-06-05 13:38:33 +02:00
passport: require('passport'),
key: 'connect.sid',
secret: null,
store: null,
success: null,
fail: null
};
2012-09-05 20:14:36 +02:00
var auth = xtend({}, defaults, options );
2013-06-30 21:06:21 +02:00
auth.userProperty = auth.passport._userProperty || 'user';
2012-09-05 20:14:36 +02:00
2013-06-05 13:38:33 +02:00
if (typeof auth.cookieParser === 'undefined' || !auth.cookieParser) {
throw new Error('cookieParser is required use connect.cookieParser or express.cookieParser');
}
2012-09-05 20:14:36 +02:00
return function(data, accept){
if (!data.headers.cookie) {
return accept(null, false);
2012-09-05 20:14:36 +02:00
}
2013-06-05 13:38:33 +02:00
data.cookie = parseCookie(auth, data.headers.cookie);
2012-09-05 20:14:36 +02:00
data.sessionID = data.cookie[ auth.key ];
2012-09-05 20:14:36 +02:00
auth.store.get(data.sessionID, function(err, session){
2012-09-05 20:14:36 +02:00
if (err) {
return accept('Error in session store.', false);
} else if (!session) {
return accept(null, false);
2012-09-05 20:14:36 +02:00
}
if( !session[ auth.passport._key ] ){
2012-09-05 20:14:36 +02:00
return accept('passport was not initialized', false);
}
var userKey = session[ auth.passport._key ][ auth.userProperty ];
2013-06-30 21:44:46 +02:00
if(userKey === undefined) {
2013-06-30 21:06:21 +02:00
if(auth.fail)
return auth.fail( data, accept );
else
return accept(null, false);
2012-09-05 20:14:36 +02:00
}
auth.passport.deserializeUser(userKey, function(err, user) {
data[ auth.userProperty ] = user;
if( auth.success ) {
return auth.success( data, accept );
}
accept(null, true);
2012-09-05 20:14:36 +02:00
});
});
};
}
function filterSocketsByUser(socketIo, filter){
var handshaken = socketIo.sockets.manager.handshaken;
return Object.keys(handshaken || {})
.filter(function(skey){
return filter(handshaken[skey].user);
})
.map(function(skey){
return socketIo.sockets.manager.sockets.sockets[skey];
});
}
exports.authorize = authorize;
exports.filterSocketsByUser = filterSocketsByUser;