How to do asynchronous task when defining a permission
prashant-pokhriyal opened this issue · 0 comments
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.