Hello, I'm creating an authentication and verifying system with Angularjs, I'm using stateChangeStart to validate the permissions in view.
Only when I use $ state.go ('app.home'); it goes into infinite loop.
My code is as follows:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams)
{
if (typeof(toState) !== undefined){
$templateCache.remove(toState.templateUrl);
}
if($rootScope.session == undefined && $cookieStore.get('user') == undefined)
{
$rootScope.session = {};
}else if($rootScope.session == undefined && $cookieStore.get('user') != undefined)
{
$rootScope.session = {
set:true,
name : $cookieStore.get('user')['name'],
userid : $cookieStore.get('user')['id'],
role: $cookieStore.get('user')['nivel'],
email: $cookieStore.get('user')['email']
};
}
if(toState.name === "page.login" || toState.name === "page.register")
{
return;
}
var authorized = true;
if(Object.keys($rootScope.session).length === 0)
{
event.preventDefault();
$state.go('page.login');
return;
}else if(Object.keys(toState.permissions).length !== 0) {
angular.forEach(toState.permissions, function(value, key)
{
angular.forEach(value, function(role)
{
if(key === 'except' && role === $rootScope.session.role)
{
authorized = false;
}else if(key === 'allow' && role !== $rootScope.session.role)
{
authorized = false;
};
});
});
}
if(!authorized){
event.preventDefault();
$state.go('app.home');
return;
};
}); // Start View
I've also tried:
var array = toState.permissions['except'];
if(array.indexOf($rootScope.session.role) > 0)
{
authorized = false;
}
Thank you.