You can create a function with a promise that verifies if the user is authenticated and if not, that redirects to the login.
Then, in each state that a logged-in user is required, you solve that function. For example:
$stateProvider
.state('home', {
url: '/',
templateUrl: 'components/home/home.html',
controller: 'homeCtrl as home',
resolve: {
authenticate: authenticate
}
})
.state('login', {
url: '/login',
templateUrl: 'components/login/login.html',
controller: 'loginCtrl as login'
});
// Además, cuando el usuario hace login almaceno su token en el localstorage.
// Al iniciar la aplicación si no hay token es que no hay usuario logueado,
// por lo que redirijo directamente al login.
if (!(typeof window.localStorage.token !== 'undefined' &&
window.localStorage.token !== null)) {
$urlRouterProvider.otherwise('/login');
} else {
$urlRouterProvider.otherwise('/');
}
Being my function to authenticate the following:
function authenticate($ionicPlatform, $q, Auth) {
// Auth es mi propio servicio que se encarga del login/logout.
if (Auth.isLogged()) {
return $q.resolve();
} else {
Auth.logout();
return $q.reject();
}
}
and Auth.logout () I have a $state.go('login');
at the end to direct the login.