Angularjs中基于路线的授权

时间:2016-06-28 13:30:27

标签: javascript angularjs angular-routing

我希望通过AngularJS进行基于路由的授权。我试过但是找不到合适的解决方案。

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');
    });
});

0 个答案:

没有答案