koa-socket icon indicating copy to clipboard operation
koa-socket copied to clipboard

Middleware Not Fired Before "connection" event

Open thealexbaron opened this issue 9 years ago • 4 comments

Pardon my ignorance, but why aren't middlewares fired before the connection event? If this isn't clear, I have an example handy.

Should my client simply trigger a separate event once it has received a connected event or something? Thanks in advance.

thealexbaron avatar Apr 12 '16 22:04 thealexbaron

The connection event is a special event that just passes back the id of the new connection. Unlike socket.io where you'd usually wait for that connection event and then apply your listeners, koa-socket handles the listener application for you, so the connection event loses much of its importance.

I'm going to leave this open though as I think the middleware application code could do with a bit of thought, which would include adding the middleware stack to all events.

mattstyles avatar Apr 14 '16 07:04 mattstyles

To give a bit more context: I have a global session store which I look at to decide if the user is authenticated. Users should receive "authentication error" before they receive the connection.

Does this seem reasonable?

thealexbaron avatar Apr 15 '16 22:04 thealexbaron

For some reason, I wasn't aware that I had access to the handshake. Now I'm doing something like:

io.on( 'connection', co.wrap( function *( ctx, data ) {
    // do stuff with ctx.socket.handshake.headers.cookie to validate authentication
    // if invalid:
    // return ctx.socket.disconnect('You must be logged in to receive a connection');
}))

thealexbaron avatar Apr 18 '16 23:04 thealexbaron

This put me on the right track, but to highlight a bit more the "do stuff with ctx.socket.handshake.headers.cookie to validate authentication", which was not really straight forward, this is how I solved it, by basically using the same mechanism than Koa:

import Cookies from 'cookies'
//....
io.on( 'connection', ctx => {
  const cookies = new Cookies( ctx.socket.handshake, null, {keys: app.keys } )
  if(!cookies.get('koa:sess', {signed: true})) {
    ctx.socket.disconnect()
  }
})

0cv avatar Jun 20 '16 09:06 0cv