Configurare una rotta WebSocket con flag, autenticazione e parametri
Una rotta SOCKET usa gli stessi elementi di una rotta HTTP. Per impostazione predefinita i messaggi sono oggetti JSON. @text rende i messaggi in ingresso semplici stringhe e @binary li rende Buffer. In una rotta di testo send(message) codifica comunque in JSON ciò che invia, quindi una stringa arriva tra virgolette; passa true come secondo argomento, send(message, true), per inviare la stringa così com'è. Un + davanti a SOCKET accetta solo gli utenti che AUTH() approva (altrimenti la connessione viene rifiutata), e i segmenti {name} sono disponibili in self.params. @csrf controlla un token CSRF prima di accettare la connessione: invialo come parametro csrf della query string (/secure/?csrf=...), e vedi la ricetta CSRF per secret_csrf e $.csrf(). Un middleware si collega con #name come su qualsiasi rotta.
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() });
}