---
title: Authorization
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/authorization/
updated: 2026-11-16T15:41:00.817Z
---

# Authorization

> AUTH(), route flags, roles, cookies and the SESSION() store.

Total.js signs in requests with the `AUTH()` delegate, limits routes with the `+` and `-` flags, and keeps sessions with the built-in cookie session or the `SESSION()` store. The guide [Authorization](../../guides/authorization/) explains how to use them with examples; this page is the exact reference.

Encryption has its own page: [Encryption](../encryption/).

## API

### AUTH(fn)

Type: `method`

Registers the delegate that signs in every request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function($)` | yes |  | The delegate. `$` is the authorization object. |

Returns: `undefined`

The delegate runs for every HTTP request that reaches routing and for every WebSocket connection. It receives an authorization object `$` (see `$.success()`, `$.invalid()` and the properties of `$`). It must call exactly one of `$.success(user)`, `$.invalid()` or `$.cancel()`. Registering a new delegate replaces the previous one.

Passing an object instead of a function starts the built-in cookie session, see `AUTH(options)`.

Example: Sign in with a token header
```js
AUTH(function($) {
	var token = $.headers['x-token'];
	if (token && token === CONF.apitoken)
		$.success({ id: 'api', name: 'API' });
	else
		$.invalid();
});
```

### AUTH(options)

Type: `method`

Starts the built-in cookie session mechanism.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | yes |  | Options and delegates of the session, see the table. |

Returns: `undefined` Methods are added to `options`.

With an object, `AUTH()` registers its own delegate. It reads the session token from the cookie `options.cookie` (or from the header `options.header`), decrypts it with `options.secret`, and keeps the user data in memory for `options.expire`. When the data is not cached, it calls `options.onread()`. Requests waiting for the same session share one `onread()` call.

`AUTH()` does not return anything, but it adds methods to the object you pass: `logout()`, `update()`, `refresh()`, `sign()`, `authcookie()` and `auth()` (the delegate itself). Keep a reference to the object.

| Option | Type | Description |
| --- | --- | --- |
| `secret` | String | Key for encrypting the token. Always set it. |
| `cookie` | String | Name of the cookie with the token. |
| `header` | String | Name of a request header with the token, used when the cookie is missing. Write it in lower case. |
| `expire` | String | How long user data stays in memory. Default `'5 minutes'`. |
| `strict` | Boolean | The cached session works only with the same user agent. Default `true`. |
| `ddos` | Number | Failed attempts per IP address before every request of that IP is invalid. The counters reset with each cleaning. |
| `cleaner` | Number | Cleaning interval in minutes. Default `5`. |
| `options` | Object | Cookie options used when the cookie is written or removed. |
| `onread` | Function(meta, next, $) | Loads the user data, see `options.onread`. |
| `onsession` | Function(session, $, init) | Called when a session is found. Return `true` to stop the processing; then answer `$` yourself. `init` is `true` when the data was just loaded. |
| `onauthorize` | Function($) | Called first for every request. Return `true` to skip the built-in processing; then answer `$` yourself. |
| `onlogout` | Function(session) | Called by `logout()`. |
| `onfree` | Function(meta) | Called after cleaning with `{ sessions: Array, users: Array }`: the removed session IDs and the user IDs without any live session. |
| `onddos` | Function($) | Called when a blocked IP address makes a request. |
| `locale` | Function(data, req) | Returns the language of the request. `data` is `null` for anonymous visitors. |

An invalid or unknown token removes the cookie.

Example: Built-in session
```js
var opt = {};
opt.secret = 'a-long-random-key';
opt.cookie = 'session';
opt.expire = '10 minutes';
opt.onread = function(meta, next) {
	NOSQL('users').one().where('id', meta.userid).callback(next);
};
AUTH(opt);
MAIN.auth = opt;
```

Example: Language of the user
```js
opt.locale = function(data, req) {
	return data ? data.language : '';
};
```

### options.onread = function(meta, next, $)

Type: `delegate`

Loads the user data for a session token in the built-in session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |
| `next` | `Function(err, data)` | yes |  | Callback with the user data. |
| `$` | `Object` | yes |  | The authorization object. |

Called when a valid token has no cached data. `meta` contains `sessionid`, `userid`, `ip` and `ua`. Call `next(err, data)`: with data, the session is cached for `options.expire` and the request is signed in; without data, the cookie is removed and the request is anonymous. Check in your database that the session still exists, so a signed-out session cannot be used again.

Example: Read the user
```js
opt.onread = function(meta, next) {
	NOSQL('sessions').one().where('id', meta.sessionid).callback(function(err, session) {
		if (session)
			NOSQL('users').one().where('id', meta.userid).callback(next);
		else
			next();
	});
};
```

### options.authcookie($, sessionid, userid, expiration, [cookieoptions])

Type: `method`

Writes the session cookie of the built-in session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller|Object` | yes |  | Object with a `cookie()` method. |
| `sessionid` | `String` | yes |  | Your session ID. |
| `userid` | `String` | yes |  | The user ID. |
| `expiration` | `String|Date` | yes |  | Expiration of the cookie, for example `'1 month'`. |
| `cookieoptions` | `Object` | no | `options.options` | Cookie options. |

