Skip to content

Commit

Permalink
fix: fire an error event on middleware failure for non-root namespace (
Browse files Browse the repository at this point in the history
…#1202)

In the following example:

```js
io.use((socket, next) => {
  next(new Error('Auth failed'));
});

// client-side
const socket = io('https://url/custom-namespace');

socket.on('error', (err) => {
  // ...
});
```

The 'error' event wasn't fired on the custom namespace.
  • Loading branch information
darrachequesne authored May 17, 2018
1 parent 3eb047f commit 165ce3e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,10 @@ Socket.prototype.onclose = function (reason) {
*/

Socket.prototype.onpacket = function (packet) {
if (packet.nsp !== this.nsp) return;
var sameNamespace = packet.nsp === this.nsp;
var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';

if (!sameNamespace && !rootNamespaceError) return;

switch (packet.type) {
case parser.CONNECT:
Expand Down
18 changes: 18 additions & 0 deletions test/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,22 @@ describe('socket', function () {
});
});
});

it('should fire an error event on middleware failure from main namespace', function (done) {
var socket = io('/foo', { forceNew: true, query: { 'fail': true } });
socket.on('error', function (err) {
expect(err).to.eql('Auth failed (main namespace)');
socket.disconnect();
done();
});
});

it('should fire an error event on middleware failure from custom namespace', function (done) {
var socket = io('/no', { forceNew: true });
socket.on('error', function (err) {
expect(err).to.eql('Auth failed (custom namespace)');
socket.disconnect();
done();
});
});
});
9 changes: 9 additions & 0 deletions test/support/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ server.of('/abc').on('connection', function (socket) {
socket.emit('handshake', socket.handshake);
});

server.use(function (socket, next) {
if (socket.request._query.fail) return next(new Error('Auth failed (main namespace)'));
next();
});

server.of('/no').use(function (socket, next) {
next(new Error('Auth failed (custom namespace)'));
});

server.on('connection', function (socket) {
// simple test
socket.on('hi', function () {
Expand Down

0 comments on commit 165ce3e

Please sign in to comment.