diff --git a/.travis.yml b/.travis.yml index 992827c..0173c35 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,7 @@ language: node_js node_js: - - "0.12" - - "0.11" - - "0.10" \ No newline at end of file + - 4 + - 8 + - 10 + - 12 + - node diff --git a/README.md b/README.md index 368ae03..3d6f6f9 100644 --- a/README.md +++ b/README.md @@ -41,9 +41,10 @@ io.sockets .on('connection', socketioJwt.authorize({ secret: 'your secret or public key', timeout: 15000 // 15 seconds to send the authentication message - })).on('authenticated', function(socket) { + })) + .on('authenticated', (socket) => { //this socket is authenticated, we are good to handle more events from it. - console.log('hello! ' + socket.decoded_token.name); + console.log(`hello! ${socket.decoded_token.name}`); }); ``` @@ -52,15 +53,15 @@ io.sockets **Client side** ```javascript -var socket = io.connect('http://localhost:9000'); -socket.on('connect', function () { +const socket = io.connect('http://localhost:9000'); +socket.on('connect', () => { socket - .emit('authenticate', {token: jwt}) //send the jwt - .on('authenticated', function () { + .emit('authenticate', { token: jwt }) //send the jwt + .on('authenticated', () => { //do other things }) - .on('unauthorized', function(msg) { - console.log("unauthorized: " + JSON.stringify(msg.data)); + .on('unauthorized', (msg) => { + console.log(`unauthorized: ${JSON.stringify(msg.data)}`); throw new Error(msg.data.type); }) }); @@ -71,8 +72,8 @@ socket.on('connect', function () { The previous approach uses a second roundtrip to send the jwt. There is a way you can authenticate on the handshake by sending the JWT as a query string, the caveat is that intermediary HTTP servers can log the url. ```javascript -var io = require('socket.io')(server); -var socketioJwt = require('socketio-jwt'); +const io = require('socket.io')(server); +const socketioJwt = require('socketio-jwt'); ``` With socket.io < 1.0: @@ -83,7 +84,7 @@ io.set('authorization', socketioJwt.authorize({ handshake: true })); -io.on('connection', function (socket) { +io.on('connection', (socket) => { console.log('hello!', socket.handshake.decoded_token.name); }); ``` @@ -96,7 +97,7 @@ io.use(socketioJwt.authorize({ handshake: true })); -io.on('connection', function (socket) { +io.on('connection', (socket) => { console.log('hello!', socket.decoded_token.name); }); ``` @@ -108,21 +109,35 @@ For more validation options see [auth0/jsonwebtoken](https://github.com/auth0/no Append the jwt token using query string: ```javascript -var socket = io.connect('http://localhost:9000', { - 'query': 'token=' + your_jwt +const socket = io.connect('http://localhost:9000', { + query: `token=${your_jwt}` }); ``` Append the jwt token using 'Authorization Header' (Bearer Token): ```javascript -var socket = io.connect('http://localhost:9000', { - 'extraHeaders': { Authorization: `Bearer ${your_jwt}` } +const socket = io.connect('http://localhost:9000', { + extraHeaders: { Authorization: `Bearer ${your_jwt}` } }); ``` Both options can be combined or used optionally. +### Authorization Header Requirement + +Require Bearer Tokens to be passed in as an Authorization Header + +**Server side**: + +```javascript +io.use(socketioJwt.authorize({ + secret: 'your secret or public key', + handshake: true, + auth_header_required: true +})); +``` + ### Handling token expiration **Server side** @@ -130,7 +145,7 @@ Both options can be combined or used optionally. When you sign the token with an expiration time (example: 60 minutes): ```javascript -var token = jwt.sign(user_profile, jwt_secret, {expiresIn: 60*60}); +const token = jwt.sign(user_profile, jwt_secret, { expiresIn: 60*60 }); ``` Your client-side code should handle it as below: @@ -138,7 +153,7 @@ Your client-side code should handle it as below: **Client side** ```javascript -socket.on('unauthorized', function(error) { +socket.on('unauthorized', (error) => { if (error.data.type == 'UnauthorizedError' || error.data.code == 'invalid_token') { // redirect user to login page perhaps? console.log('User token has expired'); @@ -159,7 +174,7 @@ No further configuration needed. Add a callback client-side to execute socket disconnect server-side. ```javascript -socket.on('unauthorized', function(error, callback) { +socket.on('unauthorized', (error, callback) => { if (error.data.type == 'UnauthorizedError' || error.data.code == 'invalid_token') { // redirect user to login page perhaps or execute callback: callback(); @@ -201,7 +216,7 @@ Your client-side code should handle it as below: **Client side** ```javascript -socket.on('unauthorized', function(error, callback) { +socket.on('unauthorized', (error, callback) => { if (error.data.type == 'UnauthorizedError' || error.data.code == 'invalid_token') { // redirect user to login page perhaps or execute callback: callback(); @@ -220,13 +235,13 @@ the provided token. **Server side** ```javascript -var SECRETS = { +const SECRETS = { 'user1': 'secret 1', 'user2': 'secret 2' } io.use(socketioJwt.authorize({ - secret: function(request, decodedToken, callback) { + secret: (request, decodedToken, callback) => { // SECRETS[decodedToken.userId] will be used as a secret or // public key for connection user. diff --git a/lib/UnauthorizedError.js b/lib/UnauthorizedError.js index ca197bc..d6184d9 100644 --- a/lib/UnauthorizedError.js +++ b/lib/UnauthorizedError.js @@ -5,7 +5,7 @@ function UnauthorizedError (code, error) { this.data = { message: this.message, code: code, - type: "UnauthorizedError" + type: 'UnauthorizedError' }; } diff --git a/lib/index.js b/lib/index.js index f5d7905..53cf7c7 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,102 +1,107 @@ -var xtend = require('xtend'); -var jwt = require('jsonwebtoken'); -var UnauthorizedError = require('./UnauthorizedError'); +const xtend = require('xtend'); +const jwt = require('jsonwebtoken'); +const UnauthorizedError = require('./UnauthorizedError'); -function noQsMethod(options) { - var defaults = { required: true }; - options = xtend(defaults, options); +function noQsMethod (options) { + const defaults = { required: true }; + options = xtend(defaults, options); - return function (socket) { - var server = this.server || socket.server; + return (socket) => { + 'use strict'; // Node 4.x workaround + const server = this.server || socket.server; if (!server.$emit) { //then is socket.io 1.0 - var Namespace = Object.getPrototypeOf(server.sockets).constructor; + const Namespace = Object.getPrototypeOf(server.sockets).constructor; if (!~Namespace.events.indexOf('authenticated')) { Namespace.events.push('authenticated'); } } - if(options.required){ - var auth_timeout = setTimeout(function () { + let auth_timeout = null; + if (options.required) { + auth_timeout = setTimeout(() => { socket.disconnect('unauthorized'); }, options.timeout || 5000); } - socket.on('authenticate', function (data) { - if(options.required){ + socket.on('authenticate', (data) => { + if (options.required) { clearTimeout(auth_timeout); } + // error handler - var onError = function(err, code) { - if (err) { - code = code || 'unknown'; - var error = new UnauthorizedError(code, { - message: (Object.prototype.toString.call(err) === '[object Object]' && err.message) ? err.message : err - }); - var callback_timeout; - // If callback explicitely set to false, start timeout to disconnect socket - if (options.callback === false || typeof options.callback === "number") { - if (typeof options.callback === "number") { - if (options.callback < 0) { - // If callback is negative(invalid value), make it positive - options.callback = Math.abs(options.callback); - } + const onError = (err, code) => { + if (err) { + code = code || 'unknown'; + const error = new UnauthorizedError(code, { + message: (Object.prototype.toString.call(err) === '[object Object]' && err.message) ? err.message : err + }); + + let callback_timeout; + // If callback explicitly set to false, start timeout to disconnect socket + if (options.callback === false || typeof options.callback === 'number') { + if (typeof options.callback === 'number') { + if (options.callback < 0) { + // If callback is negative(invalid value), make it positive + options.callback = Math.abs(options.callback); } - callback_timeout = setTimeout(function () { - socket.disconnect('unauthorized'); - }, (options.callback === false ? 0 : options.callback)); } - socket.emit('unauthorized', error, function() { - if (typeof options.callback === "number") { - clearTimeout(callback_timeout); - } + + callback_timeout = setTimeout(() => { socket.disconnect('unauthorized'); - }); - return; // stop logic, socket will be close on next tick + }, (options.callback === false ? 0 : options.callback)); } + + socket.emit('unauthorized', error, () => { + if (typeof options.callback === 'number') { + clearTimeout(callback_timeout); + } + socket.disconnect('unauthorized'); + }); + return; // stop logic, socket will be close on next tick + } }; - var token = options.cookie ? socket.request.cookies[options.cookie] : (data ? data.token : undefined); + const token = options.cookie ? socket.request.cookies[options.cookie] : (data ? data.token : undefined); - if(!token || typeof token !== "string") { - return onError({message: 'invalid token datatype'}, 'invalid_token'); + if (!token || typeof token !== 'string') { + return onError({ message: 'invalid token datatype' }, 'invalid_token'); } // Store encoded JWT - socket[options.encodedPropertyName] = data.token; - - var onJwtVerificationReady = function(err, decoded) { + socket[options.encodedPropertyName] = token; + const onJwtVerificationReady = (err, decoded) => { if (err) { return onError(err, 'invalid_token'); } // success handler - var onSuccess = function() { + const onSuccess = () => { socket[options.decodedPropertyName] = decoded; socket.emit('authenticated'); if (server.$emit) { server.$emit('authenticated', socket); } else { //try getting the current namespace otherwise fallback to all sockets. - var namespace = (server.nsps && socket.nsp && - server.nsps[socket.nsp.name]) || - server.sockets; + const namespace = (server.nsps && socket.nsp && + server.nsps[socket.nsp.name]) || + server.sockets; // explicit namespace namespace.emit('authenticated', socket); } }; - if(options.additional_auth && typeof options.additional_auth === 'function') { + if (options.additional_auth && typeof options.additional_auth === 'function') { options.additional_auth(decoded, onSuccess, onError); } else { onSuccess(); } }; - var onSecretReady = function(err, secret) { + const onSecretReady = (err, secret) => { if (err || !secret) { return onError(err, 'invalid_secret'); } @@ -109,26 +114,26 @@ function noQsMethod(options) { }; } -function authorize(options, onConnection) { +function authorize (options, onConnection) { options = xtend({ decodedPropertyName: 'decoded_token', encodedPropertyName: 'encoded_token' }, options); if (typeof options.secret !== 'string' && typeof options.secret !== 'function') { - throw new Error('Provided secret "' + options.secret + '" is invalid, must be of type string or function.'); + throw new Error(`Provided secret ${options.secret} is invalid, must be of type string or function.`); } if (!options.handshake) { return noQsMethod(options); } - var defaults = { - success: function(socket, accept){ + const defaults = { + success: (socket, accept) => { if (socket.request) { accept(); } else { accept(null, true); } }, - fail: function(error, socket, accept){ + fail: (error, socket, accept) => { if (socket.request) { accept(error); } else { @@ -137,19 +142,21 @@ function authorize(options, onConnection) { } }; - var auth = xtend(defaults, options); + const auth = xtend(defaults, options); - return function(socket, accept){ - var token, error; - var handshake = socket.handshake; - var req = socket.request || socket; - var authorization_header = (req.headers || {}).authorization; + return (socket, accept) => { + 'use strict'; // Node 4.x workaround + let token, error; + + const handshake = socket.handshake; + const req = socket.request || socket; + const authorization_header = (req.headers || {}).authorization; if (authorization_header) { - var parts = authorization_header.split(' '); + const parts = authorization_header.split(' '); if (parts.length == 2) { - var scheme = parts[0], - credentials = parts[1]; + const scheme = parts[0], + credentials = parts[1]; if (scheme.toLowerCase() === 'bearer') { token = credentials; @@ -162,8 +169,15 @@ function authorize(options, onConnection) { } } - //get the token from handshake or query string - if (handshake && handshake.query.token){ + // Check if the header has to include authentication + if (options.auth_header_required && !token) { + return auth.fail(new UnauthorizedError('missing_authorization_header', { + message: 'Server requires Authorization Header' + }), socket, accept); + } + + // Get the token from handshake or query string + if (handshake && handshake.query.token) { token = handshake.query.token; } else if (req._query && req._query.token) { @@ -175,7 +189,7 @@ function authorize(options, onConnection) { if (!token) { error = new UnauthorizedError('credentials_required', { - message: 'No Authorization header was found' + message: 'no token provided' }); return auth.fail(error, socket, accept); } @@ -183,8 +197,7 @@ function authorize(options, onConnection) { // Store encoded JWT socket[options.encodedPropertyName] = token; - var onJwtVerificationReady = function(err, decoded) { - + const onJwtVerificationReady = (err, decoded) => { if (err) { error = new UnauthorizedError(err.code || 'invalid_token', err); return auth.fail(error, socket, accept); @@ -195,7 +208,7 @@ function authorize(options, onConnection) { return auth.success(socket, accept); }; - var onSecretReady = function(err, secret) { + const onSecretReady = (err, secret) => { if (err) { error = new UnauthorizedError(err.code || 'invalid_secret', err); return auth.fail(error, socket, accept); @@ -208,13 +221,15 @@ function authorize(options, onConnection) { }; } -function getSecret(request, secret, token, callback) { +function getSecret (request, secret, token, callback) { + 'use strict'; // Node 4.x workaround + if (typeof secret === 'function') { if (!token) { return callback({ code: 'invalid_token', message: 'jwt must be provided' }); } - var parts = token.split('.'); + const parts = token.split('.'); if (parts.length < 3) { return callback({ code: 'invalid_token', message: 'jwt malformed' }); @@ -224,7 +239,7 @@ function getSecret(request, secret, token, callback) { return callback({ code: 'invalid_token', message: 'jwt signature is required' }); } - var decodedToken = jwt.decode(token); + let decodedToken = jwt.decode(token); if (!decodedToken) { return callback({ code: 'invalid_token', message: 'jwt malformed' }); @@ -234,7 +249,7 @@ function getSecret(request, secret, token, callback) { } else { callback(null, secret); } -}; +} exports.authorize = authorize; exports.UnauthorizedError = UnauthorizedError; diff --git a/package.json b/package.json index a2072df..8a6f993 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,8 @@ "express": "~4.15.2", "mocha": "~3.2.0", "request": "~2.81.0", - "serve-static": "^1.12.1", + "serve-static": "^1.13.2", + "q": "^1.5.1", "server-destroy": "~1.0.1", "should": "~11.2.1", "socket.io": "^1.7.3", diff --git a/test/authorizer.test.js b/test/authorizer.test.js index 3e2efc3..fd1b561 100644 --- a/test/authorizer.test.js +++ b/test/authorizer.test.js @@ -1,74 +1,141 @@ -var fixture = require('./fixture'); -var request = require('request'); -var io = require('socket.io-client'); - -describe('authorizer', function () { +const Q = require('q'); +const fixture = require('./fixture'); +const request = require('request'); +const io = require('socket.io-client'); +describe('authorizer', () => { //start and stop the server - before(fixture.start); + before((done) => { fixture.start({ }, done) }); after(fixture.stop); - describe('when the user is not logged in', function () { - - it('should emit error with unauthorized handshake', function (done){ - var socket = io.connect('http://localhost:9000?token=boooooo', { - 'forceNew': true + describe('when the user is not logged in', () => { + it('should emit error with unauthorized handshake', (done) => { + const socket = io.connect('http://localhost:9000?token=boooooo', { + forceNew: true }); - socket.on('error', function(err){ - err.message.should.eql("jwt malformed"); - err.code.should.eql("invalid_token"); + socket.on('error', (err) => { + err.message.should.eql('jwt malformed'); + err.code.should.eql('invalid_token'); socket.close(); done(); }); }); - }); - describe('when the user is logged in', function() { - - beforeEach(function (done) { + describe('when the user is logged in', () => { + before((done) => { request.post({ url: 'http://localhost:9000/login', form: { username: 'jose', password: 'Pa123' }, json: true - }, function (err, resp, body) { + }, (err, resp, body) => { this.token = body.token; done(); - }.bind(this)); + }); }); - it('should do the handshake and connect', function (done){ - var socket = io.connect('http://localhost:9000', { - 'forceNew':true, - 'query': 'token=' + this.token + describe('authorizer disallows query string token when specified in startup options', () => { + before((done) => { + Q.ninvoke(fixture, 'stop') + .then(() => Q.ninvoke(fixture, 'start', { auth_header_required: true })) + .done(done); }); - socket.on('connect', function(){ - socket.close(); - done(); - }).on('error', done); + + after((done) => { + Q.ninvoke(fixture, 'stop') + .then(() => Q.ninvoke(fixture, 'start', { })) + .done(done); + }); + + it('auth headers are supported', (done) => { + const socket = io.connect('http://localhost:9000', { + forceNew: true, + extraHeaders: { Authorization: 'Bearer ' + this.token} + }); + + socket + .on('connect', () => { + socket.close(); + done(); + }) + .on('error', done); + }); + + it('auth token in query string is disallowed', (done) => { + const socket = io.connect('http://localhost:9000', { + forceNew: true, + query: 'token=' + this.token + }); + + socket.on('error', (err) => { + err.message.should.eql('Server requires Authorization Header'); + err.code.should.eql('missing_authorization_header'); + socket.close(); + done(); + }); + }); + }) + + describe('authorizer all auth types allowed', () => { + before((done) => { + Q.ninvoke(fixture, 'stop') + .then(() => Q.ninvoke(fixture, 'start', {})) + .done(done); + }) + + it('auth headers are supported', (done) => { + const socket = io.connect('http://localhost:9000', { + forceNew: true, + extraHeaders: { Authorization: 'Bearer ' + this.token } + }); + + socket + .on('connect', () => { + socket.close(); + done(); + }) + .on('error', done); + }); + + it('should do the handshake and connect', (done) => { + const socket = io.connect('http://localhost:9000', { + forceNew: true, + query: 'token=' + this.token + }); + + socket + .on('connect', () => { + socket.close(); + done(); + }) + .on('error', done); + }); + }); }); - describe('unsgined token', function() { - beforeEach(function () { + describe('unsigned token', () => { + beforeEach(() => { this.token = 'eyJhbGciOiJub25lIiwiY3R5IjoiSldUIn0.eyJuYW1lIjoiSm9obiBGb28ifQ.'; }); - it('should not do the handshake and connect', function (done){ - var socket = io.connect('http://localhost:9000', { - 'forceNew':true, - 'query': 'token=' + this.token - }); - socket.on('connect', function () { - socket.close(); - done(new Error('this shouldnt happen')); - }).on('error', function (err) { - socket.close(); - err.message.should.eql("jwt signature is required"); - done(); + it('should not do the handshake and connect', (done) => { + const socket = io.connect('http://localhost:9000', { + forceNew: true, + query: 'token=' + this.token }); + + socket + .on('connect', () => { + socket.close(); + done(new Error('this shouldnt happen')); + }) + .on('error', (err) => { + socket.close(); + err.message.should.eql('jwt signature is required'); + done(); + }); }); }); - }); diff --git a/test/authorizer_namespaces.test.js b/test/authorizer_namespaces.test.js index 84785b3..69be467 100644 --- a/test/authorizer_namespaces.test.js +++ b/test/authorizer_namespaces.test.js @@ -1,53 +1,45 @@ -var fixture = require('./fixture/namespace'); -var request = require('request'); -var io = require('socket.io-client'); +const fixture = require('./fixture/namespace'); +const request = require('request'); +const io = require('socket.io-client'); -describe('authorizer with namespaces', function () { +describe('authorizer with namespaces', () => { //start and stop the server before(fixture.start); - after(fixture.stop); - describe('when the user is not logged in', function () { + describe('when the user is not logged in', () => { - it('should be able to connect to the default namespace', function (done){ - var socket = io.connect('http://localhost:9000'); - socket.once('hi', done); + it('should be able to connect to the default namespace', (done) => { + io.connect('http://localhost:9000') + .once('hi', () => done()); }); - it('should not be able to connect to the admin namespace', function (done){ - var socket = io.connect('http://localhost:9000/admin'); - socket.once('disconnect', function () { - done(); - }); + it('should not be able to connect to the admin namespace', (done) => { + io.connect('http://localhost:9000/admin') + .once('disconnect', () => done()) + .once('hi admin', () => done(new Error('unauthenticated client was able to connect to the admin namespace'))); }); }); - describe('when the user is logged in', function() { + describe('when the user is logged in', () => { - beforeEach(function (done) { + beforeEach((done) => { request.post({ url: 'http://localhost:9000/login', form: { username: 'jose', password: 'Pa123' }, json: true - }, function (err, resp, body) { + }, (err, resp, body) => { this.token = body.token; done(); - }.bind(this)); + }); }); - it('should do the handshake and connect', function (done){ - var socket = io.connect('http://localhost:9000/admin', { - 'forceNew': true, - }); - var token = this.token; - socket.on('connect', function(){ - socket.on('authenticated', function () { - done(); - }).emit('authenticate', { token: token }); - }); + it('should do the handshake and connect', (done) => { + io.connect('http://localhost:9000/admin', { forceNew: true }) + .on('authenticated', () => done()) + .emit('authenticate', { token: this.token }); }); }); diff --git a/test/authorizer_noqs.test.js b/test/authorizer_noqs.test.js index 53ef9ca..87fe379 100644 --- a/test/authorizer_noqs.test.js +++ b/test/authorizer_noqs.test.js @@ -1,69 +1,56 @@ -var fixture = require('./fixture'); -var request = require('request'); -var io = require('socket.io-client'); +const fixture = require('./fixture'); +const request = require('request'); +const io = require('socket.io-client'); -describe('authorizer without querystring', function () { +describe('authorizer without querystring', () => { //start and stop the server - before(function (done) { - fixture.start({ - handshake: false - } , done); + before((done) => { + fixture.start({ handshake: false }, done); }); after(fixture.stop); - describe('when the user is not logged in', function () { + describe('when the user is not logged in', () => { - it('should close the connection after a timeout if no auth message is received', function (done){ - var socket = io.connect('http://localhost:9000', { - forceNew: true - }); - socket.once('disconnect', function () { - done(); - }); + it('should close the connection after a timeout if no auth message is received', (done) => { + io.connect('http://localhost:9000', { forceNew: true }) + .once('disconnect', () => done()); }); - it('should not respond echo', function (done){ - var socket = io.connect('http://localhost:9000', { - 'forceNew':true, - }); - - socket.on('echo-response', function () { - done(new Error('this should not happen')); - }).emit('echo', { hi: 123 }); + it('should not respond echo', (done) => { + io.connect('http://localhost:9000', { forceNew: true }) + .on('echo-response', () => done(new Error('this should not happen'))) + .emit('echo', { hi: 123 }); setTimeout(done, 1200); }); }); - describe('when the user is logged in', function() { + describe('when the user is logged in', () => { - beforeEach(function (done) { + beforeEach((done) => { request.post({ url: 'http://localhost:9000/login', form: { username: 'jose', password: 'Pa123' }, json: true - }, function (err, resp, body) { + }, (err, resp, body) => { this.token = body.token; done(); - }.bind(this)); + }); }); - it('should do the handshake and connect', function (done){ - var socket = io.connect('http://localhost:9000', { - 'forceNew':true, - }); - var token = this.token; - socket.on('connect', function(){ - socket.on('echo-response', function () { + it('should do the handshake and connect', (done) => { + const socket = io.connect('http://localhost:9000', { forceNew: true }); + + socket + .on('echo-response', () => { socket.close(); done(); - }).on('authenticated', function () { - socket.emit('echo'); - }).emit('authenticate', { token: token }); - }); + }) + .on('authenticated', () => { socket.emit('echo'); }) + .emit('authenticate', { token: this.token }); }); }); diff --git a/test/authorizer_secret_function_noqs.test.js b/test/authorizer_secret_function_noqs.test.js index 912eed0..464d38f 100644 --- a/test/authorizer_secret_function_noqs.test.js +++ b/test/authorizer_secret_function_noqs.test.js @@ -1,76 +1,62 @@ -var fixture = require('./fixture/secret_function'); -var request = require('request'); -var io = require('socket.io-client'); +const fixture = require('./fixture/secret_function'); +const request = require('request'); +const io = require('socket.io-client'); -describe('authorizer with secret function', function () { +describe('authorizer with secret function', () => { //start and stop the server - before(function (done) { + before((done) => { fixture.start({ handshake: false - } , done); + }, done); }); after(fixture.stop); - describe('when the user is not logged in', function () { + describe('when the user is not logged in', () => { - describe('and when token is not valid', function() { - beforeEach(function (done) { + describe('and when token is not valid', () => { + beforeEach((done) => { request.post({ url: 'http://localhost:9000/login', json: { username: 'invalid_signature', password: 'Pa123' } - }, function (err, resp, body) { + }, (err, resp, body) => { this.invalidToken = body.token; done(); - }.bind(this)); + }); }); - it('should emit unauthorized', function (done){ - var socket = io.connect('http://localhost:9000', { - 'forceNew':true, - }); - - var invalidToken = this.invalidToken; - socket.on('unauthorized', function() { - done(); - }); - - socket.on('connect', function(){ - socket - .emit('authenticate', { token: invalidToken + 'ass' }) - }); + it('should emit unauthorized', (done) => { + io.connect('http://localhost:9000', { forceNew: true }) + .on('unauthorized', () => done()) + .emit('authenticate', { token: this.invalidToken + 'ass' }) }); }); }); - describe('when the user is logged in', function() { + describe('when the user is logged in', () => { - beforeEach(function (done) { + beforeEach((done) => { request.post({ url: 'http://localhost:9000/login', json: { username: 'valid_signature', password: 'Pa123' } - }, function (err, resp, body) { + }, (err, resp, body) => { this.token = body.token; done(); - }.bind(this)); + }); }); - it('should do the handshake and connect', function (done){ - var socket = io.connect('http://localhost:9000', { - 'forceNew':true, - }); - var token = this.token; - socket.on('connect', function(){ - socket.on('echo-response', function () { + it('should do the handshake and connect', (done) => { + const socket = io.connect('http://localhost:9000', { forceNew: true }); + + socket + .on('echo-response', () => { socket.close(); done(); - }).on('authenticated', function () { - socket.emit('echo'); }) - .emit('authenticate', { token: token }) - }); + .on('authenticated', () => { socket.emit('echo'); }) + .emit('authenticate', { token: this.token }); }); }); diff --git a/test/authorizer_secret_function_qs.test.js b/test/authorizer_secret_function_qs.test.js index 0d3467e..dd38d97 100644 --- a/test/authorizer_secret_function_qs.test.js +++ b/test/authorizer_secret_function_qs.test.js @@ -1,23 +1,21 @@ -var fixture = require('./fixture/secret_function'); -var request = require('request'); -var io = require('socket.io-client'); +const fixture = require('./fixture/secret_function'); +const request = require('request'); +const io = require('socket.io-client'); -describe('authorizer with secret function', function () { +describe('authorizer with secret function', () => { //start and stop the server before(fixture.start); after(fixture.stop); - describe('when the user is not logged in', function () { + describe('when the user is not logged in', () => { - it('should emit error with unauthorized handshake', function (done){ - var socket = io.connect('http://localhost:9000?token=boooooo', { - 'forceNew': true - }); + it('should emit error with unauthorized handshake', (done) => { + const socket = io.connect('http://localhost:9000?token=boooooo', { forceNew: true }); - socket.on('error', function(err){ - err.message.should.eql("jwt malformed"); - err.code.should.eql("invalid_token"); + socket.on('error', (err) => { + err.message.should.eql('jwt malformed'); + err.code.should.eql('invalid_token'); socket.close(); done(); }); @@ -25,48 +23,54 @@ describe('authorizer with secret function', function () { }); - describe('when the user is logged in', function() { + describe('when the user is logged in', () => { - beforeEach(function (done) { + beforeEach((done) => { request.post({ url: 'http://localhost:9000/login', json: { username: 'valid_signature', password: 'Pa123' } - }, function (err, resp, body) { + }, (err, resp, body) => { this.token = body.token; done(); - }.bind(this)); + }); }); - it('should do the handshake and connect', function (done){ - var socket = io.connect('http://localhost:9000', { - 'forceNew':true, - 'query': 'token=' + this.token + it('should do the handshake and connect', (done) => { + const socket = io.connect('http://localhost:9000', { + forceNew: true, + query: 'token=' + this.token }); - socket.on('connect', function(){ - socket.close(); - done(); - }).on('error', done); + + socket + .on('connect', () => { + socket.close(); + done(); + }) + .on('error', done); }); }); - describe('unsigned token', function() { - beforeEach(function () { + describe('unsigned token', () => { + beforeEach(() => { this.token = 'eyJhbGciOiJub25lIiwiY3R5IjoiSldUIn0.eyJuYW1lIjoiSm9obiBGb28ifQ.'; }); - it('should not do the handshake and connect', function (done){ - var socket = io.connect('http://localhost:9000', { - 'forceNew':true, - 'query': 'token=' + this.token - }); - socket.on('connect', function () { - socket.close(); - done(new Error('this shouldnt happen')); - }).on('error', function (err) { - socket.close(); - err.message.should.eql("jwt signature is required"); - done(); + it('should not do the handshake and connect', (done) => { + const socket = io.connect('http://localhost:9000', { + forceNew: true, + query: 'token=' + this.token }); + + socket + .on('connect', () => { + socket.close(); + done(new Error('this shouldnt happen')); + }) + .on('error', (err) => { + socket.close(); + err.message.should.eql('jwt signature is required'); + done(); + }); }); }); diff --git a/test/fixture/index.js b/test/fixture/index.js index f897021..2f77105 100644 --- a/test/fixture/index.js +++ b/test/fixture/index.js @@ -1,20 +1,21 @@ -var express = require('express'); -var http = require('http'); +'use strict'; // Node 4.x workaround -var socketIo = require('socket.io'); -var socketio_jwt = require('../../lib'); +const express = require('express'); +const http = require('http'); -var jwt = require('jsonwebtoken'); +const socketIo = require('socket.io'); +const socketio_jwt = require('../../lib'); -var xtend = require('xtend'); -var bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const xtend = require('xtend'); +const bodyParser = require('body-parser'); +const enableDestroy = require('server-destroy'); -var server, sio; -var enableDestroy = require('server-destroy'); +let sio; -exports.start = function (options, callback) { +exports.start = (options, callback) => { - if(typeof options == 'function'){ + if (typeof options == 'function') { callback = options; options = {}; } @@ -25,12 +26,13 @@ exports.start = function (options, callback) { handshake: true }, options); - var app = express(); + const app = express(); + const server = http.createServer(app); + sio = socketIo.listen(server); app.use(bodyParser.json()); - - app.post('/login', function (req, res) { - var profile = { + app.post('/login', (req, res) => { + const profile = { first_name: 'John', last_name: 'Doe', email: 'john@doe.com', @@ -38,43 +40,39 @@ exports.start = function (options, callback) { }; // We are sending the profile inside the token - var token = jwt.sign(profile, options.secret, { expiresIn: 60*60*5 }); - + const token = jwt.sign(profile, options.secret, { expiresIn: 60*60*5 }); res.json({token: token}); }); - server = http.createServer(app); - - sio = socketIo.listen(server); if (options.handshake) { sio.use(socketio_jwt.authorize(options)); - sio.sockets.on('echo', function (m) { + sio.sockets.on('echo', (m) => { sio.sockets.emit('echo-response', m); }); } else { sio.sockets .on('connection', socketio_jwt.authorize(options)) - .on('authenticated', function (socket) { - socket.on('echo', function (m) { + .on('authenticated', (socket) => { + socket.on('echo', (m) => { socket.emit('echo-response', m); }); }); } server.__sockets = []; - server.on('connection', function (c) { + server.on('connection', (c) => { server.__sockets.push(c); }); server.listen(9000, callback); enableDestroy(server); }; -exports.stop = function (callback) { +exports.stop = (callback) => { sio.close(); try { server.destroy(); } catch (er) {} callback(); -}; \ No newline at end of file +}; diff --git a/test/fixture/namespace.js b/test/fixture/namespace.js index eff8223..f8e5f8f 100644 --- a/test/fixture/namespace.js +++ b/test/fixture/namespace.js @@ -1,36 +1,37 @@ -var express = require('express'); -var http = require('http'); +'use strict'; // Node 4.x workaround -var socketIo = require('socket.io'); -var socketio_jwt = require('../../lib'); +const express = require('express'); +const http = require('http'); -var jwt = require('jsonwebtoken'); +const socketIo = require('socket.io'); +const socketio_jwt = require('../../lib'); -var xtend = require('xtend'); -var bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const enableDestroy = require('server-destroy'); +const bodyParser = require('body-parser'); -var server, sio; -var enableDestroy = require('server-destroy'); +let sio; /** * This is an example server that shows how to do namespace authentication. * * The /admin namespace is protected by JWTs while the global namespace is public. */ -exports.start = function (callback) { +exports.start = (callback) => { - options = { + const options = { secret: 'aaafoo super sercret', timeout: 1000, handshake: false }; - var app = express(); + const app = express(); + const server = http.createServer(app); + sio = socketIo.listen(server); app.use(bodyParser.json()); - - app.post('/login', function (req, res) { - var profile = { + app.post('/login', (req, res) => { + const profile = { first_name: 'John', last_name: 'Doe', email: 'john@doe.com', @@ -38,23 +39,20 @@ exports.start = function (callback) { }; // We are sending the profile inside the token - var token = jwt.sign(profile, options.secret, { expiresIn: 60*60*5 }); - - res.json({token: token}); + const token = jwt.sign(profile, options.secret, { expiresIn: 60*60*5 }); + res.json({ token: token }); }); - server = http.createServer(app); - sio = socketIo.listen(server); - sio.on('connection', function (socket) { + sio.on('connection', (socket) => { socket.emit('hi'); }); - var admin_nsp = sio.of('/admin'); + const admin_nsp = sio.of('/admin'); admin_nsp.on('connection', socketio_jwt.authorize(options)) - .on('authenticated', function (socket) { + .on('authenticated', (socket) => { socket.emit('hi admin'); }); @@ -63,10 +61,10 @@ exports.start = function (callback) { enableDestroy(server); }; -exports.stop = function (callback) { +exports.stop = (callback) => { sio.close(); try { server.destroy(); } catch (er) {} callback(); -}; \ No newline at end of file +}; diff --git a/test/fixture/secret_function.js b/test/fixture/secret_function.js index 48badd0..1ee17cd 100644 --- a/test/fixture/secret_function.js +++ b/test/fixture/secret_function.js @@ -1,42 +1,44 @@ -var express = require('express'); -var http = require('http'); +'use strict'; // Node 4.x workaround -var socketIo = require('socket.io'); -var socketio_jwt = require('../../lib'); +const express = require('express'); +const http = require('http'); -var jwt = require('jsonwebtoken'); +const socketIo = require('socket.io'); +const socketio_jwt = require('../../lib'); -var xtend = require('xtend'); -var bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const xtend = require('xtend'); +const bodyParser = require('body-parser'); +const enableDestroy = require('server-destroy'); -var server, sio; -var enableDestroy = require('server-destroy'); +let sio; -exports.start = function (options, callback) { - var SECRETS = { +exports.start = (options, callback) => { + const SECRETS = { 123: 'aaafoo super sercret', 555: 'other' }; - if(typeof options == 'function'){ + if (typeof options == 'function') { callback = options; options = {}; } options = xtend({ - secret: function(request, decodedToken, callback) { + secret: (request, decodedToken, callback) => { callback(null, SECRETS[decodedToken.id]); }, timeout: 1000, handshake: true }, options); - var app = express(); + const app = express(); + const server = http.createServer(app); + sio = socketIo.listen(server); app.use(bodyParser.json()); - - app.post('/login', function (req, res) { - var profile = { + app.post('/login', (req, res) => { + const profile = { first_name: 'John', last_name: 'Doe', email: 'john@doe.com', @@ -44,33 +46,28 @@ exports.start = function (options, callback) { }; // We are sending the profile inside the token - var token = jwt.sign(profile, SECRETS[123], { expiresIn: 60*60*5 }); - + const token = jwt.sign(profile, SECRETS[123], { expiresIn: 60*60*5 }); res.json({token: token}); }); - server = http.createServer(app); - - sio = socketIo.listen(server); - if (options.handshake) { sio.use(socketio_jwt.authorize(options)); - sio.sockets.on('echo', function (m) { + sio.sockets.on('echo', (m) => { sio.sockets.emit('echo-response', m); }); } else { sio.sockets .on('connection', socketio_jwt.authorize(options)) - .on('authenticated', function (socket) { - socket.on('echo', function (m) { + .on('authenticated', (socket) => { + socket.on('echo', (m) => { socket.emit('echo-response', m); }); }); } server.__sockets = []; - server.on('connection', function (c) { + server.on('connection', (c) => { server.__sockets.push(c); }); @@ -78,7 +75,7 @@ exports.start = function (options, callback) { enableDestroy(server); }; -exports.stop = function (callback) { +exports.stop = (callback) => { sio.close(); try { server.destroy(); @@ -86,4 +83,3 @@ exports.stop = function (callback) { callback(); }; -