How to restrict access to routes in Angularjs?

Asked

Viewed 1,021 times

5

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

2 answers

8

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

Follow an example of 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");
            }
        }
        });
  });

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 the 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
            });
    }]);
  • and how the rule works!?

  • can be a global variable? of type $rootScope.logged in?

  • @Eltontomaslaice this goes according to your business rule, for example if(user.Podeacessar), is a validation as you want. and to use $rootScope, simply Cvoce injects it into the controller to apply the event to. $on, I use the main module in the . run function()

  • thank you so much for your help!

  • @Eltontomaslaice worked out ? That’s what you needed ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.