Authorization
Decide who the user of a request is with AUTH(), protect routes and actions, and use built-in sessions.
On this page
Total.js does not decide who a user is. You register one authorization delegate with AUTH(), the framework calls it for every request that matches a route, and the object you accept becomes the user of the request: $.user in a route action and in an action. Routes then use the + and - flags to say who may call them.
// definitions/auth.js
AUTH(function($) {
var token = $.headers['x-token'];
if (token === 'secret-token')
$.success({ id: '1', name: 'Peter', sa: true });
else
$.invalid();
});The delegate
The delegate gets $, an options object built for the current request. It has $.headers, $.query, $.ip, $.ua, $.url, $.cookie(name) and $.controller. For WebSocket connections $.iswebsocket is true. End the delegate with exactly one of these calls:
| Call | Result |
|---|---|
$.success(user) | The request is authorized and user becomes $.user |
$.invalid() | The request is not authorized and the user is undefined |
The delegate can be asynchronous: call $.success() or $.invalid() when your database answers. The request body is already parsed when the delegate runs, so $.body is available.
Without an AUTH() delegate no user is ever assigned and the + and - flags of routes are not checked.
Route flags + and -
Put the flag in front of the HTTP method:
exports.install = function() {
ROUTE('+GET /admin/', dashboard);
ROUTE('-GET /login/', 'login');
ROUTE('-POST /api/login/ --> Account/login');
ROUTE('+GET /api/logout/ --> Account/logout');
ROUTE('GET /', 'index');
};| Flag | Who may call the route |
|---|---|
+ | Only an authorized request (the delegate called $.success()) |
- | Only an unauthorized request (the delegate called $.invalid()) |
| none | Everybody |
The framework first finds the route by its URL, then runs the delegate. When the result does not fit the flag of the route, it looks for another route with the same URL whose flag fits. So you can define +GET / and -GET / side by side, one for logged users and one for visitors. When no route fits, 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 belongs to the whole API line and is checked for every endpoint: ROUTE('+API /api/ products_save --> Products/save').
The user in controllers and actions
function dashboard($) {
$.json({ id: $.user.id, name: $.user.name });
}
NEWACTION({
id: 'Account/profile',
action: function($) {
$.success({ id: $.user.id, name: $.user.name });
}
});When a route is public (no flag) you can still read the user: $.user is filled whenever the delegate accepted the request. controller.authorize() runs the delegate on demand and returns a Promise with the user.
Roles and permissions
Total.js reads two conventions of the user object:
user.saoruser.su(super admin) passes every check.user.permissionsoruser.roleshold what the user may do, as an array (['products', 'orders']) or as an object ({ products: true }).
UNAUTHORIZED($, ...permissions) returns false when the user has at least one of the permissions. Otherwise it responds with 401 through $.invalid(401) and returns true:
NEWACTION({
id: 'Products/remove',
params: '*id:UID',
action: function($) {
if (UNAUTHORIZED($, 'products', 'admin'))
return;
$.success();
}
});Actions can declare the same checks: user: true (only authorized), user: false (only unauthorized), sa: true (only super admins) and permissions: 'products,admin' (any of them).
Built-in sessions
Pass an object instead of a function and AUTH() installs a cookie session system. The framework fills the object with methods, so keep a reference to it:
// definitions/auth.js
var opt = {};
opt.secret = 'a-long-random-string';
opt.cookie = '__user';
opt.expire = '10 minutes';
opt.ddos = 10;
opt.options = { httponly: true, security: 'lax' };
opt.onread = function(meta, next) {
// meta: { sessionid, userid, ip, ua }
DATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);
};
AUTH(opt);
MAIN.session = opt;The cookie holds a signed token with the session ID and the user ID. On a request the framework verifies the token, looks for the session in memory and calls onread() only when the session is not there yet. The loaded data is kept for expire since the last read from the database; expired sessions are removed every cleaner minutes (default 5).
Sign in and sign out from actions:
NEWACTION({
id: 'Account/login',
input: '*email:Email,*password:String',
action: function($, model) {
if (BLOCKED($, 10)) {
$.invalid(401);
return;
}
DATA.read('tbl_user').where('email', model.email).where('password', model.password.sha256(CONF.secret)).callback(function(err, user) {
if (user) {
BLOCKED($, null);
MAIN.session.authcookie($, UID(), user.id, '1 month');
$.success();
} else
$.invalid(401);
});
}
});
NEWACTION({
id: 'Account/logout',
action: function($) {
MAIN.session.logout($);
$.success();
}
});opt.update(userid, fn) changes the cached data of all sessions of a user and opt.refresh(userid) drops them, so the next request reads the user again.
Brute-force protection
BLOCKED($, limit, expire) counts calls per IP address. It returns true when the address was counted more than limit times (default 5). The counter is removed after expire (default '15 minutes'), or at once with BLOCKED($, null). Call it before you check a password and reset it after a success, as in the login above.