Spanish Total.js
English
Documentation For AI agents
Contents

Authorization and sessions

Sign in requests with the AUTH() delegate, limit routes with the + and - flags, and keep sessions in cookies, tokens or the SESSION() store.

.md GitHub
On this page

Total.js signs in requests with one delegate. You register it with AUTH(), the framework calls it for every request (and for every WebSocket connection), and the delegate answers either "this is the user" or "nobody is signed in". Routes then decide with a flag whether they run for signed-in visitors, for anonymous visitors or for both.

Put the delegate in a file in the definitions/ folder, for example definitions/auth.js.

The AUTH() delegate

AUTH(function($) { ... }) receives a $ object with the request data: $.cookie(name), $.headers, $.query, $.ip, $.ua, $.url, $.websocket and more. Call $.success(user) when the request belongs to a user, or $.invalid() when it does not:

// definitions/auth.js
AUTH(function($) {

    var token = $.cookie('token');
    if (!token) {
        $.invalid();
        return;
    }

    var userid = DECRYPTREQ($.req, token, 'auth');
    if (!userid) {
        $.invalid();
        return;
    }

    NOSQL('users').one().where('id', userid).callback(function(err, user) {
        if (user)
            $.success(user);
        else
            $.invalid();
    });
});

The object you pass to $.success() becomes controller.user in actions, $.user in schemas and client.user in WebSockets. Keep it small: it is the same object for the whole request.

$.cancel() stops the processing when you have already answered the request yourself, for example with a redirect from $.res.

Route flags: + and -

Start the URL with + for routes that need a signed-in user, and with - for routes only anonymous visitors can see. A route without a flag runs for both:

exports.install = function() {
    ROUTE('+GET  /account/', account);   // signed in
    ROUTE('-GET  /login/', 'login');     // not signed in
    ROUTE('-POST /login/', login);
    ROUTE('+GET  /logout/', logout);
    ROUTE('GET   /', 'index');           // everybody
};

The prefix 🔒 works like +. In the flags array you can write 'authorize', 'authorized' or 'logged' instead of +, and 'unauthorize', 'unauthorized' or 'unlogged' instead of -. WebSocket routes accept the same prefixes.

You can declare the same URL twice, once with + and once with -, and Total.js picks the route that matches the visitor. When a route exists only for the other state, the visitor gets 401; when no route exists at all, 404. A WebSocket that does not match is closed with 4001.

The flags only take effect when an AUTH() delegate is registered. Without one, the framework does not check them.

Roles

A flag that starts with @ is a role. Total.js keeps it in controller.route.flags and treats the route as one that needs a signed-in user, but it does not compare roles for you. Check them in the action, for example with UNAUTHORIZED():

exports.install = function() {
    ROUTE('GET /admin/', admin, ['@admin']);
};

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

UNAUTHORIZED($, role1, role2, ...) looks for the roles in user.permissions or user.roles (an array or an object). It returns false when the user has one of them, or has sa or su set to a truthy value. Otherwise it calls $.invalid(401) and returns true.

Signing in and out with cookies

A cookie holds an encrypted token. ENCRYPTREQ() encrypts a value together with the browser's user agent (and the IP address in strict mode), so a stolen cookie does not work in another browser:

function login() {
    var self = this;
    NOSQL('users').one().where('email', self.body.email).callback(function(err, user) {

        if (!user || user.password !== self.body.password.sha256()) {
            self.invalid('error-credentials');
            return;
        }

        self.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month', { httponly: true });
        self.redirect('/account/');
    });
}

function logout() {
    var self = this;
    self.cookie('token', '', '-1 day');
    self.redirect('/');
}

controller.cookie(name) reads a cookie and controller.cookie(name, value, expires, [options]) writes one. Options are domain, path (default /), secure, httponly and samesite. CONF.default_cookies_samesite (default 'Lax') and CONF.default_cookies_secure (default false) set the defaults.

The built-in session mechanism

Pass an object to AUTH() instead of a function, and Total.js runs a cookie session for you. It decrypts the cookie, keeps the user data in memory and calls onread only when the data is not cached:

var opt = {};
opt.secret = 'a-long-random-key';
opt.cookie = 'session';
opt.expire = '10 minutes';   // how long user data stays in memory
opt.ddos = 10;               // failed attempts per IP before blocking

opt.onread = function(meta, next) {
    // meta = { sessionid, userid, ip, ua }
    NOSQL('sessions').one().where('id', meta.sessionid).where('userid', meta.userid).callback(function(err, session) {
        if (!session)
            return next();
        NOSQL('users').one().where('id', meta.userid).callback(next);
    });
};

opt.onlogout = function(session) {
    NOSQL('sessions').remove().where('id', session.sessionid);
};

AUTH(opt);
MAIN.auth = opt;

AUTH() adds methods to the object you pass, so keep a reference to it. Sign the user in with opt.authcookie(), and sign out with opt.logout():

function login() {
    var self = this;
    // ... check the credentials, then:
    var sessionid = UID();
    NOSQL('sessions').insert({ id: sessionid, userid: user.id, dtcreated: NOW });
    MAIN.auth.authcookie(self, sessionid, user.id, '1 month');
    self.redirect('/account/');
}

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

After you change a user in the database, call opt.refresh(userid) to drop the cached data, so the next request reads it again, or opt.update(userid, fn) to change the cached data in place.

SESSION(): a session store

SESSION([name]) returns a named session store (the default name is default). It keeps sessions in memory, writes their metadata to databases/sessions.txt and loads it again after a restart. The user data is not written to the file: after a restart, or after the data is released, the store asks the ondata delegate for it:

var session = SESSION();

session.ondata = function(meta, next) {
    // meta.sessionid, meta.id (user ID), meta.note, meta.settings
    NOSQL('users').one().where('id', meta.id).callback(next);
};

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

Create the session when the user signs in, and remove it when the user signs out:

function login() {
    var self = this;
    // ... check the credentials, then:
    session.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key', note: self.ua }, function() {
        self.redirect('/account/');
    });
}

function logout() {
    var self = this;
    session.remove(self.sessionid);
    self.cookie('sid', '', '-1 day');
    self.redirect('/');
}

For an API with tokens instead of cookies, use session.settoken() and session.gettoken(). Methods that end with 2 (get2, set2, update2, remove2, release2, has2, contains2) work with the user ID instead of the session ID, so you can update or end all sessions of a user at once.

Every 10 minutes the framework removes expired sessions and releases the data of sessions unused for CONF.allow_sessions_unused (default '-20 minutes').

Made in Europe