ForgeTotal.js 5
en

Total.js 5

Sign users in with the built-in session auth

Total.js 5 · total5@0.0.19 authsessionssecurity Executed against Total.js 5

Instead of a function, AUTH(options) accepts an options object and installs a complete cookie-session authentication:

  • secret signs the cookie, cookie is its name and expire how long a session stays in memory without activity
  • onread(meta, next, $) loads the user when a valid cookie arrives from a session that is not in memory (for example after a restart); call next(null, user), or next('not found') to refuse. Check that the session still exists in your own store here, otherwise a copied cookie keeps working after the user signed out
  • onlogout(session) and onremove(sessionid) run when a session is removed: delete it from your store
  • options.authcookie($, sessionid, userid, expiration) signs the user in: it writes the signed cookie to the response
  • options.logout($) removes the session and the cookie

Keep the options object in a variable: it is the handle you use to sign users in and out. After that, $.user is set and + and - routes work as in the AUTH recipe.

definitions/auth.js
var users = {
	'1': { id: '1', name: 'Anna', password: 'secret' }
};

// sessionid -> userid. In a real app this is a database table.
MAIN.sessions = {};

MAIN.auth = {
	secret: 'change-this-secret',
	cookie: 'forge_session',
	expire: '1 day',
	onread: function(meta, next) {
		var user = users[MAIN.sessions[meta.sessionid]];
		user ? next(null, { id: user.id, name: user.name }) : next('session not found');
	},
	onlogout: function(session) {
		delete MAIN.sessions[session.sessionid];
	},
	onremove: function(sessionid) {
		delete MAIN.sessions[sessionid];
	}
};

AUTH(MAIN.auth);
controllers/account.js
exports.install = function() {
	ROUTE('POST /login/', login);
	ROUTE('+POST /logout/', logout);
	ROUTE('+GET /me/', me);
};

function login($) {

	var user = $.body.id && $.body.id === '1' && $.body.password === 'secret' ? { id: '1', name: 'Anna' } : null;

	if (!user) {
		$.invalid(401);
		return;
	}

	var sessionid = UID();
	MAIN.sessions[sessionid] = user.id;
	MAIN.auth.authcookie($, sessionid, user.id, '1 day');
	$.json({ name: user.name });
}

function logout($) {
	MAIN.auth.logout($);
	$.json({ ok: true });
}

function me($) {
	$.json({ name: $.user.name });
}