# Sign users in with the built-in session auth

> Pass an options object to AUTH() to get signed session cookies, a session store and logout without writing the plumbing.

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

Instead of a function, `AUTH(options)` accepts an options object and installs a complete cookie-session authentication:

- `secret` signs the cookie, `cookie` is its name and `expire` how long a session stays in memory without activity
- `onread(meta, next, $)` loads the user when a valid cookie arrives from a session that is not in memory (for example after a restart); call `next(null, user)`, or `next('not found')` to refuse. **Check that the session still exists in your own store here**, otherwise a copied cookie keeps working after the user signed out
- `onlogout(session)` and `onremove(sessionid)` run when a session is removed: delete it from your store
- `options.authcookie($, sessionid, userid, expiration)` signs the user in: it writes the signed cookie to the response
- `options.logout($)` removes the session and the cookie

Keep the options object in a variable: it is the handle you use to sign users in and out. After that, `$.user` is set and `+` and `-` routes work as in the AUTH recipe.

```js definitions/auth.js
var users = {
	'1': { id: '1', name: 'Anna', password: 'secret' }
};

// sessionid -> userid. In a real app this is a database table.
MAIN.sessions = {};

MAIN.auth = {
	secret: 'change-this-secret',
	cookie: 'forge_session',
	expire: '1 day',
	onread: function(meta, next) {
		var user = users[MAIN.sessions[meta.sessionid]];
		user ? next(null, { id: user.id, name: user.name }) : next('session not found');
	},
	onlogout: function(session) {
		delete MAIN.sessions[session.sessionid];
	},
	onremove: function(sessionid) {
		delete MAIN.sessions[sessionid];
	}
};

AUTH(MAIN.auth);
```

```js controllers/account.js
exports.install = function() {
	ROUTE('POST /login/', login);
	ROUTE('+POST /logout/', logout);
	ROUTE('+GET /me/', me);
};

function login($) {

	var user = $.body.id && $.body.id === '1' && $.body.password === 'secret' ? { id: '1', name: 'Anna' } : null;

	if (!user) {
		$.invalid(401);
		return;
	}

	var sessionid = UID();
	MAIN.sessions[sessionid] = user.id;
	MAIN.auth.authcookie($, sessionid, user.id, '1 day');
	$.json({ name: user.name });
}

function logout($) {
	MAIN.auth.logout($);
	$.json({ ok: true });
}

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