What you need is before filter for the routes. You can use one of the route filter libraries available for backbone. Like https://github.com/boazsender/backbone.routefilter and https://github.com/fantactuka/backbone-route-filter
Consider backbone-route-filter(2nd link above). Your code will look something like the one below:
var Router = Backbone.Router.extend({
routes: {
'A/*subroute': 'A',
'B/*subroute':'B'
},
initialize: function() {
this.checkUser();
},
before: {
'*any': function(fragment, args) {
var hasAccess = checkUser(); // Do your authentication logic
if (!hasAccess) {
Backbone.navigate('/', true);
}
return hasAccess; //return true if you want to proceed to routes else return false
},
A:function(subroute) {
xx
},
B:function(subroute) {
xx
}
checkUser: function() {
var identity = new Common.model.Identity( );
var mainrouter1=this;
identity.fetch( { "xhrFields": { "withCredentials" : true },
async: false,
success : function ( model ) {
console.log("authentication check");
}
});
}
})
Since you have ajax request in you checkUser() method which is async, you may need to modify it a bit to make it work with route filter. Like making it synchronous by adding "async: false".