---
title: Authorization
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/authorization/
updated: 2026-11-18T16:57:29.576Z
---

# Authorization

> AUTH(), route flags, permissions, sessions and BLOCKED().

Everything that decides and checks the user of a request: the `AUTH()` delegate and its built-in sessions, the `+` and `-` route flags, `UNAUTHORIZED()` and action permissions, and `BLOCKED()`. The guide [Authorization](../../guides/authorization/) explains how they work together with examples.

Encryption and audit logs have their own pages: [Encryption](../encryption/) and [Audit logs](../audit-logs/).

## API

### AUTH(callback)

Type: `delegate`

Registers the authorization delegate that decides who the user of a request is.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function($)`; call `$.success(user)` or `$.invalid()`. |

Returns: `undefined`

The delegate runs for each HTTP request and WebSocket connection that matches a route, after the body is parsed and before the route action. `$` has `headers`, `query`, `body`, `ip`, `ua`, `url`, `cookie(name)`, `controller` and, for WebSocket, `iswebsocket: true`. Call `$.success(user)` to authorize the request or `$.invalid()` to refuse it; the delegate can be asynchronous. A second call replaces the delegate. `F.auth()` is the same function.

Example: Token in a header
```js
AUTH(function($) {
	var token = $.headers['x-token'];
	if (!token) {
		$.invalid();
		return;
	}
	DATA.read('tbl_user').where('token', token).callback(function(err, user) {
		if (user)
			$.success(user);
		else
			$.invalid();
	});
});
```

### AUTH(options)

Type: `method`

Installs the built-in cookie session system.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options.secret` | `String` | yes |  | The secret that signs the session tokens. |
| `options.cookie` | `String` | no |  | The name of the session cookie. |
| `options.header` | `String` | no |  | A lower-case header name to read the token from when there is no cookie. |
| `options.options` | `Object` | no |  | Cookie options used by `authcookie()` and when the cookie is removed (`httponly`, `security`, `domain`...). |
| `options.expire` | `String` | no | `'5 minutes'` | How long loaded user data stays in memory. |
| `options.cleaner` | `Number` | no | `5` | How often, in minutes, expired sessions are removed. |
| `options.strict` | `Boolean` | no | `true` | A cached session is valid only for the same user agent. |
| `options.ddos` | `Number` | no |  | How many invalid tokens one IP address may send before it is refused until the next cleaning. |
| `options.onread` | `Function` | yes |  | `function(meta, callback, $)` loads the user; see `opt.onread`. |

Returns: `undefined`

With an object, `AUTH()` turns it into a session manager and registers its `auth` function as the delegate. The object gets the methods `authcookie()`, `sign()`, `logout()`, `update()`, `refresh()` and the in-memory `sessions`, so keep a reference to it (for example in `MAIN`). The token is read from the cookie `cookie`, or from the header `header`. Its signature is checked with `secret`, the session is taken from memory, and `onread()` is called when it is not there.

Example: Session setup
```js
var opt = {};
opt.secret = 'a-long-random-string';
opt.cookie = '__user';
opt.expire = '10 minutes';
opt.onread = function(meta, next) {
	DATA.read('tbl_user').id(meta.userid).callback(next);
};
AUTH(opt);
MAIN.session = opt;
```

### opt.onread = function(meta, callback, $)

Type: `delegate`

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

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |
| `callback` | `Function` | yes |  | `function(err, data)`. |
| `$` | `Object` | yes |  | The options of the request. |

`meta` is `{ sessionid, userid, ip, ua }` from the verified token. Call `callback(err, data)`; `data` becomes the user and is cached for `expire`. An error or empty `data` refuses the request and removes the cookie. Parallel requests with the same session wait for the first `onread()`.

Example: Read from the database
```js
opt.onread = function(meta, next) {
	DATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);
};
```

### opt.onsession = function(session, $, [isnew])

Type: `delegate`

Runs for each authorized request before the user is accepted.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `session` | `Object` | yes |  | The session. |
| `$` | `Object` | yes |  | The options of the request. |
| `isnew` | `Boolean` | no |  | `true` when the data was just read. |

