流星用户帐户和alanning流星角色-登录时检查角色

meteor-useraccounts and alanning meteor-roles - Check role on sign-in

本文关键字:角色 流星 检查 登录 alanning 用户      更新时间:2023-09-26

是否可以在登录时检查用户角色,如果用户在"admin"角色中显示一个页面,如果在"basic user"角色中则显示另一个页面(转到另一条路线)。

让我们看看useraccounts:iron-routing包文档的Routes部分。

这应该可以解决你的问题

AccountsTemplates.configureRoute('signIn', {
  redirect: function(){
    var user = Meteor.user();
    if (user && Roles.userIsInRole(user, ['admin'])) {
      Router.go('admin');
    }
    else {
      Router.go('home');
    }
  }
});

请注意检查您是否可以从客户端访问用户roles字段:让我们检查allanning:roles官方文档

要为用户定义默认角色,我使用以下方法:

// server    
Accounts.onLogin(function(user) {
        var user = user.user;
        var defaultRole = ['student'];
        if (!user.roles){
            Roles.addUsersToRoles(user, defaultRole)
        };
    })

我正在使用流星用户帐户和alanning流星角色包,这对我来说很好。

如果我没有过时(http://docs.meteor.com/#/full/meteor_users暗示我不是)没有内置的用户角色。该任务应该有一些扩展,根据您的选择,您必须检查他们的文档。

然而,在Meteor:中实现自己的简单角色逻辑并不困难

首先,在Accounts.onCreateUser函数中,为用户对象提供一个新属性role,并将其分配给默认角色。如果您还没有Accounts.onCreateUser,请创建一个服务器端。它可能看起来像这样:

Accounts.onCreateUser(function(options, user) {
    // Add an user roles array
    user.roles = ["default-user"];
    if (options.profile)
    user.profile = options.profile;
    return user;
}

接下来,您需要实现一些逻辑,将"admin"或任何您喜欢的可信用户添加到他们的角色数组中。这取决于您,首先,如果您没有几十个管理员,您也可以选择在MongoDB中手动执行。

现在,请确保将用户对象的新属性发布给当前登录的用户。为此,使用Meteor.publishnull作为第一个参数来寻址当前用户,如下所示:

Meteor.publish(null, function () {
    return Meteor.users.find({_id: this.userId}, {fields: {
        'roles': 1,
        'profile': 1, // You probably want to publish the profile of a user to himself
        // And here would be any other custom stuff you need
    }});
});

这样一来,您就已经处于可以在客户端进行个性化造型或路由的状态。例如,你可以这样做:

if (Meteor.user().roles.indexOf("admin") > -1) {
    // Route for admins!
}

您还可以解析整个数组,并将用户角色作为类添加到body元素中,例如,只向管理员显示某些元素。可以这样做:

Meteor.user().roles.forEach(function(role){
    $('body').addClass(role);
});

请注意,这只是"表面上的",但您也可以用它实现真正的安全性,只要您在服务器端这样做。因此,如果你想让Meteoer订阅或Meteor方法只对管理员可用,请添加以下内容:

var requestingUser = Meteor.users.findOne({ '_id': this.userId});
if (!_.contains(requestingUser.roles, "admin")) {
    // Terminate the pbulish function or Meteor method here when there is no "admin" role
    return;
}

如上所述,这只在服务器端工作,并且应该在Meteor.publish功能的开始处或在Meteor.methods块内的功能的开始。