Spanish Total.js
English
Documentation For AI agents
Contents

Authorization

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

.md GitHub
On this page

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 explains how to use them with examples; this page is the exact reference.

Encryption has its own page: Encryption.

API

method

AUTH(fn)

Registers the delegate that signs in every request.
ParameterTypeDescription
fn Function($) 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).

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

AUTH(options)

Starts the built-in cookie session mechanism.
ParameterTypeDescription
options Object 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.

OptionTypeDescription
secretStringKey for encrypting the token. Always set it.
cookieStringName of the cookie with the token.
headerStringName of a request header with the token, used when the cookie is missing. Write it in lower case.
expireStringHow long user data stays in memory. Default '5 minutes'.
strictBooleanThe cached session works only with the same user agent. Default true.
ddosNumberFailed attempts per IP address before every request of that IP is invalid. The counters reset with each cleaning.
cleanerNumberCleaning interval in minutes. Default 5.
optionsObjectCookie options used when the cookie is written or removed.
onreadFunction(meta, next, $)Loads the user data, see options.onread.
onsessionFunction(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.
onauthorizeFunction($)Called first for every request. Return true to skip the built-in processing; then answer $ yourself.
onlogoutFunction(session)Called by logout().
onfreeFunction(meta)Called after cleaning with { sessions: Array, users: Array }: the removed session IDs and the user IDs without any live session.
onddosFunction($)Called when a blocked IP address makes a request.
localeFunction(data, req)Returns the language of the request. data is null for anonymous visitors.

An invalid or unknown token removes the cookie.

Built-in session
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;
Language of the user
opt.locale = function(data, req) {
	return data ? data.language : '';
};
delegate

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

Loads the user data for a session token in the built-in session.
ParameterTypeDescription
meta Object { sessionid, userid, ip, ua }.
next Function(err, data) Callback with the user data.
$ Object 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.

Read the user
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();
	});
};
method

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

Writes the session cookie of the built-in session.
ParameterTypeDescription
$ Controller|Object Object with a cookie() method.
sessionid String Your session ID.
userid String The user ID.
expiration String|Date Expiration of the cookie, for example '1 month'.
cookieoptions? Object Cookie options. Default: options.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 $.

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

options.logout($)

Signs out the current session of the built-in session.
ParameterTypeDescription
$ Controller|String 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.

Sign out
function logout() {
	var self = this;
	MAIN.auth.logout(self);
	self.redirect('/');
}
method

options.update(userid, fn)

since 0.0.56 Changes the cached data of all sessions of a user in the built-in session.
ParameterTypeDescription
userid String The user ID.
fn Function(data, session) 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.

Rename the user
MAIN.auth.update(user.id, function(data) {
	data.name = model.name;
});
method

options.refresh(userid, [exceptsessionid])

since 0.0.56 Drops the cached data of a user in the built-in session.
ParameterTypeDescription
userid String The user ID.
exceptsessionid? String 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.

Reload after a change
MAIN.auth.refresh(user.id, self.sessionid);
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.

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

$.success(user)

Signs the request in with a user object.
ParameterTypeDescription
user Object 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.

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

$.invalid([user])

Marks the request as not signed in.
ParameterTypeDescription
user? Object 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.

No token
if (!token) {
	$.invalid();
	return;
}
method

$.cancel()

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.

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

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

Reads or writes a cookie inside the AUTH() delegate.
ParameterTypeDescription
name String Cookie name.
value? String|null New value; null removes the cookie.
expire? String|Date Expiration, for example '1 month'.
options? Object 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.

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

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

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.

One URL, two routes
exports.install = function() {
	ROUTE('+GET /', 'dashboard');
	ROUTE('-GET /', 'login');
	ROUTE('+SOCKET /live/', live);
};
Flags in an array
ROUTE('GET /account/', account, ['authorize']);
config

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

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().

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

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

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

Checks the roles of the signed-in user and answers 401 when none matches.
ParameterTypeDescription
$ Controller|Object A controller or a schema/operation $.
role String 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.

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

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

Counts attempts from an IP address and tells when to block it.
ParameterTypeDescription
$ Controller|Object Object with ip.
limit? Number Allowed attempts. Default: 5
expiration? String How long the counter lives. Default: '15 minutes'

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.

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

controller.user

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.

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

$.user

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.

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

controller.session / controller.sessionid

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.

Sign out of a SESSION() store
session.remove(self.sessionid);
method

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

Reads or writes a cookie.
ParameterTypeDescription
name String Cookie name.
value? String New value.
expires? String|Date|Object Expiration, or the options.
options? Object 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.

OptionDescription
domainCookie domain.
pathCookie path. Default /.
securetrue adds Secure. Default CONF.default_cookies_secure.
httponlytrue 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.

Write and read
self.cookie('theme', 'dark', '1 year', { httponly: true });
var theme = self.cookie('theme');
Remove
self.cookie('token', '', '-1 day');
method

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

