Giter Site home page Giter Site logo

mongoose-rbac's Introduction

mongoose-rbac

Role-based access control for mongoose apps.

Build Status

Requirements

Installation

npm install mongoose-rbac --save

Usage

mongoose-rbac gives you the building blocks to lock down your app with role-based access control and gets out of your way.

Generally, you will want to do the following:

  1. Create a Permission for each action you desire to control. A Permission consists of a subject and an action.
  2. Create a Role for each role you wish to assign. A Role only requires a unique name.
  3. Assign the desired set of permissions to each role.
  4. Use the mongoose-rbac plugin in your user schema.

Example

Following is a typical example. Let's imagine we are managing a blog with users, preferences, posts and comments. First, we will define our permissions and roles:

// permissions.js

var rbac = require('mongoose-rbac')
  , Permission = rbac.Permission
  , Role = rbac.Role
  , permissions;

permissions = [
    { subject: 'Post', action: 'create' }
  , { subject: 'Post', action: 'read' }
  , { subject: 'Post', action: 'update' }
  , { subject: 'Post', action: 'delete' }
  , { subject: 'Comment', action: 'create' }
  , { subject: 'Comment', action: 'read' }
  , { subject: 'Comment', action: 'update' }
  , { subject: 'Comment', action: 'delete' }
  , { subject: 'Preference', action: 'create' }
  , { subject: 'Preference', action: 'read' }
  , { subject: 'Preference', action: 'update' }
  , { subject: 'Preference', action: 'delete' }
];

Permission.create(permissions, function (err) {
  var perms, admin, developer, readonly;

  perms = Array.prototype.slice.call(arguments, 1);

  admin = new Role({ name: 'admin' });
  admin.permissions = perms;
  admin.save(function (err, admin) {
    developer = new Role({ name: 'developer' });
    developer.permissions = perms.slice(0, 7);
    developer.save(function (err, developer) {
      readonly = new Role({ name: 'readonly' });
      readonly.permissions = [perms[1], perms[5], perms[9]];
      readonly.save(function (err, readonly) {
        // ...
      });
    });
  });
});

Alternatively we can use init to easily bootstrap roles and permissions:

// permissions.js

var rbac = require('mongoose-rbac');

rbac.init({
  admin: [
    ['create', 'Post'],
    ['read', 'Post'],
    ['update', 'Post'],
    ['delete', 'Post']
  ],
  readonly: [
    // we can also specify permissions as an object
    { action: 'read', subject: 'Post' }
  ]
}, function (err, admin, readonly) {
  console.log(admin);
  /*
    { __v: 1,
      name: 'admin',
      _id: 513c14dbc90000d10100004e,
      permissions: [ 513c14dbc90000d101000044,
        513c14dbc90000d101000045,
        513c14dbc90000d101000046,
        513c14dbc90000d101000047 ] }
  */
  console.log(readonly);
  /*
    { __v: 1,
      name: 'readonly',
      _id: 513c14dbc90000d10100004f,
      permissions: [ 513c14dbc90000d101000045 ] }
  */
});

Next, we will enhance our user model with the mongoose-rbac plugin:

// user.js

var mongoose = require('mongoose')
  , rbac = require('mongoose-rbac')
  , UserSchema
  , User;

UserSchema = mongoose.Schema({
  username: String,
  passwordHash: String
});

UserSchema.plugin(rbac.plugin);

module.exports = mongoose.model('User', UserSchema);

Finally, we can assign roles to our users and control their access to system resources:

var User = require('user')
  , user;

user = new User({ username: 'hercules' });
user.save();

user.addRole('admin', function (err) {});

user.hasRole('admin', function (err, isAdmin) {
  console.log(isAdmin); // true
});

user.can('create', 'Post', function (err, can) {
  if (can) {
    // ok
  }
  else {
    // insufficient privileges
  }
});

