I found exactly the plugin that I required:
https://github.com/fantactuka/backbone-route-filter
This plugin allows to create/receive an Ajax request/response before the route is hit.
In the router:
routes: {
'': 'landing_page',
'(/)login': 'login',
'(/)home': 'home',
},
/*--- Before filter checks authentication (BB async router plugin) ---*/
before: {
'(/)login': 'redirect_auth',
'(/)home': 'redirect_auth',
'(/)users/create_role': 'redirect_auth'
},
/*--- Checks if the user is logged in and redirects ---*/
redirect_auth: function(fragment, args, next) {
APP.controllers.auth_controller.redirect(fragment, args, next);
}
The redirection logic is implemented as such in the auth_controller object:
/*--- Check if the user is logged ---*/
/*--- PHP REST Show (GET) ---*/
Auth_controller.prototype.isLogged = function(){
//Check if the user is authenticated
var getAuthStatus = this.auth_model.fetch();
return getAuthStatus;
};
/*--- Redirect the user based on auth status (before -> route) ---*/
Auth_controller.prototype.redirect = function(fragment, args, next){
var getAuthStatus = this.isLogged();
var self = this;
$.when(getAuthStatus).then(function(response){
var auth_status = Object.keys(response.success)[0];
if(auth_status === 'guest'){
if(fragment === 'login'){
next();
}else{
APP.router.navigate("login", {trigger: true});
}
} else {
var sidebars_controller = new Sidebars_controller();
APP.user = response.success["auth"];
if(fragment === 'login'){
APP.router.navigate("home", {trigger: true});
}else{
next();
}
}
})
};