Signs `sessionid` and `userid` with `options.sign()` and writes them to the cookie `options.cookie`. Call it after you check the credentials and store the session. `options.sign(sessionid, userid)` returns the same token without writing a cookie, for clients that send it in the header `options.header`. `$` is anything with a `cookie()` method: a controller, a schema `$` or the authorization `$`.

Example: Sign in
```js
var sessionid = UID();
NOSQL('sessions').insert({ id: sessionid, userid: user.id });
MAIN.auth.authcookie(self, sessionid, user.id, '1 month');
self.redirect('/');
```

### options.logout($)

Type: `method`

Signs out the current session of the built-in session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller|String` | yes |  | The controller or the session ID. |

Returns: `Boolean` `true` when a session was removed.

`$` is the controller (or another object with `sessionid`), or a session ID string. Removes the session from memory, calls `options.onlogout(session)` and removes the cookie when `$` has a `cookie()` method. Returns `true` when the session was found. Delete the session from your database in `onlogout`, otherwise `onread` can load it again.

Example: Sign out
```js
function logout() {
	var self = this;
	MAIN.auth.logout(self);
	self.redirect('/');
}
```

### options.update(userid, fn)

Type: `method` · Since: `0.0.56`

Changes the cached data of all sessions of a user in the built-in session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `userid` | `String` | yes |  | The user ID. |
| `fn` | `Function(data, session)` | yes |  | Called for each session. |

Returns: `Number` Count of sessions.

Calls `fn(data, session)` for every cached session of `userid`, so you can change the user object in place.

Example: Rename the user
```js
MAIN.auth.update(user.id, function(data) {
	data.name = model.name;
});
```

### options.refresh(userid, [exceptsessionid])

Type: `method` · Since: `0.0.56`

Drops the cached data of a user in the built-in session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `userid` | `String` | yes |  | The user ID. |
| `exceptsessionid` | `String` | no |  | A session ID to keep. |

Returns: `Number` Count of removed sessions.

Removes the user's sessions from memory, so the next request calls `onread` again. The cookies stay valid. Pass `exceptsessionid` to keep one session, for example the current one.

Example: Reload after a change
```js
MAIN.auth.refresh(user.id, self.sessionid);
```

### $

Type: `class`

The `$` object the AUTH() delegate receives.

Properties (read-only): `$.req`, `$.res`, `$.ip`, `$.ua`, `$.url` (lower-case path), `$.uri`, `$.path`, `$.split`, `$.language`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.mobile` and `$.websocket` (`true` for a WebSocket connection).

Methods: `$.success(user)`, `$.invalid()`, `$.cancel()`, `$.cookie()`, `$.done()`, `$.audit(message, [type])` and `$.next(is, user)` (alias `$.callback()`). Only the first answer counts; later calls are ignored.

In a WebSocket connection `$.res` is the WebSocket client, so you cannot write cookies.

Example: Different rules for WebSockets
```js
AUTH(function($) {
	var token = $.websocket ? $.query.token : $.cookie('token');
	var id = DECRYPTREQ($.req, token, 'auth');
	if (id)
		$.success({ id: id });
	else
		$.invalid();
});
```

### $.success(user)

Type: `method`

Signs the request in with a user object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `user` | `Object` | yes |  | The signed-in user. |

