Meteor(0.9.0.1):使用角色包分配管理员角色的问题

Meteor (0.9.0.1): Issue assigning admin role using a roles package

本文关键字:角色 分配 问题 包分配 管理员 Meteor      更新时间:2023-09-26

我正在使用这个角色流星包,无法访问我的管理面板。

我目前的行为是登录管理用户被重定向到主页,而不是显示在管理区域。

如果我运行以下代码,我会返回"false",表明该用户不是管理员用户:

Roles.userIsInRole(Meteor.user(), ['admin']);

如果我尝试在控制台上添加角色,我会得到以下信息:

Roles.addUsersToRoles("Nvu2wZRg3K2wd4j4u", ['admin']);

未定义

insert failed: MongoError: E11000 duplicate key error index: meteor.roles.$name_1  dup key: { : "admin" }

update failed: Access denied
Roles.addUsersToRoles("Meteor.user()", ['admin']);
undefined
insert failed: MongoError: E11000 duplicate key error index: meteor.roles.$name_1  dup key: { : "admin" }

这似乎表明该用户已经分配了角色。我认为权限错误是由于未发布角色造成的。如果有一个重复的错误,那么这个用户似乎应该被分配管理员角色

这是相关代码。模板:

<template name="adminTemplate">
{{#if isAdminUser}}
    {{> accountsAdmin}}
{{else}}
    Must be admin to see this...
{{/if}}
</template>
<template name="accountsAdmin">
 accountsAdmin template
</template>

助手:

Template.adminTemplate.helpers({
  // check if user is an admin
  isAdminUser: function() {
      return Roles.userIsInRole(Meteor.user(), ['admin']);
  }
})

我的router.js文件

Router.configure({
 layoutTemplate: 'layout'
});

Router.map( function () {
 this.route('home', {path: '/'});
 this.route('about', {path: '/about'});
 this.route('faq', {path: '/faq'});
 this.route('myaccount', {path: '/myaccount'});
 this.route('admin', {
    layoutTemplate: 'adminlayout',
    path:'/admin',
    template: 'accountsAdmin',
    onBeforeAction: function() {
        if (Meteor.loggingIn()) {
            this.render(this.loadingTemplate);
        } else if(!Roles.userIsInRole(Meteor.user(), ['admin'])) {
            console.log('redirecting');
            this.redirect('/');
        }
    }
  });
});

我的startup.js 中有以下内容

  Meteor.startup(function () {
    // This is temporary
    if (Meteor.users.findOne("Nvu2wZRg3K2wd4j4u"))
        Roles.addUsersToRoles("Nvu2wZRg3K2wd4j4u", ['admin']);
  });

有人对此有什么想法吗?

在客户端设置用户角色是不可能的,你应该在服务器端做这件事,在代码中硬编码UUID从来都不是一个好主意(即使是临时的)。

出于测试目的,您可以使用以下代码:

server/collections/users.js:

insertUsers=function(){
  var adminId=Accounts.createUser({
    username:"admin",
    password:"password"
  });
  //
  Roles.addUsersToRoles(adminId,"admin");
};

server/startup.js:

// always start from scratch (you will want to comment this line at some point !)
Meteor.users.remove({});
if(Meteor.users.find().count()===0){
  insertUsers();
}

你可以去掉你的isAdminUser助手,Roles提供了一个专门为此目的设计的助手,它被称为{{isInRole "list of comma separated roles"}}

{{#if isInRole "admin"}}
  ...
{{else}}

当然,您必须登录,因为助手正在针对Meteor.user()进行测试。

我想你的管理员用户从来没有机会受到管理员角色的影响。。。

您的代码的其余部分看起来还可以,所以希望在解决这些细节后它应该可以工作。