I'm using ui-router (0.2.18) and I want to restrict access to some pages if a user isn't logged in or isn't allowed to see something.
I came up with the solution below, but even though I'm not logged in, I still can see the page for a second, then I get redirected to the /login page. Clearly this is ugly, how can I do the check before loading the page? I'm trying to find a modular solution.
I do backend checks, so if a user isn't logged in, he/she can't see anything anyway, but this redirect thing bugs me.
Factory
angular.module('app.index').factory('Auth', ["$http", "$window", function($http, $window) {
return {
isLoggedIn: function() {
return $http.get('/whoami').then(function(rt) {
if (rt.data.length) {
return true;
}
}).catch(function(err) {
return $window.location.href = 'http://localhost/login';
});
}
};
}]);
Routes
angular.module('app.index.routes')
.run(
['$rootScope', '$state', '$stateParams', 'Auth',
function($rootScope, $state, $stateParams, Auth) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
if (toState.authenticate && !Auth.isLoggedIn()) {
console.log("please log in");
event.preventDefault();
} else {
console.log("you are logged in");
}
});
}
]
)
.config(
['$stateProvider', '$urlRouterProvider', '$locationProvider',
function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$stateProvider
.state('index', {
url: '/test',
authenticate: true, // if this is true, `toState.authenticate` becomes true
template: "auth check"
});
}
]);