The user object becomes `controller.user`, `$.user` in schemas and `client.user` in WebSockets. Routes with `+` match; routes with `-` do not. `$.done([user])` returns a callback `function(is, user)` for asynchronous code: a truthy `is` (or `null` with a user) signs the request in, an `Error` marks it as anonymous.

Example: Sign in
```js
$.success({ id: user.id, name: user.name, roles: user.roles });
```

### $.invalid([user])

Type: `method`

Marks the request as not signed in.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `user` | `Object` | no |  | Optional data for an anonymous visitor. |

Routes with `-` and routes without a flag match. A user object passed here is still set as `controller.user`, but the request counts as anonymous.

Example: No token
```js
if (!token) {
	$.invalid();
	return;
}
```

### $.cancel()

Type: `method` · Since: `0.0.89`

Stops the authorization and the request processing.

Returns: `AuthOptions` The same object.

Use it when you answer the request yourself in the delegate, for example with a redirect through `$.res`. After `$.cancel()` the framework does not route the request.

Example: Redirect old domains
```js
AUTH(function($) {
	if ($.headers.host === 'old.example.com') {
		$.cancel();
		$.res.redirect('https://www.example.com' + $.url);
		return;
	}
	$.invalid();
});
```

### $.cookie(name, [value], [expire], [options])

Type: `method`

Reads or writes a cookie inside the AUTH() delegate.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Cookie name. |
| `value` | `String|null` | no |  | New value; `null` removes the cookie. |
| `expire` | `String|Date` | no |  | Expiration, for example `'1 month'`. |
| `options` | `Object` | no |  | Cookie options, see `controller.cookie()`. |

Returns: `String|AuthOptions` The value when reading, otherwise `$`.

With only `name`, returns the cookie value (an empty string when it is missing). With `value`, writes the cookie. With `value` set to `null`, removes it. The same method exists on schema and operation `$` objects.

Example: Remove an invalid cookie
```js
var token = $.cookie('token');
if (token && !DECRYPTREQ($.req, token, 'auth')) {
	$.cookie('token', null);
	$.invalid();
	return;
}
```

### ROUTE('+GET /url/') / ROUTE('-GET /url/')

Type: `config`

Limits a route to signed-in or anonymous visitors.

A URL that starts with `+` (or `🔒`) matches only requests signed in with `$.success()`. A URL that starts with `-` matches only requests marked with `$.invalid()`. A route without a flag matches both. In the flags array, `'authorize'`, `'authorized'` and `'logged'` mean `+`; `'unauthorize'`, `'unauthorized'` and `'unlogged'` mean `-`.

The same URL can have a `+` and a `-` route. When the only route is for the other state, the response is `401`; with no route at all, `404`. WebSocket routes use the same prefixes; a WebSocket that does not match is closed with code `4001`.

The flags are checked only when `AUTH()` is registered.

Example: One URL, two routes
```js
exports.install = function() {
	ROUTE('+GET /', 'dashboard');
	ROUTE('-GET /', 'login');
	ROUTE('+SOCKET /live/', live);
};
```

Example: Flags in an array
```js
ROUTE('GET /account/', account, ['authorize']);
```

### ROUTE('GET /url/', action, ['@role'])

Type: `config`

Marks a route with roles.

A flag that starts with `@` is a role. It is lower-cased and kept in `controller.route.flags`, and the route needs a signed-in user (as with `+`) unless you add `-`. Total.js does not compare roles with the user: check them in the action, for example with `UNAUTHORIZED()`.

Example: Check the role of the route
```js
ROUTE('GET /admin/', admin, ['@admin']);

function admin() {
	var self = this;
	if (UNAUTHORIZED(self, 'admin'))
		return;
	self.view('admin');
}
```

### UNAUTHORIZED($, role, [role2], ...)

Type: `method`

