angularjs ui-router generates infinite loop - angularjs

I am aware this question was discussed multiple times but the solutions didnt fit into my requirement. The quest is simple. If the user is not logged in the user should be redirected to login page. When i do it in $on, it generates infinite loop. Let me know what is the best solution.
var adminpanel = angular.module('administrator', ['ngMessages','ui.router','ui.bootstrap','ngCookies']);
adminpanel.config(function ($stateProvider, $urlRouterProvider) {
// $urlRouterProvider.otherwise("/login");
$urlRouterProvider.otherwise( function($injector, $location) {
var $state = $injector.get("$state");
$state.go("login");
});
$stateProvider
.state('login', {
url: "/login",
controller:"userCtrl",
templateUrl: "views/login.tpl.html",
permissions:{except:['admin']}
}
)
.state('menu', {
templateUrl: "views/menu.tpl.html",
controller:'adminCtrl',
permissions:{allow : ['admin']}
}
)
.state('menu.dashboard', {
url: "/dashboard",
templateUrl: "views/dashboard.tpl.html",
permissions:{allow : ['admin']}
}
)
});
adminpanel.run([ '$rootScope', '$state', '$stateParams','$cookieStore',function ($rootScope, $state, $stateParams,$cookieStore) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.$on('$stateChangeStart',function(event, toState, fromState){
if($rootScope.session == undefined && $cookieStore.get('name') == undefined){$rootScope.session={}}
else if($rootScope.session == undefined && $cookieStore.get('name') != undefined){
$rootScope.session={set:true, name : $cookieStore.get('name'), userid :$cookieStore.get('userid'), role:$cookieStore.get('role')};
};
//Added below lines as update
if(toState.name === "login"){
return;
}
//Added above lines as update
var authorized = true;
if(Object.keys($rootScope.session).length === 0){
event.preventDefault();
$state.go('login');
}
else if(Object.keys(toState.permissions).length !=0){
console.log($rootScope.session.role);
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('menu.dashboard');
};
});
}]);
Thanks in advance for help.
Update 1 :
The solution works fine. But if the user is logged in, the user shall not access the login page if he tries to hit it through address bar. So i created a permission parameter with except key.
But if the user hits login page through address bar, the login page is generated, which should not and it should be redirected to menu.dashboard.
Hope i am clear.

The point here, is to avoid redirection, if it already happened, if already redirected:
...
// never redirect to state, if already going there
if(toState.name === "login"){
return;
}
// evaluate some IF here only if we go to other state then login
if(Object.keys($rootScope.session).length === 0) {
event.preventDefault();
$state.go('login');
return;
}

Changed the if loop and it worked as required. Below is the working code.
if(Object.keys($rootScope.session).length === 0){
if(toState.name === "login"){
return;
}
else{
event.preventDefault();
$state.go('login');
}
}
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('menu.dashboard');
};

Related

routeprovider resolve not restricting access with parse.com

I want to restrict page to only Administrators. I am finding that my auth factory is not completing before resolve returns answer to route. When i follow/watch the code path page gets loaded before the factory finishes.
I am thinking i need to do better with promises and /or ".then()".
Any help would be appreciated. Thanks
My route code:
.when("/admin", {
templateUrl : "templates/admin.htm",
controller: 'AdminCtrl',
resolve : {
'auth' : function(AuthService){
return AuthService.isAdmin();
}
}
}).run(function($rootScope, $location){
$rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
if(rejection === 'Not Administrator'){
$location.path('/404');
}
if(rejection === 'Not Authenticated'){
$location.path('/404');
}
});
});
My factory:
app.factory('AuthService', function($q){
var isAuthenticated = Parse.User.current();
var isAdmin = undefined;
var currentUser = Parse.User.current();
return {
authenticate : function(){
if(isAuthenticated){
return true;
} else {
return $q.reject('Not Authenticated');
}
},
isAdmin : function(){
if(isAuthenticated){
userHasRole(currentUser, "Administrator").then(function(isRole) {
console.log((isRole)? "user is admin" : "user is not admin");
isAdmin = isRole;
return isAdmin;
}).then(function(isAdmin){
if(isAdmin){
return true;
} else {
return $q.reject('Not Administrator');
}
});
} else {
return $q.reject('Not Authenticated');
}
}
};
});
function userHasRole(user, roleName) {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", roleName);
query.equalTo("users", user);
return query.find().then(function(roles) {
if(roles.length > 0){
return true;
}else{
return false;
}
});
}
So close.
isAdmin is returning undefined because you're missing the return statement before userHasRole, so you're calling it, but then isAdmin hits the end of the if( isAuthenticated ) block without a return value since it doesn't know it's supposed to return the result of userHasRole.