Returns: `Boolean` `true` to stop the default success.

`session` is `{ sessionid, userid, data, ua, expire }`; `isnew` is `true` right after `onread()`. Return `true` to take over: the framework does not call `$.success()`, so you call `$.success()` or `$.invalid()` yourself.

Example: Count requests
```js
opt.onsession = function(session, $) {
	session.data.requests = (session.data.requests || 0) + 1;
};
```

### opt.onauthorize = function($)

Type: `delegate`

Runs first in the session delegate; return true to handle the request yourself.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The options of the request. |

Returns: `Boolean` `true` to skip the session check.

Use it to accept other credentials (an API key, for example) before the cookie is read. When it returns `true` you must call `$.success()` or `$.invalid()`.

Example: API key
```js
opt.onauthorize = function($) {
	if ($.headers['x-apikey'] === CONF.apikey) {
		$.success({ id: 'api', sa: true });
		return true;
	}
};
```

### opt.onfree = function(meta)

Type: `delegate`

Runs after expired sessions are removed from memory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | `{ sessions: Array, users: Array }`. |

`meta.sessions` is an array of removed session IDs, `meta.users` the IDs of users that have no live session left.

Example: Log it
```js
opt.onfree = function(meta) {
	console.log('Released', meta.sessions.length, 'sessions');
};
```

### opt.onlogout = function(session)

Type: `delegate`

Runs when logout() removes a session from memory.

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

Gets the removed session object `{ sessionid, userid, data, ua, expire }`. When the session is not in memory, `opt.onremove(sessionid)` is called instead.

Example: Store the time
```js
opt.onlogout = function(session) {
	DATA.modify('tbl_user', { dtlogout: NOW }).id(session.userid);
};
```

### opt.onddos = function($)

Type: `delegate`

Runs when an IP address exceeded the ddos limit of invalid tokens.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The options of the request. |

The request is refused right after this call. The counters are cleared every `cleaner` minutes.

Example: Log it
```js
opt.ddos = 10;
opt.onddos = function($) {
	console.warn('Too many invalid tokens from', $.ip);
};
```

### opt.localize = function(user, controller)

Type: `delegate`

Returns the language of the request from the user data.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `user` | `Object` | yes |  | The user data or `null`. |
| `controller` | `Controller` | yes |  | The controller. |

Returns: `String` A language code.

Called with the user data, or with `null` when the request has no token or the cached session belongs to another user agent; the returned value becomes `controller.language`. `opt.locale` is accepted as the same option.

Example: User language
```js
opt.localize = function(user, ctrl) {
	return user ? user.language : (ctrl.headers['accept-language'] || '').substring(0, 2);
};
```

### opt.authcookie($, sessionid, userid, [expire], [options])

Type: `method`

Signs a token and sets the session cookie.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` of an action or a controller. |
| `sessionid` | `String` | yes |  | A new unique ID, for example `UID()`. |
| `userid` | `String` | yes |  | The user ID passed later to `onread()`. |
| `expire` | `String|Date` | no |  | The cookie expiration, for example `'1 month'`. |
| `options` | `Object` | no |  | Cookie options. |

Returns: `String` The token.

Call it after a successful login. It creates the token with `sign()` and writes the cookie `opt.cookie` with `options` (default `opt.options`). The session itself is created on the next request through `onread()`.

Example: Login
```js
MAIN.session.authcookie($, UID(), user.id, '1 month');
$.success();
```

### opt.sign(sessionid, userid)

Type: `method`

Creates a signed session token without setting a cookie.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sessionid` | `String` | yes |  | A unique session ID. |
| `userid` | `String` | yes |  | The user ID. |

Returns: `String` The token.

Use it for clients that send the token in the `header` option instead of a cookie.

Example: Token for a mobile app
```js
opt.header = 'x-token';
// in the login action
$.success(MAIN.session.sign(UID(), user.id));
```

### opt.logout($)

Type: `method`

