From 9389672a9dc7bedb7dec09f57b02c677772d437b Mon Sep 17 00:00:00 2001 From: David Damerell Date: Fri, 24 Oct 2014 17:01:53 +0100 Subject: [PATCH] Added optional authentication and the ability to call another function to further validate the token * Optional authentication is useful when you wish to serve both secure and unsecured services via the same server socket * The ability to specify an additional function to be called to further validate the token is useful when you wish to be able to expire tokens for some reason --- lib/index.js | 45 +++++++++++++++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/lib/index.js b/lib/index.js index bcba250..fba6a66 100644 --- a/lib/index.js +++ b/lib/index.js @@ -13,24 +13,41 @@ function noQsMethod(options) { Namespace.events.push('authenticated'); } } - - var auth_timeout = setTimeout(function () { - socket.disconnect('unauthorized'); - }, options.timeout || 5000); - + + if(options.required){ + var auth_timeout = setTimeout(function () { + socket.disconnect('unauthorized'); + }, options.timeout || 5000); + } + socket.on('authenticate', function (data) { - clearTimeout(auth_timeout); + if(options.required){ + clearTimeout(auth_timeout); + } + jwt.verify(data.token, options.secret, options, function(err, decoded) { - if (err) { + var onError = function(){ return socket.disconnect('unauthorized'); + }; + + if (err) { + onError(); } - - socket.decoded_token = decoded; - socket.emit('authenticated'); - if (server.$emit) { - server.$emit('authenticated', socket); - } else { - server.server.sockets.emit('authenticated', socket); + + var onSuccess = function(){ + socket.decoded_token = decoded; + socket.emit('authenticated'); + if (server.$emit) { + server.$emit('authenticated', socket); + } else { + server.server.sockets.emit('authenticated', socket); + } + }; + + if(options.additional_auth){ + options.additional_auth(decoded, onSuccess, onError); + }else{ + onSuccess(); } }); });