alanning:roles

v1.3.0Published 3 years ago

meteor-roles v1

This version of the package is being maintained just for security and compatibility issues. Please consider the latest version.

Authorization package for Meteor - compatible with built-in accounts package.

Table of Contents

Contributors

Thanks to:

Authorization

This package lets you attach permissions to a user which you can then check against later when deciding whether to grant access to Meteor methods or publish data. The core concept is very simple, essentially you are attaching strings to a user object and then checking for the existence of those strings later. In some sense, it is very similar to tags on blog posts. This package provides helper methods to make the process of adding, removing, and verifying those permissions easier.

All versions of Meteor from 0.5 to current are supported (excluding Meteor 0.9.1). UI-less apps are supported as well.

v1.1.0 - adds support for per-group assignment of permissions

v1.2.0 - adds the special Roles.GLOBAL_GROUP, used to provide blanket permissions across all groups

Permissions vs roles (or What's in a name...)

Although the name of this package is 'roles', you can define your permissions however you like. They are essentially just tags that you assign on a user and which you can check for later.

You can have traditional roles like, "admin" or "webmaster", or you can assign more granular permissions such as, "view-secrets", "users.view", or "users.manage". Often times more granular is actually better because you are able to handle all those pesky edge cases that come up in real-life usage without creating a ton of higher-level 'roles'. To the roles package, it's all strings.

What are "groups"?

Sometimes it's useful to let a user have independent sets of permissions. The roles package calls these independent sets, "groups" for lack of a better term. You can think of them as "partitions" if that is more clear. Users can have one set of permissions in group A and another set of permissions in group B. Let's go through an example of this using soccer/football teams as groups.

1import { Roles } from 'meteor/alanning:roles'
2
3Roles.addUsersToRoles(joesUserId, ['manage-team','schedule-game'], 'manchester-united.com')
4Roles.addUsersToRoles(joesUserId, ['player','goalie'], 'real-madrid.com')
5
6Roles.userIsInRole(joesUserId, 'manage-team', 'manchester-united.com')  // => true
7Roles.userIsInRole(joesUserId, 'manage-team', 'real-madrid.com')  // => false

In this example we can see that Joe manages Manchester United and plays for Real Madrid. By using groups, we can assign permissions independently and make sure that they don't get mixed up between groups.

NOTE: If you use groups for ANY of your users, you should use groups for ALL of your users. This is due to how the roles package stores the roles internally in the database. In roles 2.0, you won't need to worry about this anymore, we'll have a default group that will hold roles not assigned to a specific group.

Now, let's take a look at how to use the Global Group. Say we want to give Joe permission to do something across all of our groups. That's what the Global Group is for:

1import { Roles } from 'meteor/alanning:roles'
2
3Roles.addUsersToRoles(joesUserId, 'super-admin', Roles.GLOBAL_GROUP)
4
5if (Roles.userIsInRole(joesUserId, ['manage-team', 'super-admin'], 'real-madrid.com')) {
6
7  // True!  Even though Joe doesn't manage Real Madrid, he is 'super-admin' in
8  // the Global Group so this check succeeds.
9
10}

Changes to default Meteor behavior

  1. User entries in the Meteor.users collection gain a new field named roles corresponding to the user's roles. †
  2. A new collection Meteor.roles contains a global list of defined role names. ††
  3. The currently logged-in user's roles field is automatically published to the client.

† The type of the roles field depends on whether or not groups are used:

1import { Roles } from 'meteor/alanning:roles'
2
3Roles.addUsersToRoles(bobsUserId, ['manage-team','schedule-game'])
4// internal representation - no groups
5// user.roles = ['manage-team','schedule-game']
6
7Roles.addUsersToRoles(joesUserId, ['manage-team','schedule-game'], 'manchester-united.com')
8Roles.addUsersToRoles(joesUserId, ['player','goalie'], 'real-madrid.com')
9// internal representation - groups
10// NOTE: MongoDB uses periods to represent hierarchy so periods in group names
11//   are converted to underscores.
12//
13// user.roles = {
14//   'manchester-united_com': ['manage-team','schedule-game'],
15//   'real-madrid_com': ['player','goalie']
16// }

Note: See the addUsersToRoles documentation for restrictions on group names.

†† The Meteor.roles collection is currently only for convenience on the UI-side and is not used functionally within this package. In the future it may be used to support role hierarchies. Since it is not currently required, it is not automatically published to the client. Here's how you would publish it to every client without needing a subscription:

1// in server/publish.js
2Meteor.publish(null, function (){
3  return Meteor.roles.find({})
4})

Installing

Meteor 0.9 - latest

  1. Add one of the built-in accounts packages so the Meteor.users collection exists. From a command prompt:

    meteor add accounts-password
  2. Add this package to your project. From a command prompt:

    meteor add alanning:roles
  3. Run your application:

    meteor

Meteor 0.8.3 and below (meteorite)

  1. Add one of the built-in accounts packages so the Meteor.users collection exists. From a command prompt:

    meteor add accounts-password
  2. Install Meteorite

  3. Add this smart package to your project. From a command prompt:

    mrt add roles
  4. Run your application:

    meteor

NOTE for Meteor 0.8-0.8.3: Manually add the 'ui' package to your '.meteor/packages' file so that roles knows you are using it. Otherwise, the 'isInRole' client-side helper will not be registered. Since some versions of Meteor had 'standard-app-packages' without 'ui' there is no other way to detect its use.

Usage Examples

Here are some potential use cases:

-- Server --

Add users to roles:

1import { Roles } from 'meteor/alanning:roles'
2
3var users = [
4      {name:"Normal User",email:"normal@example.com",roles:[]},
5      {name:"View-Secrets User",email:"view@example.com",roles:['view-secrets']},
6      {name:"Manage-Users User",email:"manage@example.com",roles:['manage-users']},
7      {name:"Admin User",email:"admin@example.com",roles:['admin']}
8    ];
9
10_.each(users, function (user) {
11  var id;
12
13  id = Accounts.createUser({
14    email: user.email,
15    password: "apple1",
16    profile: { name: user.name }
17  });
18
19  if (user.roles.length > 0) {
20    // Need _id of existing user record so this call must come
21    // after `Accounts.createUser` or `Accounts.onCreate`
22    Roles.addUsersToRoles(id, user.roles, 'default-group');
23  }
24
25});

Check user roles before publishing sensitive data:

1// server/publish.js
2import { Roles } from 'meteor/alanning:roles'
3
4
5// Give authorized users access to sensitive data by group
6Meteor.publish('secrets', function (group) {
7  if (Roles.userIsInRole(this.userId, ['view-secrets','admin'], group)) {
8
9    return Meteor.secrets.find({group: group});
10
11  } else {
12
13    // user not authorized. do not publish secrets
14    this.stop();
15    return;
16
17  }
18});

Prevent non-authorized users from creating new users:

1import { Roles } from 'meteor/alanning:roles'
2
3Accounts.validateNewUser(function (user) {
4  var loggedInUser = Meteor.user();
5
6  if (Roles.userIsInRole(loggedInUser, ['admin','manage-users'])) {
7    // NOTE: This example assumes the user is not using groups.
8    return true;
9  }
10
11  throw new Meteor.Error(403, "Not authorized to create new users");
12});

Prevent access to certain functionality, such as deleting a user:

1// server/userMethods.js
2import { Roles } from 'meteor/alanning:roles'
3
4Meteor.methods({
5  /**
6   * delete a user from a specific group
7   *
8   * @method deleteUser
9   * @param {String} targetUserId _id of user to delete
10   * @param {String} group Company to update permissions for
11   */
12  deleteUser: function (targetUserId, group) {
13    var loggedInUser = Meteor.user()
14
15    if (!loggedInUser ||
16        !Roles.userIsInRole(loggedInUser,
17                            ['manage-users', 'support-staff'], group)) {
18      throw new Meteor.Error(403, "Access denied")
19    }
20
21    // remove permissions for target group
22    Roles.setUserRoles(targetUserId, [], group)
23
24    // do other actions required when a user is removed...
25  }
26})

Manage a user's permissions:

1// server/userMethods.js
2import { Roles } from 'meteor/alanning:roles'
3
4Meteor.methods({
5  /**
6   * update a user's permissions
7   *
8   * @param {Object} targetUserId Id of user to update
9   * @param {Array} roles User's new permissions
10   * @param {String} group Company to update permissions for
11   */
12  updateRoles: function (targetUserId, roles, group) {
13    var loggedInUser = Meteor.user()
14
15    if (!loggedInUser ||
16        !Roles.userIsInRole(loggedInUser,
17                            ['manage-users', 'support-staff'], group)) {
18      throw new Meteor.Error(403, "Access denied")
19    }
20
21    Roles.setUserRoles(targetUserId, roles, group)
22  }
23})

Perform complex permission checks in a declaritive way:

(requires mdg:validated-method and didericis:permissions-mixin).

1// server/userMethods.js
2
3/**
4 * A user of role 'partner_admin' and group Roles.GLOBAL_GROUP can only create valid partner topics
5 * A user of role 'admin' and group Roles.GLOBAL_GROUP can create any arbitrary topic
6 *
7 * @param {Object} input Input parameters
8 * @param {String} input.title Topic title
9 */
10const createTopic = new ValidatedMethod({
11    name: 'CreateTopic',
12    mixins: [PermissionsMixin],
13    allow: [{
14        roles: ['partner_admin'],
15        group: Roles.GLOBAL_GROUP,
16        allow({ title }) { 
17          return VALID_PARTNER_TOPIC_TITLES.includes(title)
18        }
19    }, {
20        roles: ['admin'],
21        group: Roles.GLOBAL_GROUP
22    }],
23    validate: new SimpleSchema({
24        title: { type: String }
25    }).validator(),
26    run({ title }) {
27        return topics.insert({ title });
28    }
29});
30

-- Client --

Client javascript has access to all the same Roles functions as the server with the addition of a isInRole handlebars helper which is automatically registered by the Roles package.

As with all Meteor applications, client-side checks are a convenience, rather than a true security implementation since Meteor bundles the same client-side code to all users. Providing the Roles functions client-side also allows for latency compensation during Meteor method calls.

NOTE: Any sensitive data needs to be controlled server-side to prevent unwanted disclosure. To be clear, Meteor sends all templates, client-side javascript, and published data to the client's browser. This is by design and is a good thing. The following example is just sugar to help improve the user experience for normal users. Those interested in seeing the 'admin_nav' template in the example below will still be able to do so by manually reading the bundled client.js file. It won't be pretty but it is possible. But this is not a problem as long as the actual data is restricted server-side.

To check for permissions when not using groups:

<!-- client/myApp.html -->

<template name="header">
  ... regular header stuff
  {{#if isInRole 'admin'}}
    {{> admin_nav}}  
  {{/if}}
  {{#if isInRole 'admin,editor'}}
    {{> editor_stuff}}
  {{/if}}
</template>

To check for permissions when using groups:

<!-- client/myApp.html -->

<template name="header">
  ... regular header stuff
  {{#if isInRole 'admin,editor' 'group1'}}
    {{> editor_stuff}}  
  {{/if}}
</template>

API Docs

Online API docs found here: http://alanning.github.io/meteor-roles/classes/Roles.html

API docs generated using YUIDoc

To re-generate documentation:

  1. install YUIDoc
  2. cd meteor-roles
  3. yuidoc

To serve documentation locally:

  1. install YUIDoc
  2. cd meteor-roles
  3. yuidoc --server
  4. point browser at http://localhost:3000/

Example Apps

The examples directory contains Meteor apps which show off the following features:

  • Server-side publishing with authorization to secure sensitive data
  • Client-side navigation with link visibility based on user permissions
  • 'Sign-in required' app with up-front login page using accounts-ui
  • Client-side routing

The only difference among the example apps is which routing package is used.

View the meteor-router example app online @ http://roles.meteor.com/

Iron Router or Flow Router

  1. git clone https://github.com/Meteor-Community-Packages/meteor-roles.git
  2. either
* `cd meteor-roles/examples/iron-router` or
* `cd meteor-roles/examples/flow-router`
  1. meteor
  2. point browser to http://localhost:3000

Deprecated routing packages: Mini-Pages or Router

  1. install Meteorite
  2. git clone https://github.com/Meteor-Community-Packages/meteor-roles.git
  3. either
* `cd meteor-roles/examples/router` or
* `cd meteor-roles/examples/mini-pages`
  1. mrt update
  2. meteor
  3. point browser to http://localhost:3000

Tests

To run tests:

  1. cd meteor-roles
  2. meteor test-packages ./roles
  3. point browser at http://localhost:3000/

NOTE: If you see an error message regarding "The package named roles does not exist" that means you are either: a) in the wrong directory or b) left off the './' in front of 'roles' in step 2.

Step 2 needs to be run in the main 'meteor-roles' directory and the './' is needed because otherwise Meteor only looks in directories named 'packages'.