user.canAny([['read', 'Post'], ['create', 'Post']], function (err, canReadOrCreate) {
  if (canReadOrCreate) {
    // ok
  }
  else {
    // insufficient privileges
  }
});

user.removeRole('admin', function (err) {});

Model Plugin API

hasRole(role, callback)

Check if the model has the given role.

  • role String or Role
  • callback(err, bool) Function

addRole(role, callback)

Add the given role to the model.

  • role String or Role
  • callback(err) Function

removeRole(role, callback)

Remove the given role from the model.

  • role String or Role
  • callback(err) Function

can(action, subject, callback)

Check if the model has the given permisison.

  • action String
  • subject String
  • callback(err, bool) Function

canAny(actionsAndSubjects, callback)

Check if the model has any of the given permissions.

  • actionsAndSubjects Array (of [String, String])
  • callback(err, bool) Function

canAll(actionsAndSubjects, callback)

Check if the model has all of the given permissions.

  • actionsAndSubjects Array (of [String, String])
  • callback(err, bool) Function

Running Tests

To run the tests, clone the repository and install the dev dependencies:

git clone git://github.com/bryandragon/mongoose-rbac.git
cd mongoose-rbac && npm install
make test

License

MIT

mongoose-rbac's People

Contributors

remotevision avatar uahengojr avatar vincentbriglia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoose-rbac's Issues

assigning more than one role not possible

It's not possible to assign more than one role to user. Following snippet

        _user.addRole('admin', function (err) {
            _user.addRole('superadmin', function (err) {
                _user.save(function (err, user) {
                    if (err) {
                        throw err;
                    }
                    console.log(user);
                });
            });
        });

results in

roles:
   [ { name: 'admin',
       _id: 530e7c8fdf60103bb7a4906e,
       __v: 0,
       permissions: [Object] },
     530e7c8fdf60103bb7a4906d ],

As you can see admin permission is saved as whole object not just objectID

object user has not method addRole

var config = require('../../config/config');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var crypto = require('crypto');
var authTypes = ['github', 'twitter', 'facebook', 'google'];
var rbac = require('mongoose-rbac');

var UserSchema = new Schema({
name: String,
email: { type: String, lowercase: true },
hashedPassword: String,
provider: String,
salt: String,
facebook: {},
twitter: {},
google: {},
github: {}
});

UserSchema.plugin(rbac.plugin);

This being the schema, when trying to add role the console is shouting that the method is not a available

Multiple entries in permission collection for same action/subject.

My code is as below

var mongoose = require('mongoose')
, rbac = require('./lib/');

var db = mongoose.connect('mongodb://localhost/ecommerece_rbac');

if(db)
{
console.log("connected");

var UserSchema = mongoose.Schema({

username: {type:String},
status: {type:String, default:"A"},
createdAt : {type:Date, default:Date.now}

});

UserSchema.plugin(rbac.plugin);

var User = mongoose.model('User', UserSchema);

rbac.init({
ops: [
['create', 'CallRecord'],
['read', 'CallRecord'],
['update', 'CallRecord'],
['delete', 'CallRecord']
],
callcenteragent: [

  ['read', 'CallRecord'],
  ['create', 'CallRecord']

]

}, function (err, ops, callcenteragent) {

var user1 = new User({ username: 'prince' });
user1.save();

 user1.addRole('ops', function () {
    console.log(require('util').inspect(user1.roles[0]));
 });

}

)

}

This is creating 2 document in permission collection for read and create permission in mongo.

can not init

mongoose.model('Role').findOne() is not active.lead to can not save data.

Duplicate roles created

Hi Bryan,
First, let me say I greatly appreciate your library. It will save me a lot of time moving forward with my project.

However, one of the things I've noticed is that the role names are not unique. Therefore when I create my roles in the init() of permissions.js it will create duplicate roles. Is this by design?

hasRole return false after calling can

The problem I believe is calling 'can' somehow populate roles, but 'hasRole' still expects array.

