Angular ui-router: how to prevent access to a state

Asked
Active3 hr before
Viewed126 times

6 Answers

staterouterangularprevent
90%

This will trigger an error, preventing the user from accessing this state if they are not allowed., in resolve: { security: ['$q', function($q){ if(/*user is not admin*/){ return $q.reject("Not Authorized"); } }] } - how can i get $q – Pathik Vejani Sep 16 '15 at 11:40 ,If you need to show an error, or send the user to a different state, handle the $stateChangeError event:,Hello I'm new to angularJS and have been trying to prevent access to certain states based on user critera.

The best way I have found to do this uses resolve:

    $stateProvider.
    state('createCourse', {
       url: '/courses/create',
       templateUrl: 'modules/courses/views/create-course.client.view.html',
       resolve: {
          security: ['$q', function($q) {
             if ( /*user is not admin*/ ) {
                return $q.reject("Not Authorized");
             }
          }]
       }
    });

If you need to show an error, or send the user to a different state, handle the $stateChangeError event:

$rootScope.$on('$stateChangeError', function(e, toState, toParams, fromState, fromParams, error) {

         if (error === "Not Authorized") {
            $state.go("notAuthorizedPage");
         }

If you want to check for admin access on all states, you could use a decorator to add the resolve to all states. Something like this:

$stateProvider.decorator('data', function(state, parent) {
         var stateData = parent(state);
         var data = stateData.data || {};

         state.resolve = state.resolve || {};
         if (data.needAdmin) {
            state.resolve.security = ['$q', function($q) {
               if ( /*user is not admin*/ ) {
                  return $q.reject("Not Authorized");
               }
            }];
            return stateData;
         });
load more v
88%

Depending on authentication mechanism, that we will create the appropriate check on state resolve. I will use JSON Web Token and Satellizer to demonstrate this.,In a typical web application, there requires to protected many routes from users. For example, protected admin routes from normal users, or users must have logged in to view the contents …,We will need to create two functions _redirectIf*** to handle to the authentication check that will return a promise.,For UI Router, we will make use of the resolve property to do this. The concept is similar in backend, which is usually known as Middleware. I work with Laravel much, therefore, it is very familiar with me.

Depending on authentication mechanism, that we will create the appropriate check on state resolve. I will use JSON Web Token and Satellizer to demonstrate this.

angular.module(‘app’, [‘ui.router’, ‘satellizer’]).config(function($stateProvider, $urlRouterProvider, $authProvider) {
   $stateProvider.state(‘login’, {
      url: ‘ /login’,      templateUrl: ‘…’,      resolve: {        skipIfAuthenticated: _skipIfAuthenticated      },      controller: ‘LoginCtrl as login’    })    .state(‘home’, {      url: ‘/home’,
      templateUrl: ‘…’,
      resolve: {
         redirectIfNotAuthenticated: _redirectIfNotAuthenticated
      },
      controller: ‘HomeCtrl as home’
   })
})
load more v
72%

UI-Router applications behave like a state machine.,The basic building block of a UI-Router application is a UI-Router state. A UI-Router state usually corresponds to a feature (or place) in the application in terms of the overall UI and navigation. Some examples of states might be dashboard, messages, shoppingcart, or blogentry.,Unlike states in a traditional state machine, UI-Router states can be nested inside each other. A parent state can have multiple children, forming a tree of states.,The child state’s view usually renders inside a viewport that the parent state created. This is referred to as Nested Views

UI-Router States

The basic building block of a UI-Router application is a UI-Router state.
A UI-Router state usually corresponds to a feature (or place) in the application in terms of the overall UI and navigation. Some examples of states might be dashboard, messages, shoppingcart, or blogentry.

dashboard

UI-Router States

The basic building block of a UI-Router application is a UI-Router state.
A UI-Router state usually corresponds to a feature (or place) in the application in terms of the overall UI and navigation. Some examples of states might be dashboard, messages, shoppingcart, or blogentry.

messages

UI-Router States

The basic building block of a UI-Router application is a UI-Router state.
A UI-Router state usually corresponds to a feature (or place) in the application in terms of the overall UI and navigation. Some examples of states might be dashboard, messages, shoppingcart, or blogentry.

shoppingcart

UI-Router States

The basic building block of a UI-Router application is a UI-Router state.
A UI-Router state usually corresponds to a feature (or place) in the application in terms of the overall UI and navigation. Some examples of states might be dashboard, messages, shoppingcart, or blogentry.

blogentry
load more v
65%

Hello I'm new to angularJS and have been trying to prevent access to certain states based on user critera.,This, from ui-router's FAQ describes exactly what I want to do, but I cant get it to work properly. What do I need to but in the data object exactly to accomplish this?,Wrap $state.go in a $timeout() to allow the original transition to complete before redirecting.,1) Why is the parent state being reinitialized when .go is called on a child state?

Here is my code:

angular.module('courses').config(['$stateProvider',
   function($stateProvider) {
      // Courses state routing
      $stateProvider.
      state('listCourses', {
         url: '/courses',
         templateUrl: 'modules/courses/views/list-courses.client.view.html'
      }).
      state('createCourse', {
         url: '/courses/create',
         templateUrl: 'modules/courses/views/create-course.client.view.html',
         data: {
            needAdmin: true
         }
      }).
      state('viewCourse', {
         url: '/courses/:courseId',
         templateUrl: 'modules/courses/views/view-course.client.view.html'
      }).
      state('editCourse', {
         url: '/courses/:courseId/edit',
         templateUrl: 'modules/courses/views/edit-course.client.view.html',
         data: {
            needAdmin: true
         }
      });

   }
]);

angular.module('courses').run(['$rootScope', '$state', 'Authentication', function($rootScope, $state, Authentication) {
   $rootScope.$on('$stateChangeStart', function(e, to) {

      var auth = Authentication;

      console.log(auth.user.roles[0]);
      if (to.data.needAdmin && auth.user.roles[0] !== 'admin') {
         e.preventDefault();
         $state.go('/courses');
      }

   });
}]);
load more v
75%

As the UI Router framework evaluates this directive, the anchor is transformed to have the appropriate URL value. For example:,One of the advantages of using the UI Router framework is the ability to enforce separation of concerns. As the articles state implements a resolve object, the raw array of articles is injected into the controller.,The Angular UI Router framework is an abstraction layer for routing that features a declarative approach to navigation,In order to start working with the UI Router framework, you have to configure the page. The first step is to add the application name into the ng-app attribute of the HTML element on the page. Here, the app name is simply app.

Perhaps the best way to appreciate the problem that the UI Router framework hopes to solve is to consider the nature of the Web. In most applications when you create a link to a page, you define an explicit URL path. For instance, if you wanted to navigate to your site's Products page, you may have a URL like:

http: //www.example.com/products
load more v
40%

There are routes that I don't want non-logged in users to access. For example, /home and /login are okay for anonymous users./dashboard should only be for those that are logged in.,http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider,I want it so if a user tries to access /dashboard in the future without being logged in, they are not able to.,The resolve block of your state definition is the best place to put logic that checks authentication

controllers.js

var controllers = angular.module('controllers', [])
// Login Controller -- This handles the login page that the user can enter
// enter his username & password.
controllers.controller('loginController', function($scope, $state, $location, LoginService) {
   $scope.email = "";
   $scope.password = ""

   $scope.login = function() {
      var data = ({
         email: "test",
         password: "ayylmao"
      })
      LoginService.login(data).then(function(res) {
            console.log(res);
         })
         .catch(function(err) {
            console.log("ERROR!");
            console.log(err);
            $state.go('dashboard')
         })
   }
})
load more v

Other "state-router" queries related to "Angular ui-router: how to prevent access to a state"