AngularJS Dynamically Load Controller and Template based on Route

I am trying to dynamically load BOTH a template and controller based on the route (in Angular 1.6), pulling from the current directory architecture.
app
|__login.module.js
|__home.controller.js
|__login.factory.js
|__home.view.html
|__404.view.html
|__index.html
Currently, the below code works to pull the proper template, but the controller won't load:
angular.module('common.auto-loading-routes', []).config(function($routeProvider){
function getTemplate(routeParams){
var route = (routeParams.current) ? routeParams.current.params.route : routeParams.route;
var directory = route.split('/');
directory = directory.filter(function(entry) { return entry.trim() != ''; });
var page = directory[directory.length - 1];
directory.splice(-1,1);
directory = directory.join('/');
return directory + '/' + page +'.view.html';
}
function getController(routeParams){
//I think I need a promise here, but I don't know how to write it
routeParams = routeParams.route.split('/').join('.');
return routeParams + 'controller';
}
$routeProvider.when('/:route*', {
controller: function($routeParams) { //does not work
return getController($routeParams);
},
templateUrl: function($routeParams) { //works
return getTemplate($routeParams);
},
resolve: {
check: function($route, $http, $location){
return $http.get(getTemplate($route)).then(function(response){
if (response.status !== 404){
return true;
} else {
$location.path('404');
}
});
}
}
}).otherwise('/404');
});
I understand that controllers need to be present at the start of the app, but I am unable to write a proper resolve with a promise statement.
Can someone help me right a resolve with a simple promise that returns a string of the controller name based on the route?
I was able to get it working by not including the controller in the routing at all. Instead I put the ng-controller attribute in the view I was loading.
This worked!
angular.module('common.auto-loading-routes', []).config(function($routeProvider){
function getTemplate(routeParams){
var route = (routeParams.current) ? routeParams.current.params.route : routeParams.route;
var directory = route.split('/');
directory = directory.filter(function(entry) { return entry.trim() != ''; });
var page = directory[directory.length - 1];
directory.splice(-1,1);
directory = directory.join('/');
return directory + '/' + page +'.view.html';
}
$routeProvider.when('/:route*', {
templateUrl: function($routeParams) { //works
return getTemplate($routeParams);
},
resolve: {
check: function($route, $http, $location){
return $http.get(getTemplate($route)).then(function(response){
if (response.status !== 404){
return true;
} else {
$location.path('404');
}
});
}
}
}).otherwise('/404');
});
In the HTML of that view, I just put ng-controller="home.controller"(or whatever controller is appropriate)

user role on UI-STATE

in my app i have many different USER ROLE's.
And on one state i need to set different roles. Bellow code, with only one user role, working ok
.state('distributor-dashboard', {
url: '/distributor-dashboard',
templateUrl: 'assets/html_templates/distributor-dashboard/distributor-dashboard.html',
controller: 'distributorDashboardCtrl',
authentication: {role: admin}
})
But, if i try to add another roles, they don' work here is example
.state('distributor-dashboard', {
url: '/distributor-dashboard',
templateUrl: 'assets/html_templates/distributor-dashboard/distributor-dashboard.html',
controller: 'distributorDashboardCtrl',
authentication: {role: ["admin" || "user"]}
})
Here is where i check USER ROLE
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
$rootScope.previousState = fromState.name;
var auth = authService.authentication.isAuth;
if (toState.name !== "login" && toState.name !== "signup" && toState.name !== "resset-password" && toState.name !== "new-password" && toState.name !== "account-activation" && auth === false) {
event.preventDefault();
$state.go('login', {});
}
var role = authService.authentication.role;
if (toState.authentication !== undefined && toState.authentication.role !== role) {
event.preventDefault();
$state.go('login', {});
}
}
Thnx.
I found a solution. It is necessary to set on STATE under authentification any role that we want to use.
authentication: {roles: ["admin", "user"]}
and then make a check if the roll there is in the allowed rolls
var userRole = authService.authentication.role;
if (toState.authentication !== undefined && toState.authentication.roles.indexOf(userRole) < 0) {
event.preventDefault();
$state.go('login', {});
}
I use indexOf for check, is roles in array. If someone have any question, feel free to ask

Common service for sessionstorage in angularjs

