# Proteggere le route con AUTH

> Autentica ogni richiesta con AUTH() e limita le route a utenti autenticati o anonimi con i prefissi + e -.

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

`AUTH()` viene eseguita a ogni richiesta. Chiama `$.success(user)` quando la richiesta è autenticata e `$.invalid()` quando non lo è. L'oggetto utente è quindi disponibile come `$.user` in ogni handler.

Anteponi `+` a una route per consentire solo utenti autenticati e `-` per consentire solo utenti anonimi. Una route senza prefisso è aperta a tutti.

```js definitions/auth.js
AUTH(function($) {

	// This demo reads a cookie. In a real app verify a signed session instead.
	var token = $.cookie('auth');

	if (token === 'secret-token')
		$.success({ id: '1', name: 'Peter' });
	else
		$.invalid();
});
```

```js controllers/private.js
exports.install = function() {
	ROUTE('+GET /private/', private_page);
	ROUTE('-GET /login/', login_page);
	ROUTE('GET /whoami/', whoami);
};

function private_page($) {
	$.json({ user: $.user.name });
}

function login_page($) {
	$.json({ message: 'Please sign in' });
}

function whoami($) {
	$.json({ user: $.user ? $.user.name : null });
}
```