I wrote one test to reproduce bug:

  it('should be able to hasRole after can', function (next) {
    henry.addRole('admin', function (err) {
      expect(err).to.not.exist;
      henry.can('create', 'Post', function (err, can) {
        expect(err).to.not.exist;
        expect(can).to.be.true;
        henry.hasRole('admin', function (err, isAdmin) {
          expect(err).to.not.exist;
          expect(isAdmin).to.be.true;
          next();
        });
      });
    });
  });

Not compatible with Mongoose 3.8

This is the error I'm currently getting. I'll look into it but wanted to go ahead and open an issue on it.

MissingSchemaError: Schema hasn't been registered for model "Role".
Use mongoose.model(name, schema)
    at NativeConnection.Connection.model (/Users/ryan/dev/node/bandwango-node/node_modules/mongoose/lib/connection.js:625:11)
    at populate (/Users/ryan/dev/node/bandwango-node/node_modules/mongoose/lib/model.js:2064:24)
    at Function.Model.populate (/Users/ryan/dev/node/bandwango-node/node_modules/mongoose/lib/model.js:2029:5)
    at model.populate (/Users/ryan/dev/node/bandwango-node/node_modules/mongoose/lib/document.js:1724:22)
    at model.schema.methods.can (/Users/ryan/dev/node/bandwango-node/node_modules/mongoose-rbac/lib/index.js:175:9)
    at Server.authorize (/Users/ryan/dev/node/bandwango-node/permissions.js:103:14)
    at next (/Users/ryan/dev/node/bandwango-node/node_modules/restify/lib/server.js:728:42)
    at /Users/ryan/dev/node/bandwango-node/node_modules/restify/node_modules/once/once.js:17:15
    at complete (/Users/ryan/dev/node/bandwango-node/node_modules/passport/lib/passport/middleware/authenticate.js:218:13)
    at /Users/ryan/dev/node/bandwango-node/node_modules/passport/lib/passport/middleware/authenticate.js:200:15

callback not being called when using rbac.init()

I haven't done any digging yet, but when I pulled down version 0.1.0 it doesn't appear as though the callback function is being called during rbac.init();

using your example,

rbac.init({
  admin: [
    ['create', 'Post'],
    ['read', 'Post'],
    ['update', 'Post'],
    ['delete', 'Post']
  ],
  readonly: [
    // we can also specify permissions as an object
    { action: 'read', subject: 'Post' }
  ]
}, function (err, admin, readonly) {
  console.log("permissions callback");
  if(err) console.log(err);

  console.log(admin);

  /*
    { __v: 1,
      name: 'admin',
      _id: 513c14dbc90000d10100004e,
      permissions: [ 513c14dbc90000d101000044,
        513c14dbc90000d101000045,
        513c14dbc90000d101000046,
        513c14dbc90000d101000047 ] }
  */
  console.log(readonly);
  /*
    { __v: 1,
      name: 'readonly',
      _id: 513c14dbc90000d10100004f,
      permissions: [ 513c14dbc90000d101000045 ] }
  */
});
'''

Compatibility with Mongoose 3.8.x

Yesterday I was about to update the Roles and Permissions collections with some new values and encountered a problem where:

Permissions.create(someNewPermissions, function(err) {
...create 2 new Roles with someNewPermissions
})

In my init script just hung with no error. Just hung.

I back-downgraded to mongoose 3.6.20 and all is good again.

Schema hasn't been registered for "Role"

I'm looking into this and think it may have to do with changes in Mongoose versions to 3.8, but wanted to let you know in case you aren't already aware of the issue.

MissingSchemaError: Schema hasn't been registered for model "Role".
Use mongoose.model(name, schema)
    at NativeConnection.Connection.model (/Users/ryan/dev/node/bandwango-node/node_modules/mongoose/lib/connection.js:625:11)
    at populate (/Users/ryan/dev/node/bandwango-node/node_modules/mongoose/lib/model.js:2064:24)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.