Meteor-Community-Packages / meteor-roles

Authorization package for Meteor, compatible with built-in accounts packages
http://meteor-community-packages.github.io/meteor-roles/
MIT License
921 stars 166 forks source link

Check if userIsInRole, no matter the group #262

Closed bolognese closed 6 years ago

bolognese commented 6 years ago

Something like Roles.userIsInRole(Meteor.userId(), 'my-role', Roles.ANY_GROUP) would be a great feature.

For example, say you're building a forum. You have moderators that only have access to some parts of the forum. And you want to know if the current user is a moderator or not, no matter what his group is just to give him access to special features

bolognese commented 6 years ago

A simple (but really not optimized) way to do this would be something like :

_.extend(Roles, userHasRoleOrIDontKnowWhat = (user, role) => {
    const roles = Meteor.users.findOne(user, {
        fields: { roles: 1 }
    }).roles
    return _.contains(_.flatten(_.values(roles)), role)
})
alanning commented 6 years ago

You may want to check out the v2 branch as it has a better db structure for these kinds of queries.

If you are just testing a user object that you already have in memory, you can do something like this:

for (var groupId in roles) {
  if (roles[groupId].includes('manage-users')) {
    console.log(groupId); 
    break;
  } 
}

(POC from mongodb shell. For your needs you'd wrap the loop in a function that just returns true if found.)