【问题标题】:Set admin account using Meteor to view all tasks使用 Meteor 设置管理员帐户以查看所有任务
【发布时间】:2017-11-28 05:14:08
【问题描述】:

我是 Meteor 的新手,刚刚浏览了此处提供的待办事项列表教程 (https://www.meteor.com/tutorials/blaze/creating-an-app)。我删除了自动发布并将显示功能设置为所有任务都是私有的(即用户只能看到自己的任务。)

现在,我想更改它并将一个帐户设置为管理员帐户。管理员可以查看每个人的任务,但其他人无法查看任何内容(甚至他们自己的任务)。我正在尝试使用我已经下载到 app 文件夹中的 alanning-roles 包来执行此操作。

在我的 tasks.js 文件中,我插入了以下行:

const mod = 'E9Y4qtFXK2qQGAGq3'; // this is the userId of the account that I wish to make admin
Roles.addUsersToRoles(mod, 'moderator');

然后,我不只是显示所有任务,而是将命令以在 if 语句中显示所有任务:

if (Meteor.isServer) {
  if (Roles.userIsInRole(this.userId,'moderator')) {
     Meteor.publish('tasks', function tasksPublication() {
     return Tasks.find();
    });
  }
}

如果您以主持人/管理员身份登录,这应该会显示所有任务,否则不会显示任何内容。但是,当我运行此代码时,即使我以管理员身份登录,也不会显示任何任务。我确定我设置的 userId 是正确的,并且集合中有任务。有没有人知道问题可能是什么?

(或者,关于如何执行此操作的任何其他建议?不必使用alanning-roles - 我只是认为这会最简单)

非常感谢 -C

编辑:如果我在该行中将“this.userId”替换为“mod”:

if (Roles.userIsInRole(this.userId,'moderator')){...}

然后所有任务都会出现。所以看来问题出在this.userId的输出上。

【问题讨论】:

    标签: javascript html meteor meteor-accounts alanning-roles


    【解决方案1】:

    您需要将检查当前用户是否为“版主”的位置移动到发布功能内部:

    当前在您的代码中,当您访问 this.userId 时,服务器正在启动,this.userId 将是 undefined。所以你的if语句中的代码没有被执行,所以publish函数没有被创建,没有客户端可以订阅这个数据。

    试试这个:

    if (Meteor.isServer) {
        Meteor.publish('tasks', function tasksPublication() {
            if (Roles.userIsInRole(this.userId, 'moderator')) {
                return Tasks.find({});
            } 
      });
    }
    

    现在,在启动时Meteor.isServer 块运行,创建tasks 发布,代码检查其中的角色。现在,每次客户端订阅时都会调用此函数,在此上下文中,this.userId 将是当前客户端的用户 ID。

    另外,不要将 alanning-roles 包的源代码放在应用的文件夹中 - 通过运行 meteor add alanning:roles 或通过带有 npm install @alanning/roles --save 的 npm 包含该包

    【讨论】:

      【解决方案2】:

      你应该使用 Meteor.userId() 而不是 this.userId:

      if (Meteor.isServer) {
        if (Roles.userIsInRole(Meteor.userId(),'moderator')) {
         Meteor.publish('tasks', function tasksPublication() {
           return Tasks.find();
          });
        }
      }
      

      根据经验,始终使用 Meteor.userId(),除非在出版物内部,您应该使用 this.userId

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-09
        • 2012-04-30
        • 2016-11-25
        • 1970-01-01
        • 1970-01-01
        • 2021-01-17
        相关资源
        最近更新 更多