How to restrict access to routes in angularjs?

5

How do I restrict access on some routes, and allows logged-in users to access your content on Angulajs.

    
asked by anonymous 25.08.2015 / 10:31

2 answers

8

For user validation you could implement the $ routeChangeStart event, which is triggered whenever a route is triggered, so you can validate the user and redirect it to another route if you are not authorized.

Here is an example code:

var app = angular.module("Test", []).
//Simple Routes
    config(function($routeProvider, $locationProvider) {
        $routeProvider
            .when("/restricted",{ templateUrl: "index.html" })
            .when("/login", { templateUrl: "login.html", controller: "LoginCtrl" })
            .otherwise( { redirectTo: "/login" });
    })
  .run(function($rootScope, $location, accessControl) {
        $rootScope.$on( "$routeChangeStart", function(event, next, current) {

            //Checking the accessControl service
            if(!accessControl.canAccess(next)){
                //if can´t access the future route we can redirect him to the login page
                $location.path("/login");
            }
        }
        });
  });
    
25.08.2015 / 12:57
1

If you are using ui.router, you can use the event,

$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState){
   if(regra) //Sua regra aqui.
      event.preventDefault(); // Utilizando esse método você PARA o ciclo natural, ou seja não vai mais executar a chamada da rota, assim você pode fazer seu tratamento.
});

The same goes for event $routeChangeStart ,

Edit: Changes to show according to comments.

.run(['$rootScope', function($rootScope){

            $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState){
               if(!$rootScope.logado) //a variavel logado está false.
                  event.preventDefault(); // quando falar, preventDefault, não vai mudar a rota, e continuar no msm 'current' que você se encontra
            });
    }]);
    
25.08.2015 / 14:02