Block routes according to the user's permission AngularJS

1

I have a system where I log in to a user, if all right, the server returns an object and I store that object in sessionStorage . I can retrieve this object to do some validations, eg render some components according to the user's permission.

I would like to block some routes according to the user's permission, that is, if the user has permissão = 2 he will not be able to access this route: /usuario

The route configuration is as follows:

angular.module("oraculo").config(function($routeProvider){

    $routeProvider.when("/usuario", {
        templateUrl: "public/views/usuario.html",
        controller: "usuarioCtrl"
    });


    $routeProvider.otherwise({redirectTo: "/login"});

});
    
asked by anonymous 02.10.2015 / 14:45

1 answer

2

Monitor the queue of notifications by event $locationChangeStart , and if necessary cancel the event:

$scope.$on('$locationChangeStart', function(event) {
    if (!validaPermissoesUsuario()) {
       event.preventDefault();
    }
});

Alternatively, redirect the user:

$scope.$on('$locationChangeStart', function(event) {
    if (!validaPermissoesUsuario()) {
       $location.path( "/naoAutorizado" );
    }
});

Another option is to implement, in route configuration, a otherwise term that interprets and manipulates the required route:

$routeProvider.otherwise({
    redirectTo: function() {
        //Descreva sua validação de permissões aqui.
        return '/naoAutorizado';
    }
});

However, the way I would recommend it would be by evaluating the service side. If the logged-in user does not have permissions, return 401 Unauthorized and set your view accordingly.

    
02.10.2015 / 14:54