Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a user has a specific role in Meteor

I want to manage the users of my Meteor app and in order to do that I'll need to know their current roles. I have a page setup that is only accessible to admin users and that page is subscribed to the users collection.

In my template for this page I have the following:

{{#each user}}
  <p>
    <a href="/@{{username}}">{{username}}</a>
    {{#if isInRole 'admin'}} Admin{{/if}}
  </p>  
{{/each}}

Unfortunately this leaves me with a problem where the logged in user's (which is an admin) role is what is compared in the {{#if isInRole 'admin'}} block. This results in all the users having admin status (which is not the case).

How do I check if a user that is displayed from the each block is in a specific role?

Edit Note: I am using the alanning/meteor-roles package

There is a list of all the users in the database, and I want to see their admin status.

like image 295
Barry Michael Doyle Avatar asked Jan 25 '16 18:01

Barry Michael Doyle


2 Answers

I have the following solution for anyone who runs into this issue in future.

JavaScript:

Template.registerHelper('isUserInRole', function(userId, role) {
  return Roles.userIsInRole(userId, role);
});

Template:

<p>
  Roles: {{#if isUserInRole _id 'webmaster'}}Webmaster {{/if}}
  {{#if isUserInRole _id 'admin'}}Admin {{/if}}
</p>
like image 76
Barry Michael Doyle Avatar answered Oct 10 '22 18:10

Barry Michael Doyle


You can create your own role checking functions like so:

isAdmin = function(){
  var loggedInUser = Meteor.user();
  var result = false;
  if(loggedInUser){
    if (Roles.userIsInRole(loggedInUser, ['Admin'])){
      result = true;
    }
  }
  return result;
};

So save this in ./lib/roles.js for example.

You will need to install the alanning:roles package to use this.

like image 27
Matt D. Webb Avatar answered Oct 10 '22 19:10

Matt D. Webb