# Protect routes with AUTH

> Authenticate each request with AUTH() and restrict routes to signed-in or anonymous users with the + and - prefixes.

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

`AUTH()` runs for every request. Call `$.success(user)` when the request is authenticated and `$.invalid()` when it is not. The user object is then available as `$.user` in every handler.

Prefix a route with `+` to allow only authenticated users and with `-` to allow only anonymous users. A route without a prefix is open to everybody.

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