ForgeTotal.js 5
pt

Total.js 5

Configurar uma rota WebSocket com flags, autenticação e parâmetros

Total.js 5 · total5@0.0.19 websocketrealtimesecurity Executada com o Total.js 5

Uma rota SOCKET usa os mesmos elementos que uma rota HTTP. Por omissão as mensagens são objetos JSON. @text faz com que as mensagens recebidas sejam strings e @binary que sejam Buffer. Numa rota de texto, send(message) continua a codificar em JSON o que envia, por isso uma string chega com aspas; passe true como segundo argumento, send(message, true), para enviar a string tal como está. Um + antes de SOCKET aceita apenas os utilizadores que AUTH() aprova (caso contrário a ligação é recusada), e os segmentos {name} estão disponíveis em self.params. @csrf verifica um token CSRF antes de aceitar a ligação: envie-o como o parâmetro csrf da query string (/secure/?csrf=...), e veja a receita de CSRF para secret_csrf e $.csrf(). Um middleware liga-se com #name como em qualquer rota.

config
secret_csrf : change-this-secret-in-production
definitions/auth.js
AUTH(function($) {
	if ($.query.token === 'letmein')
		$.success({ id: '1', name: 'Louis' });
	else
		$.invalid();
});
controllers/sockets.js
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() });
}