Removes the session of the request and its cookie.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object|String` | yes |  | The request or a session ID. |

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

`$` is the `$` of an action: the session in memory and the cookie are removed. With a controller or a session ID string only the session in memory is removed; the cookie stays and the next request reads the user again. It returns `true` when the session was in memory.

Example: Logout action
```js
NEWACTION({
	id: 'Account/logout',
	action: function($) {
		MAIN.session.logout($);
		$.success();
	}
});
```

### opt.update(userid, fn)

Type: `method`

Changes the cached data of every session of a user.

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

Returns: `Number` How many sessions were updated.

Calls `fn(data, session)` for each session of `userid` in memory.

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

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

Type: `method`

Drops the cached sessions of a user so the next request reads the user again.

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

Returns: `Number` How many sessions were dropped.

The cookies stay valid; `onread()` loads fresh data on the next request. Pass `exceptsessionid` to keep one session in memory.

Example: After a permission change
```js
MAIN.session.refresh(model.userid);
```

### opt.sessions

Type: `property`

The sessions in memory, keyed by session ID.

Returns: `Object`

Each item is `{ sessionid, userid, data, ua, expire }`.

Example: Online users
```js
var count = Object.keys(MAIN.session.sessions).length;
```

### DEF.onAuthorize

Type: `property`

The registered authorization delegate.

Returns: `Function`

`AUTH()` sets it. When it is empty, `$.user` is never set and the `+` and `-` flags of routes are not checked, so `+` routes are open to everybody.

Example: Check
```js
if (!DEF.onAuthorize)
	console.warn('No AUTH() delegate');
```

### ROUTE('+METHOD /url/ ...')

Type: `type`

The route is only for authorized requests.

The flag goes in front of the method. When the delegate refuses the request, the framework looks for another route with the same URL that fits (a `-` route or one without a flag); if there is none, an HTTP request gets `401` and a WebSocket connection is refused during the handshake, so a browser client receives the close code `1006`. For `API` routes the flag of the line is checked for each endpoint.

Example: Admin area
```js
ROUTE('+GET /admin/', dashboard);
ROUTE('+API /api/ orders_list --> Orders/list');
ROUTE('+SOCKET /chat/', chat);
```

### ROUTE('-METHOD /url/ ...')

Type: `type`

The route is only for unauthorized requests.

Typical for login and registration pages. With a `+` route on the same URL you serve visitors and users differently.

Example: Same URL for both
```js
ROUTE('+GET /', 'app');
ROUTE('-GET /', 'login');
```

### controller.user

Type: `property`

The user accepted by the AUTH() delegate.

Returns: `Object`

`undefined` when the request is not authorized. It is set for every route when a delegate exists, including routes without a flag, and is passed to actions as `$.user`.

Example: Read it
```js
function dashboard($) {
	$.json({ name: $.user.name });
}
```

### $.user

Type: `property`

The user of the request inside an action.

Returns: `Object`

Taken from the controller that called the action, or from `ACTION().user(obj)` when you call an action from code.

Example: Owner filter
```js
action: function($) {
	DATA.find('tbl_order').where('userid', $.user.id).callback($);
}
```

### controller.authorize([callback])

Type: `method`

Runs the AUTH() delegate on demand.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `function(err, user)`. |

Returns: `Promise` When `callback` is not given.

Sets `controller.user` when the delegate accepts the request. Without `callback` it returns a `Promise` that resolves with the user or `undefined`; it never rejects.

Example: Inside a route
```js
async function detail($) {
	var user = await $.authorize();
	$.json({ logged: !!user });
}
```

### controller.session

Type: `property`

The built-in session of the request.

Returns: `Object`

Set by `AUTH(options)`: `{ sessionid, userid, data, ua, expire }`. `controller.sessionid` holds the session ID and `$.sessionid` reads it in actions.

Example: Session ID
```js
function info($) {
	$.json({ sessionid: $.sessionid });
}
```

### UNAUTHORIZED($, [permission1], [permission2], [...])

Type: `method`

Checks the permissions of the user and responds with 401 when they are missing.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` of an action or a controller. |
| `permission` | `String` | no |  | One or more permission names; any of them is enough. |

Returns: `Boolean` `true` when the user is not allowed and the request was answered.

Returns `false` when the user has `sa` or `su`, or one of the permissions in `user.permissions` (or `user.roles`), which can be an array or an object. Otherwise it calls `$.invalid(401)` and returns `true`. Without a user it always returns `true`. `F.unauthorized()` is the same function.

Example: Guard an action
```js
action: function($) {
	if (UNAUTHORIZED($, 'orders'))
		return;
	$.success();
}
```

### $.unauthorized([permission1], [permission2], [...])

Type: `method`

UNAUTHORIZED() for the current $.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `permission` | `String` | no |  | One or more permission names. |

Returns: `Boolean` `true` when the user is not allowed.

The same check with `$` taken from the action.

Example: Short form
```js
if ($.unauthorized('orders'))
	return;
```

### user.permissions

Type: `property`

The permissions of the user, read by UNAUTHORIZED() and the permissions of actions.

Returns: `Array|Object`

An array of names or an object with names as keys. `user.roles` is used when `permissions` is missing.

Example: Accept with roles
```js
$.success({ id: '1', name: 'Anna', roles: ['orders', 'products'] });
```

### user.sa

Type: `property`

Marks a super admin.

Returns: `Boolean`

A user with `sa` or `su` passes `UNAUTHORIZED()`, action `permissions` and is the only user allowed by actions with `sa: true`.

Example: Admin
```js
$.success({ id: '1', name: 'Root', sa: true });
```

### new User([obj])

Type: `class`

A class for user objects.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | no |  | The keys of the user. |

Returns: `User`

A global class. The constructor copies every key of `obj` to the new instance, so `new User({ id: '1', sa: true })` has `id` and `sa`. Use it for the identity of code that is not a request, such as a job or a script, and check it with `instanceof User`. The framework does not change the users that your `AUTH()` delegate returns into `User` instances.

Example: A user for a job
```js
NEWACTION('reports_daily', {
	sa: true,
	action: function($) {
		$.success($.user.name);
	}
});

var scheduler = new User({ id: 'cron', name: 'Scheduler', sa: true });
ACTION('reports_daily').user(scheduler).callback(console.log);
// { success: true, value: 'Scheduler' }
```

### NEWACTION({ user: true })

Type: `config`

Limits an action to authorized (true) or unauthorized (false) requests.

When the condition fails, the action responds with `401`.

Example: Only users
```js
NEWACTION({
	id: 'Account/profile',
	user: true,
	action: function($) {
		$.success($.user);
	}
});
```

### NEWACTION({ sa: true })

Type: `config`

Limits an action to super admins.

The user must have `sa` or `su`, otherwise the action responds with `401`. `su: true` works the same.

Example: Admin action
```js
NEWACTION({
	id: 'Users/remove',
	sa: true,
	params: '*id:UID',
	action: function($) {
		$.success();
	}
});
```

### NEWACTION({ permissions: 'name1,name2' })

Type: `config`

Limits an action to users with any of the permissions.

A string separated by commas or semicolons, or an array. The check is `UNAUTHORIZED()`, so super admins always pass.

Example: Permissions
```js
NEWACTION({
	id: 'Orders/list',
	permissions: 'orders,admin',
	action: function($) {
		$.success([]);
	}
});
```

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

Type: `method`

Counts attempts per IP address and tells when the address is blocked.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` of an action or a controller. |
| `limit` | `Number|null` | no | `5` | Allowed attempts; `null` or `-1` resets the counter. |
| `expire` | `String` | no | `'15 minutes'` | How long the counter lives. |

Returns: `Boolean` `true` when blocked.

Each call counts one attempt for `$.ip`. It returns `true` when the address was counted more than `limit` times. The counter starts with the first call and is removed after `expire` (checked every minute). `BLOCKED($, null)` or `BLOCKED($, -1)` removes it at once.

Example: Login guard
```js
if (BLOCKED($, 10)) {
	$.invalid(401);
	return;
}
// ... the password is correct
BLOCKED($, null);
```
