From ffbc1702bb24b596afbb96407cc6db234a4044a8 Mon Sep 17 00:00:00 2001 From: Martijn Verbakel Date: Tue, 7 Aug 2018 09:12:27 +0200 Subject: [PATCH] Fix #211 (#212) * Added test cases for #211. * Fixed #211. --- lib/client.js | 20 ++++++++++++++------ test/will.js | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/lib/client.js b/lib/client.js index 644589d1..75464ef7 100644 --- a/lib/client.js +++ b/lib/client.js @@ -242,12 +242,20 @@ Client.prototype.close = function (done) { function finish () { if (!that.disconnected && that.will) { - that.broker.publish(that.will, that, function (err) { + that.broker.authorizePublish(that, that.will, function (err) { if (!err) { - that.broker.persistence.delWill({ - id: that.id, - brokerId: that.broker.id - }, nop) + that.broker.publish(that.will, that, done) + } else { + done() + } + + function done (err) { + if (!err) { + that.broker.persistence.delWill({ + id: that.id, + brokerId: that.broker.id + }, nop) + } } }) that.will = null // this function might be called twice @@ -298,4 +306,4 @@ function enqueue (packet) { handle(this.client, packet, this.client._nextBatch) } -function nop () {} +function nop () { } diff --git a/test/will.js b/test/will.js index 0c5bf08b..8caa218a 100644 --- a/test/will.js +++ b/test/will.js @@ -161,3 +161,44 @@ test('delete the will in the persistence after publish', function (t) { cb() } }) + +test('delivers a will with authorization', function (t) { + let authorized = false + var opts = {} + // willConnect populates opts with a will + var s = willConnect(setup(aedes({ authorizePublish: (_1, _2, callback) => { authorized = true; callback(null) } })), opts) + + s.broker.on('clientDisconnect', function () { + t.end() + }) + + s.broker.mq.on('mywill', function (packet, cb) { + t.equal(packet.topic, opts.will.topic, 'topic matches') + t.deepEqual(packet.payload, opts.will.payload, 'payload matches') + t.equal(packet.qos, opts.will.qos, 'qos matches') + t.equal(packet.retain, opts.will.retain, 'retain matches') + t.equal(authorized, true, 'authorization called') + cb() + }) + + s.conn.destroy() +}) + +test('does not deliver a will without authorization', function (t) { + let authorized = false + var opts = {} + // willConnect populates opts with a will + var s = willConnect(setup(aedes({ authorizePublish: (_1, _2, callback) => { authorized = true; callback(new Error()) } })), opts) + + s.broker.on('clientDisconnect', function () { + t.equal(authorized, true, 'authorization called') + t.end() + }) + + s.broker.mq.on('mywill', function (packet, cb) { + t.fail('received will without authorization') + cb() + }) + + s.conn.destroy() +})