routeprovider resolve not restricting access with parse.com

33 Views Asked by At

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

There are 1 best solutions below

2
Jake T. On

So close.

isAdmin is returning undefined because you're missing the return statement before userHasRole, so you're calling it, but then isAdmin hits the end of the if( isAuthenticated ) block without a return value since it doesn't know it's supposed to return the result of userHasRole.