2

I want a route based authorization through AngularJS. I tried but wasn't able to find the right solution.

var app = angular.module('app', []);    
var mycontroller = app.controller('mycontroller', function ($rootScope, authService) {

});

app.service('authService', function ($http, $rootScope) {
    var userRole = ['ROLE_USER']; // this will come from database,
    var userRoleRouteMap = {
        'ROLE_ADMIN': [ '/dashboard', '/about-us', '/authError' ],
        'ROLE_USER': [ '/usersettings', '/usersettings/personal', '/authError']
    };

    return {
        userHasRole: function (role) {
            for (var j = 0; j <= userRole.length; j++) {
                if (role == userRole[j]) {
                    return true;
                }
            }
            return false;
        },
        isUrlAccessibleForUser: function (route) {
            for (var i = 0; i <= userRole.length; i++) {
                var role = userRole[i];
                var validUrlsForRole = userRoleRouteMap[role];
                if (validUrlsForRole) {
                    for (var j = 0; j <= validUrlsForRole.length; j++){
                        if (validUrlsForRole[j] == route)
                            return true;
                    }
                }
            }
            return false;
        }
    };
});

app.run(function ($rootScope) {
    // This Block is not working i want to see the url change every time from here.
    $rootScope.$on("$locationChangeStart", function (event, next, current) {   
        // handle route changes        
        console.log(next); // this is not working
        if (!authService.isUrlAccessibleForUser("/about-us"))
            $location.path('/authError');
    });
});
C14L
  • 12,153
  • 4
  • 39
  • 52
  • there should be a method preventDefault() in event object in order to cancel the current event. You have to call it and then use $location.path(). Did you try `$routeChangeStart` ? You will probably have better result with it. – Walfrat Jun 28 '16 at 13:35
  • Walfrat i tried it with $routeChangeStart but not find the solution could you provide the better – Arvind Chaudhary Jun 28 '16 at 16:28
  • It seems you have to use $locationChangeStart in fact : see http://stackoverflow.com/questions/16344223/angularjs-cancel-route-change-event – Walfrat Jun 29 '16 at 06:50

0 Answers0