mongoose-rbac
Role-based access control for mongoose apps.
Requirements
- mongoose 3.8.x
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:
- Create a
Permission
for each action you desire to control. APermission
consists of asubject
and anaction
. - Create a
Role
for each role you wish to assign. ARole
only requires a uniquename
. - Assign the desired set of permissions to each role.
- 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 = Permission = rbacPermission Role = rbacRole 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;
Alternatively we can use init
to easily bootstrap roles and permissions:
// permissions.js var rbac = ; rbac;
Next, we will enhance our user model with the mongoose-rbac plugin:
// user.js var mongoose = rbac = UserSchema User; UserSchema = mongoose; UserSchema; moduleexports = mongoose;
Finally, we can assign roles to our users and control their access to system resources:
var User = user; user = username: 'hercules' ;user; user; user; user; user; user;
Model Plugin API
hasRole(role, callback)
Check if the model has the given role.
role
String or Rolecallback(err, bool)
Function
addRole(role, callback)
Add the given role to the model.
role
String or Rolecallback(err)
Function
removeRole(role, callback)
Remove the given role from the model.
role
String or Rolecallback(err)
Function
can(action, subject, callback)
Check if the model has the given permisison.
action
Stringsubject
Stringcallback(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.gitcd mongoose-rbac && npm installmake test
License
MIT