Writes a cookie to the HTTP response.
ParameterTypeDescription
name String Cookie name.
value String Value.
expires? String|Date|Object Expiration, or the options.
options? Object 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.

From the delegate
$.res.cookie('visited', '1', '1 day');
var old = $.req.cookie('visited');
config

default_cookies_samesite : Lax

Default SameSite attribute of cookies.

Returns String

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

config
// /config
default_cookies_samesite : Strict
config

default_cookies_secure : false

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.

config
// /config
default_cookies_secure : true
method

SESSION([name])

Returns a named session store.
ParameterTypeDescription
name? String Name of the store. Default: 'default'

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.

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

session.ondata = function(meta, next)

Loads the data of a session that is not in memory.
ParameterTypeDescription
meta Object The session item: sessionid, id, note, settings...
next Function(err, data) 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.

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

session.onremove = function(item)

Called when a session is removed or expires.
ParameterTypeDescription
item Object 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.

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

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

Creates a session and writes its cookie.
ParameterTypeDescription
res Controller|Object Where the cookie is written.
opt Object Options, see the table.
callback? Function(err, data, meta) 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.

OptionDescription
nameCookie name.
sessionidSession ID. Default UID().
idUser ID.
dataSession data.
expireExpiration, for example '1 month'.
key (or secret)Encryption key.
strictBind the cookie to the IP address too. Default false.
noteA note, for example the user agent.
settingsA string with settings.
optionsCookie options. Default { httponly: true, security: 'lax' }.
Sign in
session.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() {
	self.redirect('/');
});
method

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

Reads the session from the cookie of a request.
ParameterTypeDescription
req Object The authorization $, a controller or a request.
opt Object Options, see the table.
callback Function(err, data, meta, init, param) data is the session data, meta the item, init is true when ondata loaded the data.
param? Any 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.

OptionDescription
nameCookie name.
expireExtends the session and the cookie by this time.
key (or secret)Encryption key.
extendcookieExtend the cookie with expire. Default true.
removecookieRemove an invalid cookie. Default true.
optionsCookie options.
ddosFailed attempts per IP address before the cookie is not checked anymore.
In AUTH()
AUTH(function($) {
	session.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) {
		if (data)
			$.success(data);
		else
			$.invalid();
	});
});
method

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

Creates a session and returns a token instead of a cookie.
ParameterTypeDescription
res Object A controller, a schema $ or a response.
opt Object Options of setcookie().
callback? Function(err, token, data, meta) 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.

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

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

Reads the session from a token.
ParameterTypeDescription
req Object The authorization $ or a request.
opt Object Options.
callback Function(err, data, meta, init, param) Called with the session.
param? Any A value passed to the callback.

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

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

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

Creates or replaces a session.
ParameterTypeDescription
sessionid String Session ID.
id? String User ID.
data Object Session data.
expire String Expiration.
note? String A note.
settings? String Settings.
callback? Function(err, data, meta) 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.

Create a session
session.set(UID(), user.id, user, '1 month', $.ua);
method

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

Reads a session.
ParameterTypeDescription
sessionid String Session ID.
expire? String Extends the session by this time.
callback Function(err, data, meta, init) 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.

Read
session.get(self.sessionid, function(err, data, meta) {
	self.json(data);
});
method

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

Changes a session.
ParameterTypeDescription
sessionid String Session ID.
data Object New data.
expire? String New expiration from now.
note? String New note.
settings? String New settings.
callback? Function 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.

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

session.remove(sessionid, [callback])

Removes a session.
ParameterTypeDescription
sessionid String|Object Session ID or item.
callback? Function(err, item) 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.

Sign out
session.remove(self.sessionid);
self.cookie('sid', '', '-1 day');
Sign out everywhere
session.remove2(user.id);
method

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

Frees the data of a session from memory.
ParameterTypeDescription
sessionid? String|Object Session ID or item.
expire? String Used by release2().
callback? Function(err, count) 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.

Reload a user after a change
session.release2(user.id);
method

session.contains(sessionid, callback)

Returns a session only when its data is in memory.
ParameterTypeDescription
sessionid String Session ID.
callback Function(err, data, meta) 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.

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

session.list(id, callback)

Lists the live sessions of a user.
ParameterTypeDescription
id String User ID.
callback Function(err, items) 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.

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

session.count([id], callback)

Counts sessions.
ParameterTypeDescription
id? String User ID.
callback Function(err, stats) 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.

Stats
session.count(function(err, stats) {
	console.log(stats.count, 'sessions');
});
console.log(session.usage());
method

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

Removes sessions.
ParameterTypeDescription
lastusage? String Unused time.
callback? Function(err, count) 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.

Remove old sessions
session.clear('30 days');
config

allow_sessions_unused : -20 minutes

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.

config
// /config
allow_sessions_unused : -1 hour
Made in Europe