This repository has been archived on 2024-11-11. You can view files and clone it, but cannot push or open issues or pull requests.
socketio-jwt/lib/index.js

74 lines
1.8 KiB
JavaScript
Raw Normal View History

2012-09-05 20:14:36 +02:00
var connectUtils = require('connect').utils,
2013-01-07 14:40:52 +01:00
cookie = require('cookie'),
xtend = require('xtend');
function authorize(options) {
var defaults = {
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 );
auth.userProperty = auth.passport._userProperty || 'user';
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
}
var parsedCookie = cookie.parse(data.headers.cookie);
data.cookie = connectUtils.parseSignedCookies(parsedCookie, auth.secret);
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 ];
if( !userKey && auth.fail ) {
return auth.fail( data, accept );
} else if( !userKey ) {
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;