首先,我使用 Iron Router 进行路由。在某些时候我可能会放弃它并自己编写,至少对于这个项目,因为我没有使用一半的功能,但现在这就是我所拥有的。
对于角色,我使用alanning:roles 包。再说一次,我可能会自己写,但它现在也能满足我的需要,所以我很满意。
接下来我编写了一个自定义包。在其中,我设置了一个用于登录和注销的模板,以及路由等。我还提供了一个实用程序类,它提供了一个名为 authenticationRequired 的函数。此函数将检查当前用户是否已登录,以及是否传递了角色以表明他们具有这些角色。代码如下所示:
AccountUtils.authenticationRequired = function(router, roles) {
if (!router) {
throw new Meteor.Error(500, 'Router is a required parameter');
}
if (!Meteor.loggingIn()) {
var currUser = Meteor.user();
if (currUser) {
if (roles) {
if (!Roles.userIsInRole(currUser, roles)) {
console.log('User was not in the required roles: %j, %j', currUser.roles, roles);
//throw new Meteor.Error(403, 'Access Denied');
Router.go('notAuthorized');
}
}
} else {
console.log('User not found');
Router.go(AccountUtils.settings.signinRoute);
}
}
}
现在,在我的Router 路由器中,我执行以下操作:
this.route('admin', {
path: '/admin',
onBeforeAction: function() { AccountUtils.authenticationRequired(this, ['ADMIN']); }
});
所有这一切都有一些活动部分,但这就是笑话。在路由的 onBeforeAction 中,检查用户是否具有所需的角色。如果没有,请将它们发送到 notAuthorize 页面。如果是,让他们通过。在这段代码中,我仍然遗漏了一些我尚未解决的部分,但它在大多数情况下都有效。
希望能给你一个起点。