[Solved] Roles javascript not working

I’m using the alanning:roles package and login is working fine. However, I’m getting an unexpected behaviour, and I’m at a loss to fix it. Any ideas are welcome.

When I use

{{if isInRole 'admin' 'default_group'}}
  Yeah, I'm an admin
{{else}}
  Just a non-user
{{/if}}
Output: Yeah, I'm an admin

When I use

console.log( Roles.userIsInRole(Meteor.userId, ['admin'], 'default_group') )
Output: false

My users are setup like this in /server/bootstrap.js

Meteor.startup(function () {
 var default_users = [
     {name: "Sid Administrator", email: "admin@some.com", password: "1234", roles: ['admin']},
     {name: "Jonny FieldUser", email: "field@some.com", password: "1234", roles: ['field']},
     {name: "Suzie Manager", email: "manager@some.com", password: "1234", roles: ['manager']}
 ];
 if (Meteor.users.find().count() === 0) {
   _.each(default_users, function(user) {
     var id;
     id = Accounts.createUser({
       email: user.email,
       password: user.password,
       profile: {
          fullname: user.name
       }
     });
     if(user.roles.length > 0) {
      Roles.addUsersToRoles(id, user.roles, 'default_group');
     }
   });
 }
});

Don’t know if that solves your particular problem, but you need to add the Roles.addUsersToRoles(id, user.roles, 'default_group'); call inside the loop where user actually exists?

You have it outside the _.each block, which means it gets called only once with neither id nor user defined.

Sorry, that’s my typo. I’ve updated the initial post.

Meteor.userId is a function. Change your code to console.log( Roles.userIsInRole(Meteor.userId(), ['admin'], 'default_group') )

I thought that too, but when I use Meteor.userID(), I get the error

Exception from sub site_pages id 8z4... Error: meteor.userID can only be invoked in method calls. Use this.userId in publish functions

I just tried this.userId (as stated in the error) and it seems to have worked. Yeah.

That is correct, Meteor.userId() can only be invoked on the client. On server side you use this.userId in a method. So depending on where you have your console.log statement, you need to adjust it.

1 Like