Angular Js 1: Auth check when change state

Controller:

...
$stateProvider
  .state('home.contact', {
    url: '/contact',
    resolve: {
      currentAuth: function(AuthFactory) {
        return AuthFactory.authPromise();
      }
    }
  });
...

Service:

...
.factory('AuthFactory', function ($q, $timeout, $rootScope) {
  var factoryObject = {
    authPromise: function () { /* promise to check is login or not */
      // Initialize a new promise
      var deferred = $q.defer();
      $timeout(function () {
        if ($rootScope.isAuthenticated) {
          deferred.resolve();
        } else {
          deferred.reject('AUTH_REQUIRED');
        }
      });
      return deferred.promise;
    }
  };
  return factoryObject;
})
...

Root Controller:

...
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
  if (error === 'AUTH_REQUIRED') {
    $state.go('home.dash');
  }
});
...
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s