Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to do asynchronous task when defining a permission #449

Open
prashant-pokhriyal opened this issue Feb 26, 2019 · 0 comments
Open

How to do asynchronous task when defining a permission #449

prashant-pokhriyal opened this issue Feb 26, 2019 · 0 comments

Comments

@prashant-pokhriyal
Copy link

angular-permission: v5.3.2
angularjs: v1.7.3

Following is the state definition for home. In that I'm checking whether user is authorized.

$stateProvider.state('500', home);
var home = {
  abstract: true,
  url: '/home',
  data: {
    permissions: {
      only: ['loggedin',],
      redirectTo: {
        loggedin: 'login',
      },
    }
  },
  templateUrl: 'components/home/home.view.html',
  controller: 'HomeCtrl as home'
};

Following is the permission definition for loggedin

PermPermissionStore.definePermission('loggedin', isAuthenticated);

function isAuthenticated(permissionName, transitionProperties) {
  // check if token is valid.
  if ($auth.isAuthenticated()) {
    return true;
  }
  // if not then refresh token
  return tokenRestService.refresh().then(
    function (response) {
      if (response != null) {
        $auth.setToken(response);
      }
    },
    function (response) {
      localStorage.removeItem('user');
    }
  );
}

But somewhat it is not working when I'm doing asynchronous call. If I change isAuthenticated function as follow, then it is working properly, but I need to refresh token if in case token is expired, otherwise redirect user to login page.

function isAuthenticated(permissionName, transitionProperties) {
  if ($auth.isAuthenticated()) {
    return true;
  }
  return false;
}

From the doc:

Sometimes you will need to call some a back-end api or do some other
asynchronous task to check if permission is still valid. For that you
can use promises and simply return them from validation function:

PermPermissionStore
  // Define user permission calling back-end
  .definePermission('hasValidSession', /*@ngInject*/function (Session) {
    // Let's assume that Session service calls backend API via $http and return promise:
    // -- $q.resolve() means that session is active 
    // -- $q.reject() means that session expired
    return Session.checkSession();
  });

But when I use a service in the definePermission, it is simply going through without any redirection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant