ForgeTotal.js 5
en

Total.js 5

Protect routes with AUTH

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

AUTH() runs for every request. Call $.success(user) when the request is authenticated and $.invalid() when it is not. The user object is then available as $.user in every handler.

Prefix a route with + to allow only authenticated users and with - to allow only anonymous users. A route without a prefix is open to everybody.

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

	// This demo reads a cookie. In a real app verify a signed session instead.
	var token = $.cookie('auth');

	if (token === 'secret-token')
		$.success({ id: '1', name: 'Peter' });
	else
		$.invalid();
});
controllers/private.js
exports.install = function() {
	ROUTE('+GET /private/', private_page);
	ROUTE('-GET /login/', login_page);
	ROUTE('GET /whoami/', whoami);
};

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

function login_page($) {
	$.json({ message: 'Please sign in' });
}

function whoami($) {
	$.json({ user: $.user ? $.user.name : null });
}