Search code examples
javascriptnode.jsmqttiotmosca

How to access client object in 'published' callback?


I am using Mosca as embedded MQTT broker with mosquito backend. I am using Mosca primarily as an auth mechanism which can read the jwt tokens and extract some values out of it. I have created my own authorizers to read JWT token in mqtt password field and decode/verify it. After decoding I add the decoded fields to the client object like following

authenticate(client, username, password, next) {
    try {
        const decoded_token = jwt.verify(password.toString(), process.env.SECRET_KEY_BASE);
        client.decoded_token = decoded_token;
        next(null, true);
    } catch(error) {
        console.log('name: %s, error: %s', error.name, error.message);
        console.log('unauthorized!');
        next(null, false);
    }
}

I want to access the decoded_token value in the published callback like following

broker.on('published', (packet, client) => {
    console.log(client.decoded_token);
    console.log('Published', packet.topic, packet.payload);

});

Somehow the above code does not work as expected. I get the following error:

TypeError: Cannot read property 'decoded_token' of undefined

Whereas if instead of console.log(client.decoded_token) I use console.log(client), it works and I can see the decoded_token value in client object.

I have two questions.

  1. Why does the above code not work?
  2. When I store a value in the client object, is the value passed to the client (sensor) which it can send with subsequent requests or is it only stored in local memory?

I am new to MQTT so please excuse me if the questions are too naive :)


Solution

    1. If you can get decoded_token variable in client object. Then We can access it by

    client.decoded_token

    If you are using vs code or Webstrom for development you can use an inbuilt debugger to debug and print client object.

    1. You can't pass a value into a client object for the next call.