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

时间:2014-09-01 21:00:56

标签: javascript meteor

我正在使用此roles meteor package而我无法访问我的管理员面板。

我现在所记录的行为是管理员用户被重定向到主页而不是显示管理区域。

如果我运行以下代码,则返回“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']);
  });

有人对此有任何想法吗?

1 个答案:

答案 0 :(得分:2)

在客户端中设置用户角色是不可能的,你应该做这个东西服务器端,并且在代码中硬编码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助手,角色提供专门为此目的设计的助手,它被称为{{isInRole "list of comma separated roles"}}

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

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

我猜您的管理员用户从未有机会受到管理员角色的影响...

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