ForgeTotal.js 5
de

Total.js 5

Routen mit AUTH schützen

Total.js 5 · total5@0.0.19 authroutingsecurity Mit Total.js 5 ausgeführt

AUTH() läuft bei jeder Anfrage. Rufe $.success(user) auf, wenn die Anfrage authentifiziert ist, und $.invalid(), wenn nicht. Das Benutzerobjekt steht dann in jedem Handler als $.user zur Verfügung.

Setze + vor eine Route, um nur authentifizierte Benutzer zuzulassen, und -, um nur anonyme zuzulassen. Eine Route ohne Präfix ist für alle offen.

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 });
}