Checks the roles of the signed-in user and answers 401 when none matches.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller|Object` | yes |  | A controller or a schema/operation `$`. |
| `role` | `String` | yes |  | One or more roles as separate arguments. |

Returns: `Boolean` `true` when the request was refused.

Compares the roles with `$.user.permissions` or `$.user.roles` (an array, or an object whose keys are roles). Returns `false` when the user has one of the roles or when `user.sa` or `user.su` is truthy. Otherwise calls `$.invalid(401)` and returns `true`, also when there is no user.

Example: In a schema
```js
schema.setRemove(function($) {
	if (UNAUTHORIZED($, 'admin', 'editor'))
		return;
	NOSQL('articles').remove().where('id', $.id).callback($.done());
});
```

### BLOCKED($, [limit], [expiration])

Type: `method`

Counts attempts from an IP address and tells when to block it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller|Object` | yes |  | Object with `ip`. |
| `limit` | `Number` | no | `5` | Allowed attempts. |
| `expiration` | `String` | no | `'15 minutes'` | How long the counter lives. |

Returns: `Boolean` `true` when the IP address is blocked.

Use it to slow down password guessing. Each call adds one attempt for `$.ip`. Returns `true` when the count is above `limit`. With `limit` set to `-1` or `null`, clears the counter of that IP address, for example after a successful sign-in.

Example: Login form
```js
function login() {
	var self = this;
	if (BLOCKED(self, 10)) {
		self.invalid('error-blocked');
		return;
	}
	// ... on success:
	BLOCKED(self, -1);
}
```

### controller.user

Type: `property`

The user object of a signed-in request.

Returns: `Object`

Set by `$.success(user)`. It is `undefined` for anonymous requests. You can assign it. In schemas and operations read `$.user`; in WebSockets `client.user`.

Example: Use the user
```js
function account() {
	var self = this;
	self.view('account', { name: self.user.name });
}
```

### $.user

Type: `property`

The signed-in user inside schemas and operations.

Returns: `Object`

Returns `controller.user` of the request, or `null` when the operation runs without a controller.

Example: Owner of a record
```js
schema.setInsert(function($, model) {
	model.userid = $.user.id;
	NOSQL('notes').insert(model).callback($.done());
});
```

### controller.session / controller.sessionid

Type: `property`

The session object and the session ID of the request.

Returns: `Object / String`

Both read and write `req.session` and `req.sessionid`. The built-in `AUTH(options)` sets them to the cached session (`{ sessionid, userid, data, ua, expire }`) and its ID. `SESSION().getcookie()`, `gettoken()`, `setcookie()` and `settoken()` set `sessionid`. The same properties exist on schema `$` objects and WebSocket clients.

Example: Sign out of a SESSION() store
```js
session.remove(self.sessionid);
```

### controller.cookie(name, [value], [expires], [options])

Type: `method`

Reads or writes a cookie.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Cookie name. |
| `value` | `String` | no |  | New value. |
| `expires` | `String|Date|Object` | no |  | Expiration, or the options. |
| `options` | `Object` | no |  | Cookie options. |

Returns: `String|Controller` The value when reading, otherwise the controller.

With only `name`, returns the decoded value of the cookie, or an empty string. With `value`, adds a `Set-Cookie` header and returns the controller. To remove a cookie, write an empty value with a past expiration such as `'-1 day'`.

`expires` is a `Date` or a string like `'1 month'`. Instead of `expires` you can pass the options object, which then may contain `expires`.

| Option | Description |
| --- | --- |
| `domain` | Cookie domain. |
| `path` | Cookie path. Default `/`. |
| `secure` | `true` adds `Secure`. Default `CONF.default_cookies_secure`. |
| `httponly` | `true` adds `HttpOnly`. |
| `samesite` or `security` | `'Lax'`, `'Strict'` or `'None'` (or `1` for Lax, `2` for Strict). Default `CONF.default_cookies_samesite`. |

A cookie is not written once the response has been sent.

Example: Write and read
```js
self.cookie('theme', 'dark', '1 year', { httponly: true });
var theme = self.cookie('theme');
```

Example: Remove
```js
self.cookie('token', '', '-1 day');
```

### res.cookie(name, value, [expires], [options])

Type: `method`

Writes a cookie to the HTTP response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Cookie name. |
| `value` | `String` | yes |  | Value. |
| `expires` | `String|Date|Object` | no |  | Expiration, or the options. |
| `options` | `Object` | no |  | Cookie options. |

Returns: `Response`

The low-level method behind `controller.cookie()`, with the same options. Use it where you only have the response, for example `$.res` in the AUTH() delegate. `req.cookie(name)` reads a cookie from the request.

