Configure a WebSocket route with flags, auth and parameters
A SOCKET route takes the same building blocks as an HTTP route. By default messages are JSON objects. @text makes the incoming messages plain strings and @binary makes them Buffers. In a text route send(message) still encodes what it sends as JSON, so a string arrives with quotes; pass true as the second argument, send(message, true), to send the string as it is. A + before SOCKET accepts only users that AUTH() approves (the connection is refused otherwise), and {name} segments are available in self.params. @csrf checks a CSRF token before the connection is accepted: send it as the csrf query string parameter (/secure/?csrf=...), and see the CSRF recipe for secret_csrf and $.csrf(). A middleware is attached with #name as on any route.
secret_csrf : change-this-secret-in-productionAUTH(function($) {
if ($.query.token === 'letmein')
$.success({ id: '1', name: 'Louis' });
else
$.invalid();
});exports.install = function() {
ROUTE('SOCKET /text/ @text', text);
ROUTE('SOCKET /bin/ @binary', binary);
ROUTE('+SOCKET /private/', private_socket);
ROUTE('SOCKET /room/{name}/', room);
ROUTE('SOCKET /secure/ @csrf', secure);
ROUTE('GET /where/', where);
ROUTE('GET /csrf/', csrf);
};
function text() {
this.on('message', function(client, message) {
client.send(typeof(message) + ':' + message.toUpperCase(), true);
});
}
function binary() {
this.on('message', function(client, message) {
client.send(Buffer.from(Buffer.isBuffer(message) ? 'buffer:' + message.length : 'other'));
});
}
function private_socket() {
this.on('open', function(client) {
client.send({ hello: client.user.name });
});
}
function room() {
var self = this;
self.on('open', function(client) {
client.send({ room: self.params.name });
});
}
function secure() {
this.on('open', function(client) {
client.send({ welcome: true });
});
}
function where($) {
$.json({ url: $.hostname('/bin/') });
}
function csrf($) {
$.json({ csrf: $.csrf() });
}