Search code examples
node.jsmqttbrokermosca

How to connect our callback function to the mosca authenticate method?


var mqtt = require('mqtt')
var options = {
  username: 'abc',
  password: 'xyz',
}
var client  = mqtt.connect('mqtt:localhost:1883', options);

function authenteClient() {
      // I need to call this function against the callback at server's 
      // authenticate function.
}

In Above code I am providing username and password in options to this mqtt client.

var mosca = require('mosca');
var ascoltatore = {
    type: 'mongo',
    url: 'mongodb://localhost:27017/mqtt',
    pubsubCollection: 'ascoltatori',
    mongo: {}
    };

var settings = {
  port: 1883,
  backend: ascoltatore 
};
var server = new mosca.Server(settings);
server.on('ready', setup);

function setup() {
  server.authenticate = authenticate;
  console.log('Mosca server is up and running');
}

var authenticate = function(client, username, password, callback) {
   console.log(username, password);
   callback(true);
}

Here in server side in the authenticate function, I need to connect a callback at client side that is being called there as callback(true).


Solution

  • If the client fails the authentication on the broker side it will not connect.

    If it passes it will connect and you can be notified by using the client.on('connect',function(){}) event listener.