Example: From the delegate
```js
$.res.cookie('visited', '1', '1 day');
var old = $.req.cookie('visited');
```

### default_cookies_samesite : Lax

Type: `config`

Default SameSite attribute of cookies.

Returns: `String`

Used when a cookie has no `samesite`/`security` option. Default `'Lax'`.

Example: config
```js
// /config
default_cookies_samesite : Strict
```

### default_cookies_secure : false

Type: `config`

Adds the Secure attribute to every cookie.

Returns: `Boolean`

Used when a cookie has no `secure` option. Default `false`. Turn it on when the app runs only on HTTPS.

Example: config
```js
// /config
default_cookies_secure : true
```

### SESSION([name])

Type: `method`

Returns a named session store.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `'default'` | Name of the store. |

Returns: `Session` The store.

The first call creates the store and loads its saved sessions; later calls return the same instance. The default name is `default`, saved in `databases/sessions.txt`; other names use `databases/sessions_NAME.txt`. The file is written 10 seconds after a change and holds only the metadata of each session: `sessionid`, `id`, `expire`, `used`, `created`, `note` and `settings`. The user data stays in memory; after a restart the store loads it with `session.ondata`.

A session item has the properties `sessionid`, `id` (user ID), `data`, `expire`, `used`, `created`, `note`, `settings` and `released`. Store properties: `name` and `items` (a `Map` of items by session ID).

Expired sessions are removed every 10 minutes. In a cluster, changes are sent to the other processes.

Example: Create a store
```js
var session = SESSION();
session.ondata = function(meta, next) {
	NOSQL('users').one().where('id', meta.id).callback(next);
};
```

### session.ondata = function(meta, next)

Type: `delegate`

Loads the data of a session that is not in memory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | The session item: `sessionid`, `id`, `note`, `settings`... |
| `next` | `Function(err, data)` | yes |  | Callback with the data. |

Called by `get()`, `getcookie()` and `gettoken()` when the item has no data: after a restart or after the data was released. `meta` is the session item. Call `next(err, data)`. Calls for the same user ID wait for one load. Without `ondata`, `release()`, `release2()` do nothing.

Example: Load the user
```js
session.ondata = function(meta, next) {
	NOSQL('users').one().where('id', meta.id).callback(next);
};
```

### session.onremove = function(item)

Type: `event`

Called when a session is removed or expires.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `item` | `Object` | yes |  | The session item. |

Also called by `clear()` and `remove2()`. The sibling delegate `session.onrelease = function(item)` is called when the data of a session is released from memory.

Example: Log removed sessions
```js
session.onremove = function(item) {
	item && console.log('Session ended:', item.sessionid);
};
```

### session.setcookie(res, opt, [callback])

Type: `method`

Creates a session and writes its cookie.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `res` | `Controller|Object` | yes |  | Where the cookie is written. |
| `opt` | `Object` | yes |  | Options, see the table. |
| `callback` | `Function(err, data, meta)` | no |  | Called after the session is created. |

Calls `session.set()` and writes an encrypted cookie (made with `ENCRYPTREQ()`) with the session ID and the user ID. `res` can be a controller, a schema `$`, the authorization `$` or a response.

| Option | Description |
| --- | --- |
| `name` | Cookie name. |
| `sessionid` | Session ID. Default `UID()`. |
| `id` | User ID. |
| `data` | Session data. |
| `expire` | Expiration, for example `'1 month'`. |
| `key` (or `secret`) | Encryption key. |
| `strict` | Bind the cookie to the IP address too. Default `false`. |
| `note` | A note, for example the user agent. |
| `settings` | A string with settings. |
| `options` | Cookie options. Default `{ httponly: true, security: 'lax' }`. |

Example: Sign in
```js
session.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() {
	self.redirect('/');
});
```

### session.getcookie(req, opt, callback, [param])

Type: `method`

Reads the session from the cookie of a request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `req` | `Object` | yes |  | The authorization `$`, a controller or a request. |
| `opt` | `Object` | yes |  | Options, see the table. |
| `callback` | `Function(err, data, meta, init, param)` | yes |  | `data` is the session data, `meta` the item, `init` is `true` when `ondata` loaded the data. |
| `param` | `Any` | no |  | A value passed to the callback. |

