Is there an easier way to redirect to the login
state without using a resolve: {}
on each state? My app is growing and adding resolves like loginRequired
or skipIfLoggedIn
to individual states is cluttering my config blocks. If it helps, I'm using Satellizer for authentication.
Example module route config:
(function () {
'use strict';
angular
.module('uberCoolModule')
.config(configRoutes);
configRoutes.$inject = ['$stateProvider'];
function configRoutes ($stateProvider) {
$stateProvider
.state('login', {
url : '/login',
templateUrl : 'entrance/login/login.html',
data : { pageTitle: 'Login' },
resolve: {
skipIfLoggedIn: skipIfLoggedIn
}
})
.state('logout', {
url : '/logout',
controller : 'Logout'
resolve: {
loginRequired: loginRequired
}
})
.state('members', {
url : '/members',
controller : 'Home'
resolve: {
loginRequired: loginRequired
}
});
function skipIfLoggedIn($q, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.reject();
} else {
deferred.resolve();
}
return deferred.promise;
}
function loginRequired($q, $location, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.resolve();
} else {
$location.path('/login');
}
return deferred.promise;
}
}
})();
The easiest way is have a parent state that contains the authorization resolve and make all states that require login be children of that parent state.
A child state can not be accessed if resolve of any of it's ancestor states gets rejected
In this example going to
/members/profile
will fail ifloginRequired
is rejected