Open thealexbaron opened 8 years ago
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.
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?
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');
}))
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()
}
})
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.