Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware Not Fired Before "connection" event #16

Open
thealexbaron opened this issue Apr 12, 2016 · 4 comments
Open

Middleware Not Fired Before "connection" event #16

thealexbaron opened this issue Apr 12, 2016 · 4 comments

Comments

@thealexbaron
Copy link

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.

@mattstyles
Copy link
Owner

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.

@thealexbaron
Copy link
Author

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
Copy link
Author

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');
}))

@0cv
Copy link

0cv commented Jun 20, 2016

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()
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants