angularjs: conditional routing in app.config

All we need is an easy explanation of the problem, so here it is.

I’m facing an issue in angular.js ui-router and not able to sort it out .

Issue:

I want user to access all routes defined in config if the user is EnterpriseAdmin and restrict some routes if the user is Enterprise user.

Routes are defined in config:

 var adocsModule = angular.module('myApp', ['ngResource', 'ngRoute','ui.bootstrap','ui.router', 'ngAnimate']) 
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
   $stateProvider.state('Registration', {
        url: "/Registration",
        templateUrl: '/Scripts/App/Registration/Templates/registration.html', controller: 'CoursesController'
    })
    .state('Registration.Instructors', {
         url: "/Instructors",
         templateUrl: '/Scripts/App/Instructors/Templates/instructors.html', controller: 'InstructorController'
    })
    .state('Registration.Courses', {
         url: "/Courses",
         templateUrl: '/Scripts/App/Instructors/Templates/courses.html', controller: 'CoursesController'
    })

Can someone help me solve this issue because as per my understanding app.js is loaded before all controllers . Surely I can check in the controller if the user is either EnterpriseAdmin or Enterprise user but up to that time all routes are already configured and the user has access to them.

Is there any way that I can do ajax call in the config block and then define a global variable and then by checking it i can configure some routes or not ??

Any help will be appreciated
Regards

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

$stateProvider.state has a data property. One way is to add auth option to your states.

$stateProvider.state('Registration.Instructors', {
     url: "/Instructors",
     templateUrl: '/Scripts/App/Instructors/Templates/instructors.html', 
     controller: 'InstructorController',
     data: { auth: "EnterpriseAdmin"}
})

then you can listen to event fired by ui-router before any state starts loading and prevent it if the user is unauthorized:

app.run(function($rootScope, user){
  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
    if ( toState.data.auth === 'EnterpriseAdmin' && !user.isAdmin() ) {
        event.preventDefault();
        return false;
    }
  })
});

You can even redirect him to another state, based on your ui logic:

 $state.go('login');

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply