I want to restrict page to only Administrators. I am finding that my auth factory is not completing before resolve returns answer to route. When i follow/watch the code path page gets loaded before the factory finishes. I am thinking i need to do better with promises and /or ".then()".
Any help would be appreciated. Thanks
My route code:
.when("/admin", {
templateUrl : "templates/admin.htm",
controller: 'AdminCtrl',
resolve : {
'auth' : function(AuthService){
return AuthService.isAdmin();
}
}
}).run(function($rootScope, $location){
$rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
if(rejection === 'Not Administrator'){
$location.path('/404');
}
if(rejection === 'Not Authenticated'){
$location.path('/404');
}
});
});
My factory:
app.factory('AuthService', function($q){
var isAuthenticated = Parse.User.current();
var isAdmin = undefined;
var currentUser = Parse.User.current();
return {
authenticate : function(){
if(isAuthenticated){
return true;
} else {
return $q.reject('Not Authenticated');
}
},
isAdmin : function(){
if(isAuthenticated){
userHasRole(currentUser, "Administrator").then(function(isRole) {
console.log((isRole)? "user is admin" : "user is not admin");
isAdmin = isRole;
return isAdmin;
}).then(function(isAdmin){
if(isAdmin){
return true;
} else {
return $q.reject('Not Administrator');
}
});
} else {
return $q.reject('Not Authenticated');
}
}
};
});
function userHasRole(user, roleName) {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", roleName);
query.equalTo("users", user);
return query.find().then(function(roles) {
if(roles.length > 0){
return true;
}else{
return false;
}
});
}
So close.
isAdminis returning undefined because you're missing the return statement beforeuserHasRole, so you're calling it, but thenisAdminhits the end of theif( isAuthenticated )block without a return value since it doesn't know it's supposed to return the result ofuserHasRole.