Decrypts the cookie with `DECRYPTREQ()` and calls `session.get()`. `req` can be the authorization `$`, a controller or a request. Tokens shorter than 20 characters are ignored. An invalid cookie is removed, and with `ddos` each failed attempt is counted for the IP address.

| Option | Description |
| --- | --- |
| `name` | Cookie name. |
| `expire` | Extends the session and the cookie by this time. |
| `key` (or `secret`) | Encryption key. |
| `extendcookie` | Extend the cookie with `expire`. Default `true`. |
| `removecookie` | Remove an invalid cookie. Default `true`. |
| `options` | Cookie options. |
| `ddos` | Failed attempts per IP address before the cookie is not checked anymore. |

Example: In AUTH()
```js
AUTH(function($) {
	session.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) {
		if (data)
			$.success(data);
		else
			$.invalid();
	});
});
```

### session.settoken(res, opt, [callback])

Type: `method`

Creates a session and returns a token instead of a cookie.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `res` | `Object` | yes |  | A controller, a schema `$` or a response. |
| `opt` | `Object` | yes |  | Options of `setcookie()`. |
| `callback` | `Function(err, token, data, meta)` | no |  | Receives the token. |

Takes the options of `setcookie()` except `name` and `options`, and passes the encrypted token to the callback. Send the token to the client, for example in JSON.

Example: API sign-in
```js
session.settoken(self, { id: user.id, data: user, expire: '7 days', key: 'session-key' }, function(err, token) {
	self.json({ token: token });
});
```

### session.gettoken(req, opt, callback, [param])

Type: `method`

Reads the session from a token.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `req` | `Object` | yes |  | The authorization `$` or a request. |
| `opt` | `Object` | yes |  | Options. |
| `callback` | `Function(err, data, meta, init, param)` | yes |  | Called with the session. |
| `param` | `Any` | no |  | A value passed to the callback. |

Like `getcookie()`, with the token in `opt.token`. Options: `token`, `expire`, `key` (or `secret`) and `ddos`.

Example: Token header
```js
AUTH(function($) {
	session.gettoken($, { token: $.headers['x-token'], key: 'session-key' }, function(err, data) {
		if (data)
			$.success(data);
		else
			$.invalid();
	});
});
```

### session.set(sessionid, [id], data, expire, [note], [settings], [callback])

Type: `method`

Creates or replaces a session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sessionid` | `String` | yes |  | Session ID. |
| `id` | `String` | no |  | User ID. |
| `data` | `Object` | yes |  | Session data. |
| `expire` | `String` | yes |  | Expiration. |
| `note` | `String` | no |  | A note. |
| `settings` | `String` | no |  | Settings. |
| `callback` | `Function(err, data, meta)` | no |  | Called after the change. |

`id` is the user ID; it can be left out when `data` is an object. `expire` is required, for example `'1 month'`. `session.set2(id, data, [expire], [note], [settings], [callback])` replaces the data of all loaded sessions of user `id` and passes the count of updated sessions.

Example: Create a session
```js
session.set(UID(), user.id, user, '1 month', $.ua);
```

### session.get(sessionid, [expire], callback)

Type: `method`

Reads a session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sessionid` | `String` | yes |  | Session ID. |
| `expire` | `String` | no |  | Extends the session by this time. |
| `callback` | `Function(err, data, meta, init)` | yes |  | Called with the session. |

Returns the data through the callback and updates `used`. With `expire`, the session is extended. An expired session is removed. When the data is not in memory, `ondata` loads it and `init` is `true`. `session.get2(id, callback(err, items))` returns all live items of user `id`.

Example: Read
```js
session.get(self.sessionid, function(err, data, meta) {
	self.json(data);
});
```

### session.update(sessionid, data, [expire], [note], [settings], [callback])

Type: `method`

Changes a session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sessionid` | `String` | yes |  | Session ID. |
| `data` | `Object` | yes |  | New data. |
| `expire` | `String` | no |  | New expiration from now. |
| `note` | `String` | no |  | New note. |
| `settings` | `String` | no |  | New settings. |
| `callback` | `Function` | no |  | Called after the change. |

Replaces the data only when it is loaded; `note`, `settings` and `expire` change always. The callback receives `(null, data, meta)`, or no arguments when the session is missing or not loaded. `session.update2(id, data, [expire], [note], [settings], [callback])` does the same for all sessions of user `id` and passes the count of updated sessions.

Example: Update all sessions of a user
```js
session.update2(user.id, user, function(err, count) {
	console.log('Updated', count);
});
```

### session.remove(sessionid, [callback])

Type: `method`

Removes a session.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sessionid` | `String|Object` | yes |  | Session ID or item. |
| `callback` | `Function(err, item)` | no |  | Called after the removal. |

