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

86 lines
2.6 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: function(data, accept){accept(null, true)},
2013-11-15 10:41:53 +01:00
fail: function(data, message, critical, accept){accept(null, false)}
};
2012-09-05 20:14:36 +02:00
2013-11-15 10:47:51 +01: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-11-15 10:47:51 +01:00
if (!auth.cookieParser) {
2013-06-05 13:38:33 +02:00
throw new Error('cookieParser is required use connect.cookieParser or express.cookieParser');
}
2012-09-05 20:14:36 +02:00
return function(data, accept){
data.cookie = parseCookie(auth, data.headers.cookie || '');
2013-11-19 10:45:09 +01:00
data.sessionID = data.query.session_id || data.cookie[auth.key] || '';
data[auth.userProperty] = {
logged_in: false
};
2012-09-05 20:14:36 +02:00
2013-11-19 10:45:09 +01:00
if(data.xdomain && !data.sessionID)
return auth.fail(data, 'Can not read cookies from CORS-Requests. See CORS-Workaround in the readme.', false, accept);
2012-09-05 20:14:36 +02:00
auth.store.get(data.sessionID, function(err, session){
if(err)
return auth.fail(data, 'Error in session store.', true, accept);
if(!session)
return auth.fail(data, 'No session found', false, accept);
if(!session[auth.passport._key])
return auth.fail(data, 'Passport was not initialized', true, accept);
var userKey = session[auth.passport._key][auth.userProperty];
if(!userKey)
return auth.fail(data, 'User not authorized through passport. (User Property not found)', false, accept);
2012-09-05 20:14:36 +02:00
auth.passport.deserializeUser(userKey, function(err, user) {
2013-11-18 15:36:52 +01:00
if (err)
return auth.fail(data, err, true, accept);
if (!user)
return auth.fail(data, "User not found", false, accept);
data[auth.userProperty] = user;
data[auth.userProperty].logged_in = true;
auth.success(data, accept);
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;