Websocket - how to deny a channel / topic subscription

Hi.

I’d like to allow / deny a channel or topic subscription but I can’t find info on how to do this properly.

The user can request any subscription from the client. And the Controller methods are onMessage, onClose and onError. So, there is no method to stop a user from subscribing to any channel or topic they want.

Please help for start working in a Middleware to solve this.

B/R.

This is the way arround I’m implementing:

class ChatController {
  constructor ({ socket, request, auth }) {
    this.socket = socket
    this.request = request
    this.auth = auth
    this.onConnect()
  }

  onConnect(){
    const topic = Chat.getTopic(this.socket.topic) //this removes the "chat:" prefix

    if(this.auth.user.slug !== topic){
      this.socket.emit('error','no permitido')
      this.socket.close()
    }
  }
...
}

It would be great to know how to get the channel and topic in the middleware to do this check on it.

B/R.

You can access the socket as ctx.socket inside the middleware and take the decision to accept or deny the connection

Hi @virk
Thanks for your answer. I tryied your solution but the problem I’m having is that socket is returning an empty object.

class ChatSubscription {

  /**
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Function} next
   */
  async wsHandle ({ request, ctx,socket }, next) {
    console.log(ctx.socket); //Cannot read property 'socket' of undefined
    console.log(this.ctx.socket); //Cannot read property 'socket' of undefined
    console.log(socket); //Socket { channel: null, emitter: Emittery {} }
    await next()
  }
}

ctx is the main object passed to the middleware, use it like follows

async wsHandle ({ request ,socket }, next) {
    socket.emit('error', {})
  }

Hi @virk.

Thanks. I’ll use it as you recommend. Is it possible to get the topic in the middleware? I have tried but I can’t find out how.

BR