`sessionid` can also be a session item. The callback receives `(null, item)`. `session.remove2(id, [callback])` removes all sessions of user `id` and passes the count, for example to sign a user out everywhere.

Example: Sign out
```js
session.remove(self.sessionid);
self.cookie('sid', '', '-1 day');
```

Example: Sign out everywhere
```js
session.remove2(user.id);
```

### session.release([sessionid], [expire], [callback])

Type: `method`

Frees the data of a session from memory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sessionid` | `String|Object` | no |  | Session ID or item. |
| `expire` | `String` | no |  | Used by `release2()`. |
| `callback` | `Function(err, count)` | no |  | Called with the count. |

The session stays valid; the next read loads the data again with `ondata`. Without `sessionid` (or with `null`), releases every session and passes the count. `session.release2(id, [expire], [callback])` releases all sessions of user `id` and, with `expire`, sets their new expiration. `session.releaseunused(lastusage, [callback])` releases sessions not used for `lastusage`, for example `'30 minutes'`; the framework calls it every 10 minutes with `CONF.allow_sessions_unused` (default `'-20 minutes'`). Without `ondata`, `release()` and `release2()` do nothing.

Example: Reload a user after a change
```js
session.release2(user.id);
```

### session.contains(sessionid, callback)

Type: `method`

Returns a session only when its data is in memory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sessionid` | `String` | yes |  | Session ID. |
| `callback` | `Function(err, data, meta)` | yes |  | Called with the result. |

Unlike `get()`, it never calls `ondata`. The callback receives `(null, data, meta)` or no arguments. `session.contains2(id, callback)` finds the first such session of user `id`. `session.has(sessionid, callback(err, bool))` and `session.has2(id, callback(err, bool))` only tell whether a session exists.

Example: Is the user online?
```js
session.has2(user.id, function(err, is) {
	console.log(is ? 'online' : 'offline');
});
```

### session.list(id, callback)

Type: `method`

Lists the live sessions of a user.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | User ID. |
| `callback` | `Function(err, items)` | yes |  | Called with the items. |

Passes an array of session items of user `id` and removes expired items. `session.listlive(callback)` lists all sessions with loaded data, for any user.

Example: Devices of a user
```js
session.list(self.user.id, function(err, items) {
	self.json(items.map(function(item) {
		return { id: item.sessionid, note: item.note, used: item.used };
	}));
});
```

### session.count([id], callback)

Type: `method`

Counts sessions.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | no |  | User ID. |
| `callback` | `Function(err, stats)` | yes |  | Called with the counts. |

Passes `{ used, free, count }`: `used` sessions have loaded data, `free` do not. With `id`, counts only the sessions of that user. `session.usage()` returns the same object for all sessions directly.

Example: Stats
```js
session.count(function(err, stats) {
	console.log(stats.count, 'sessions');
});
console.log(session.usage());
```

### session.clear([lastusage], [callback])

Type: `method`

Removes sessions.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `lastusage` | `String` | no |  | Unused time. |
| `callback` | `Function(err, count)` | no |  | Called after the removal. |

With `lastusage` (for example `'7 days'`), removes the sessions not used for that time and passes their count. Without it, removes every session. `session.clean()` removes only expired sessions; the framework calls it every 10 minutes. `session.load([callback])` reads the saved sessions from the file again; `SESSION()` calls it on creation.

Example: Remove old sessions
```js
session.clear('30 days');
```

### allow_sessions_unused : -20 minutes

Type: `config`

Releases the data of SESSION() items unused for this time.

Returns: `String`

Every 10 minutes the framework calls `releaseunused()` with this value on every session store. Default `'-20 minutes'`. The sessions stay valid; their data is loaded again with `ondata`.

Example: config
```js
// /config
allow_sessions_unused : -1 hour
```
