botmasterai / botmaster-socket.io

The socket.io Botmaster integration
MIT License
8 stars 8 forks source link

Setting botmasterUserId on Server #6

Closed IamLance closed 6 years ago

IamLance commented 6 years ago

Hi is there anyway we can set botmasterUserId on the server it self? We are currently using JWT for decoding id of user we plan to use this as the botmasterUserId

Here is the current code

socketBot.ioServer.use((socket, next) => { jwt.verifyJWT(socket.handshake.query.auth_token, function (err, data) { if (err) next(new Error('Authentication error')); else if (data.idUser === "1safs1") { //idUser should be the botMasterUserId socket.request.user = data; return next(); } next(new Error('Authentication error')); }); });

jdwuarin commented 6 years ago

Hi @IamLance,

The botmasterUserId is set in the queryString. This means that you are able to extract it from there. You could use one of the internal methods from the SocketIoBot called: __getBotamsteruserId (yes, the user part is not camelCased by mistake). But I wouldn't recommend using an internal method actually as I may change them (in this case, I will surely at least rename it to be properly camelCase). You should just use the code that's in there to do so. I've updated your code to reflect this. See below:

const urlParser = require('url');

socketBot.ioServer.use((socket, next) => {
  const urlObject = urlParser.parse(socket.request.url, true);
  jwt.verifyJWT(urlObject.query.botmasterUserId, (err, data) => {
    if (err) next(new Error('Authentication error'))
    else if (data.idUser === '1safs1') {
      socket.request.user = data
      return next()
    }
    next(new Error('Authentication error'))
  })
})

That should do. Feel free to close the issue if that did it.

Cheers,

JD

IamLance commented 6 years ago

@jdwuarin what I want is to set botmasterUserId in the server it self after i decode the JWT token. Since i think that botmasterUserId is the one being used as room id by the botmaster socket io. Thanks for the reply!

jdwuarin commented 6 years ago

Ok got it. Well, if you want to do that, all you would need to do would be to dynamically set the botmasterUserId in this middleware. Because we know that the library will set it based on the socket.request.url, the way around that would be to have this middleware add it to that very socket.request.url string.

Essentially, just add this:

socket.request.url += `?botmasterUserId=${data.idUser}`

To your code. Making sure before hand not to set it on the client side

HTH

IamLance commented 6 years ago

@jdwuarin Thanks and Cheers. It works perfectly. Closing issue now.