Hi in my application i am setting the values in login controller and getting in all the other js files, other than this how to use a common service for setting storage and getting that storage in required js files
My login controller
app.controller('LoginController',function(loginService, $rootScope,$scope, $http,$location) {
$scope.login = function () {
$scope.log=loginService.getLogin( $scope.emailId , $scope.password).
then(function (response) {
console.log($scope.log);
console.log(response)
if (response.data.LoginVerificationResult.length === 0) {
alert('details are not Available for this emailId');
$scope.error=true;
} else {
$rootScope.name=response.data.LoginVerificationResult[0].UserName;
$scope.abc=response.data.LoginVerificationResult[0].UserType
console.log($scope.abc+"from.......");
sessionStorage.setItem("EmaiId",$scope.emailId);
sessionStorage.setItem("User Id",response.data.LoginVerificationResult[0].UserID);
sessionStorage.setItem("UserName",response.data.LoginVerificationResult[0].UserName);
sessionStorage.setItem("UserType",response.data.LoginVerificationResult[0].UserType);
$scope.UserType = sessionStorage.getItem("UserType");
console.log($scope.UserType +"from login controller")
$location.path('/dashboard')
}
});
};
});
My changepassword file
app.controller("ChangePwdController", function($scope, $http, $location,
BaseUrl, changePwdService) {
//$scope.roleId = sessionStorage.getItem("Role ID");
/* $scope.UserType = sessionStorage.getItem("UserType");*/
$scope.username = sessionStorage.getItem("UserName");
$scope.userType = sessionStorage.getItem("UserType");
$scope.EmpName=sessionStorage.getItem("EmpName");
$scope.patientName=sessionStorage.getItem("PatientName")
$scope.changePwd = function() {
$scope.emailAddress = sessionStorage.getItem("EmaiId");
console.log($scope.emailAddress)
var data = {
'emailAddress' : $scope.emailAddress,
'currentPassword' : $scope.opassword,
'newPassword' : $scope.npassword
};
console.log("Hi")
$scope.pwd=changePwdService.postChangePwd(data).success(
function(resp) {
$scope.PostDataResponse = data;
console.log($scope.pwd)
console.log($scope.PostDataResponse);
if (resp.ResetPasswordResult === true) {
alert("Successfully changed");
console.log("success")
$location.path('/dashboard');
} else {
console.log("fail")
alert("Enter valid current password")
}
})
}
})
Is there any alternative way to set and get in one file
There are ways in which you can achieve the same. Please refer this here.

Authorization Service fails on page refresh in angularjs

