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

86 lines
2.5 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 || '');
data.sessionID = data.cookie[auth.key] || '';
data[auth.userProperty] = {
logged_in: false
};
2012-09-05 20:14:36 +02:00
if(data.xdomain)
return auth.fail(data, 'Can not read cookies from CORS-Requests.', 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;