0
Hello person I am creating an authentication system and check levels with Angularjs, I am using stateChangeStart to validate permissions in view.
Only when I use $state.go('app.home'); it goes into infinite loop.
My code is this::
$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 tried too:
var array = toState.permissions['except'];
if(array.indexOf($rootScope.session.role) > 0)
{
authorized = false;
}
Thank you.
What is your problem? It’s good that you indicate exactly where the problem is and what the desired result is so that users don’t have to read your entire code and guess what might be wrong.
– Vinicius Zaramella
That’s right, I’m sorry
– Victor Rajesh