Implemented the authorization using the POST
The problem is when i go to a privileged page say '/admin' it works but when i refresh the page
manually, the admin page is redirecting to the '/unauthorized' page
Permissions service
angular.module('myApp')
.factory('PermissionsService', function ($rootScope,$http,CookieService) {
var permissionList;
return {
setPermissions: function(permissions) {
permissionList = permissions;
$rootScope.$broadcast('permissionsChanged')
},
getPermissions: function() {
var roleId = 5
if(CookieService.getLoginStatus())
var roleId = CookieService.getUserData().ROLE_ID;
return $http.post('api/user-permissions', roleId).then(function(result){
return result.data;
});
},
hasPermission: function (permission) {
permission = permission.trim();
return _.some(permissionList, function(item) {
if(_.isString(item.name))
return item.name.trim() === permission
});
}
};
});
hasPermissions directive
angular.module('myApp')
.directive('hasPermission', function(PermissionsService) {
return {
link: function(scope, element, attrs) {
if(!_.isString(attrs.hasPermission))
throw "hasPermission value must be a string";
var value = attrs.hasPermission.trim();
var notPermissionFlag = value[0] === '!';
if(notPermissionFlag) {
value = value.slice(1).trim();
}
function toggleVisibilityBasedOnPermission() {
var hasPermission = PermissionsService.hasPermission(value);
if(hasPermission && !notPermissionFlag || !hasPermission && notPermissionFlag)
element.show();
else
element.hide();
}
toggleVisibilityBasedOnPermission();
scope.$on('permissionsChanged', toggleVisibilityBasedOnPermission);
}
};
});
app.js
var myApp = angular.module('myApp',['ngRoute','ngCookies']);
myApp.config(function ($routeProvider,$httpProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/module/public/index.html',
header: 'app/partials/header.html',
footer: 'app/partials/footer.html'
})
.when('/login', {
templateUrl: 'app/module/login/login.html',
header: 'app/partials/header.html',
footer: 'app/partials/footer.html'
})
.when('/home', {
templateUrl: 'app/module/home/home.html',
header: 'app/partials/header.html',
footer: 'app/partials/footer.html'
})
.when('/register', {
templateUrl: 'app/module/register/register.html',
header: 'app/partials/header.html',
footer: 'app/partials/footer.html'
})
.when('/admin', {
templateUrl: 'app/module/admin/admin.html',
header: 'app/partials/header.html',
footer: 'app/partials/footer.html',
permission: 'admin'
})
.when('/unauthorized', {
templateUrl: 'app/partials/unauthorized.html',
header: 'app/partials/header.html',
footer: 'app/partials/footer.html'
})
.otherwise({redirectTo: '/'});
$httpProvider.responseInterceptors.push('securityInterceptor');
});
myApp.provider('securityInterceptor', function() {
this.$get = function($location, $q) {
return function(promise) {
return promise.then(null, function(response) {
if(response.status === 403 || response.status === 401) {
$location.path('/unauthorized');
}
return $q.reject(response);
});
};
};
});
myApp.run(function($rootScope, $location, $window, $route, $cookieStore, CookieService, PermissionsService) {
PermissionsService.getPermissions().then(function(permissionList){
PermissionsService.setPermissions(permissionList);
});
// Check login status on route change start
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
if(!CookieService.getLoginStatus() && $location.path() != '/register' && $location.path() != '/login') {
$location.path("/");
$rootScope.$broadcast('notloggedin');
}
if(CookieService.getLoginStatus() && $location.path() == '/login') {
$location.path("/home");
}
var permission = next.$$route.permission;
if(_.isString(permission) && !PermissionsService.hasPermission(permission))
$location.path('/unauthorized');
});
// Adds Header and Footer on route change success
$rootScope.$on('$routeChangeSuccess', function (ev, current, prev) {
$rootScope.flexyLayout = function(partialName) { return current.$$route[partialName] };
});
});
CookieService
angular.module('myApp')
.factory('CookieService', function ($rootScope,$http,$cookieStore) {
var cookie = {
data: {
login: false,
user: undefined
},
saveLoginData: function(user) {
cookie.data.login = true;
cookie.data.user = user;
$cookieStore.put('__iQngcon',cookie.data);
},
deleteLoginData: function() {
cookie.data.login = false;
cookie.data.user = undefined;
$cookieStore.put('__iQngcon',cookie.data);
},
getLoginStatus: function() {
if($cookieStore.get('__iQngcon') === undefined)
return cookie.data.login;
return $cookieStore.get('__iQngcon').login;
},
getUserData: function() {
return $cookieStore.get('__iQngcon').user;
}
};
return cookie;
});
It seems like the permissions data are lost on page refresh. Is there any other way i can solve the problem? Or is there any problem with the code??
when i refresh the page manually, the admin page is redirecting to the
'/unauthorized' page
Isn't that expected behavior? If you reload the page; then all UI state is lost; it is just like shutting down the app and starting from scratch.
It seems like the permissions data are lost on page refresh. Is there
any other way i can solve the problem? Or is there any problem with
the code??
If you want to be able to retain UI state after a page reload, you'll have to retain the Login information somehow, such as in a browser cookies. When the app loads; check for that cookie value. If it exists, you can load the user info from the database, essentially mirroring a login.
I'd be cautious about storing actual user credentials in a cookie without some type of encryption.
One approach I've used is to store a unique user key which can be sent to the DB to load user info. Sometimes this may be a UUID associated with the user, Avoid using an auto-incrementing primary key because that is easy to change to get access to a different user's account.
Well had to think for some time and made the following change for it to work. It may not be the best practice but ya worked for me. Would appreciate if anyone suggested me a better solution in the comments if found.
myApp.run(function($rootScope, $location, $window, $route, $cookieStore, CookieService, PermissionsService) {
var permChanged = false;
PermissionsService.getPermissions().then(function(permissionList){
PermissionsService.setPermissions(permissionList);
});
// Check login status on route change start
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
console.log('$routeChangeStart');
if(!CookieService.getLoginStatus() && $location.path() != '/register' && $location.path() != '/login') {
$location.path("/");
$rootScope.$broadcast('notloggedin');
}
if(CookieService.getLoginStatus() && $location.path() == '/login') {
$location.path("/home");
}
$rootScope.$on('permissionsChanged', function (ev, current, prev) {
permChanged = true;
});
if(CookieService.getLoginStatus() && permChanged) {
var permission = next.$$route.permission;
if(_.isString(permission) && !PermissionsService.hasPermission(permission))
$location.path('/unauthorized');
}
});
// Adds Header and Footer on route change success
$rootScope.$on('$routeChangeSuccess', function (ev, current, prev) {
$rootScope.flexyLayout = function(partialName) { return current.$$route[partialName] };
});
});
What i did was wait for the permissions to be set and then use the permissionChanged broadcast to set a permChanged variable to true and then combined with if user loggedin status and permchanged had to check the permissions if had
$rootScope.$on('permissionsChanged', function (ev, current, prev) {
permChanged = true;
});
if(CookieService.getLoginStatus() && permChanged) {
var permission = next.$$route.permission;
if(_.isString(permission) && !PermissionsService.hasPermission(permission))
$location.path('/unauthorized');
}

Resources