# Configurare una rotta WebSocket con flag, autenticazione e parametri

> Scegli il tipo di messaggio con @text o @binary, richiedi un utente autenticato con il prefisso +, controlla un token CSRF con @csrf e leggi i parametri dell'URL nelle rotte SOCKET.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: it
Content-SHA256: 4f79d128ad30c4205521ce203a80db1c9e3a507def0ee08a9806be353b2fed14
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

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.

```text config
secret_csrf : change-this-secret-in-production
```

```js definitions/auth.js
AUTH(function($) {
	if ($.query.token === 'letmein')
		$.success({ id: '1', name: 'Louis' });
	else
		$.invalid();
});
```

```js 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() });
}
```
