I am trying to implement some security in my app using angular ui-router's resolve function. I've fashioned a solution based on solution #2 in the 2nd answer to this question: Angular ui-router: how to prevent access to a state
It works fine, except that the controller for routes I do not want to allow the user to navigate to is still instantiated. I'm more or less following John Papa's recommendations for Angular, so I have an activate function in each controller. I could double check authentication here, but that would require repetitive work be done to each of my controllers. Also, eliminating the use of $timeout in the authenticate function from the original answer doesn't seem to have an adverse effect.
Here is how I am setting up a route to handle this:
$stateProvider.state('orderqueue', {
url: "/orderqueue",
templateUrl: "views/orderqueue.html",
controller: 'orderQueueController',
controllerAs: 'orders',
role: 'Order Admin',
resolve: {authenticate: authenticate}
});
and my authenticate function looks like this:
function authenticate($q,$state,$timeout, UserService) {
(new UserService()).$getUser().then(
function(user) {
var role = ($state.current.role) ? $state.current.role :$state.current.name ;
// alert(role) ;
if (user.userName == 'wmfeltman') {
return $q.when()
} else
{
// $timeout(function() {
// This code runs after the authentication promise has been rejected.
// Go to the log-in page
$state.go('login')
// })
// Reject the authentication promise to prevent the state from loading
return $q.reject()
}
}
)
}
Is there a way to get resolve to fire before the controller is instantiated? The docs seem to indicate that is how it's supposed to work, but it's not.