我会考虑使用类似这个项目的东西:https ://github.com/Narzerus/angular-permission
根据文档:
权限通过使用简单的概念让您决定谁可以访问它们,从而帮助您控制您的路线。我已经看过很多关于访问控制实现的大型教程,它们可能会让人不知所措。所以我给你带来了一个简单、强大、直接的解决方案。
这是一个关于如何在 Angular 中实现它的简单示例:
定义权限:
angular.module('barModule', ['permission', 'user'])
.run(function (PermissionStore, User, $q) {
PermissionStore
// Define user permission calling back-end
.definePermission('user', function (stateParams) {
// This time we will return a promise
// If the promise *resolves* then the user has the permission, if it *rejects* (you guessed it)
// Let's assume this returns a promise that resolves or rejects if session is active
return User.checkSession();
})
PermissionStore
// A different example for admin
.definePermission('admin', function (stateParams) {
var deferred = $q.defer();
User.getAccessLevel()
.then(function (data) {
if (data.accessLevel === 'admin') {
deferred.resolve();
} else {
deferred.reject();
}
}
.catch(function () {
// Error with request
deferred.reject();
});
return deferred.promise;
});
});
定义角色:
angular
.module('fooModule', ['permission', 'user'])
.run(function (RoleStore, User) {
RoleStore
// Permission array validated role
// Library will internally validate if 'user' and 'editor' permissions are valid when checking if role is valid
.defineRole('admin', ['user', 'editor']);
RoleStore
// Server side validated role
.defineRole('accountant', [], function (stateParams) {
// Let's assume that we are making a request to server here and return response as promise
return User.hasRole('accountant');
});
});
路线中的用法:
$stateProvider
.state('dashboard', {
url: '...',
data: {
permissions: {
except: ['anonymous'],
redirectTo: 'login'
}
}
});
视图中的用法:
<div permission only="'loggedIn'">
<span>Congrats! You are logged in.</span>
</div>