我希望通过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');
});
});