Konrad Straszewski Konrad Straszewski - 10 days ago 6
AngularJS Question

AngularJS authorization, resolve promise before angular permissions, check for permission

Im using angular-permission library. I defined some of permissions in run():

PermPermissionStore
.definePermission('isAuthorize', function () {
console.log('isAuthorize', OAuth.isAuthenticated());
return OAuth.isAuthenticated();
});


and then im checking users permissions in my routes.js

.state('app.main', {
abstract: true,
template: '<ui-view></ui-view>',
data: {
permissions: {
only: ['isAuthorize'],
redirectTo: {
default: 'login'
}
}
}
})


But i need to ask for profileData first on every refresh of the page, and permission-checking needs to run after i resolve promise. I've try to add resolve on parent State like this, but it still first asking for permisson for app.main and then promise is being resolved.

.state('app', {
abstract: true,
template: '<ui-view></ui-view>',
controller: function ($rootScope, userData) {
$rootScope.roles = userData.user.roles;
},
resolve: {
userData: ["ProfileFactory", function (ProfileFactory) {
return ProfileFactory
.get()
.$promise;
}]
}
})

Answer

I have not used angular permissions module. But if you are using ui.router it's very easy to implement by your own. Here is an example from the doc's.

https://ui-router.github.io/docs/latest/classes/transition.transition-1.html#onbefore

Sample use of onBefore hook

  .run(($transitions, $state, $injector) => {
    $transitions.onBefore({
      to: 'app.**'
    }, () => {
      const $window = $injector.get('$window');
      if (!$window.sessionStorage.getItem('user')) {
        return $state.target('login', $state.transition.params());
      }
      return true
    });
  });

Without login as test@gmail.com and password 123 you can't go to the home page

https://plnkr.co/edit/ZCN2hB34mMEmBJulyaAJ?p=preview