Spanish Total.js
English
Documentation For AI agents
Contents

Authorization

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

.md GitHub
On this page

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 explains how they work together with examples.

Encryption and audit logs have their own pages: Encryption and Audit logs.

API

delegate

AUTH(callback)

Registers the authorization delegate that decides who the user of a request is.
ParameterTypeDescription
callback Function 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.

Token in a header
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();
	});
});
method

AUTH(options)

Installs the built-in cookie session system.
ParameterTypeDescription
options.secret String The secret that signs the session tokens.
options.cookie? String The name of the session cookie.
options.header? String A lower-case header name to read the token from when there is no cookie.
options.options? Object Cookie options used by authcookie() and when the cookie is removed (httponly, security, domain...).
options.expire? String How long loaded user data stays in memory. Default: '5 minutes'
options.cleaner? Number How often, in minutes, expired sessions are removed. Default: 5
options.strict? Boolean A cached session is valid only for the same user agent. Default: true
options.ddos? Number How many invalid tokens one IP address may send before it is refused until the next cleaning.
options.onread Function 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.

Session setup
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;
delegate

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

Loads the user of a session that is not in memory.
ParameterTypeDescription
meta Object { sessionid, userid, ip, ua }.
callback Function function(err, data).
$ Object 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().

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

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

Runs for each authorized request before the user is accepted.
ParameterTypeDescription
session Object The session.
$ Object The options of the request.
isnew? Boolean 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.

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

opt.onauthorize = function($)

Runs first in the session delegate; return true to handle the request yourself.
ParameterTypeDescription
$ Object 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().

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

opt.onfree = function(meta)

Runs after expired sessions are removed from memory.
ParameterTypeDescription
meta Object { 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.

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

opt.onlogout = function(session)

Runs when logout() removes a session from memory.
ParameterTypeDescription
session Object 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.

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

opt.onddos = function($)

Runs when an IP address exceeded the ddos limit of invalid tokens.
ParameterTypeDescription
$ Object The options of the request.

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

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

opt.localize = function(user, controller)

Returns the language of the request from the user data.
ParameterTypeDescription
user Object The user data or null.
controller Controller 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.

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

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

Signs a token and sets the session cookie.
ParameterTypeDescription
$ Object The $ of an action or a controller.
sessionid String A new unique ID, for example UID().
userid String The user ID passed later to onread().
expire? String|Date The cookie expiration, for example '1 month'.
options? Object 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().

Login
MAIN.session.authcookie($, UID(), user.id, '1 month');
$.success();
method

opt.sign(sessionid, userid)

Creates a signed session token without setting a cookie.
ParameterTypeDescription
sessionid String A unique session ID.
userid String The user ID.

Returns String The token.

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

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

opt.logout($)

Removes the session of the request and its cookie.
ParameterTypeDescription
$ Object|String 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.

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

opt.update(userid, fn)

Changes the cached data of every session of a user.
ParameterTypeDescription
userid String The user ID.
fn Function function(data, session).

Returns Number How many sessions were updated.

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

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

opt.refresh(userid, [exceptsessionid])

Drops the cached sessions of a user so the next request reads the user again.
ParameterTypeDescription
userid String The user ID.
exceptsessionid? String 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.

After a permission change
MAIN.session.refresh(model.userid);
property

opt.sessions

The sessions in memory, keyed by session ID.

Returns Object

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

Online users
var count = Object.keys(MAIN.session.sessions).length;
property

DEF.onAuthorize

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.

Check
if (!DEF.onAuthorize)
	console.warn('No AUTH() delegate');
type

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

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.

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

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

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.

Same URL for both
ROUTE('+GET /', 'app');
ROUTE('-GET /', 'login');
property

controller.user

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.

Read it
function dashboard($) {
	$.json({ name: $.user.name });
}
property

$.user

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.

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

controller.authorize([callback])

Runs the AUTH() delegate on demand.
ParameterTypeDescription
callback? Function 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.

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

controller.session

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.

Session ID
function info($) {
	$.json({ sessionid: $.sessionid });
}
method

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

Checks the permissions of the user and responds with 401 when they are missing.
ParameterTypeDescription
$ Object The $ of an action or a controller.
permission? String 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.

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

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

UNAUTHORIZED() for the current $.
ParameterTypeDescription
permission? String One or more permission names.

Returns Boolean true when the user is not allowed.

The same check with $ taken from the action.

Short form
if ($.unauthorized('orders'))
	return;
property

user.permissions

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.

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

user.sa

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.

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

new User([obj])

A class for user objects.
ParameterTypeDescription
obj? Object 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.

A user for a job
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' }
config

NEWACTION({ user: true })

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

When the condition fails, the action responds with 401.

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

NEWACTION({ sa: true })

Limits an action to super admins.

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

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

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

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.

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

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

Counts attempts per IP address and tells when the address is blocked.
ParameterTypeDescription
$ Object The $ of an action or a controller.
limit? Number|null Allowed attempts; null or -1 resets the counter. Default: 5
expire? String How long the counter lives. Default: '15 minutes'

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.

Login guard
if (BLOCKED($, 10)) {
	$.invalid(401);
	return;
}
// ... the password is correct
BLOCKED($, null);
Made in Europe