5👍
✅
Assuming that all of your authentication logic is already inside something like AuthService
, wouldn’t it be possible to do the following?
// 'AuthService' injected earlier
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if (!AuthService.isAuthenticated()) {
// prevent navigation. don't go anywhere;
// navigation will occur inside AuthService
event.preventDefault();
AuthService.setNextState(toState.name);
AuthService.authenticateWithServer();
}
// proceed normally if user is already authenticated
});
Then, your AuthService
:
app.service('AuthService', function($rootScope, $http, $state) {
var next;
this.setNextState = function(nextState) { next = nextState; };
this.isAuthenticated = function() { ... };
this.authenticateWithServer = function() {
$http.post('/authen', { ... }).success(function(user){
// house-keeping
$rootScope.user = user;
// navigate by state name
$state.go(next);
}).error(function(error) {
// navigate to login screen
$state.go('login');
});
};
});
This way, your state definition is clean, and the authentication logic is isolated in one place. You can also be sure that navigation will never take place until you have all the info you need.
Source:stackexchange.com