├── .npmignore ├── index.js ├── .jshintrc ├── .travis.yml ├── .gitignore ├── lib ├── index.js ├── teamPlugin.js ├── cloneWhitelisted.js ├── permissionsPlugin.js └── componentsPlugin.js ├── package.json ├── test ├── cloneWhitelisted.js ├── utils.js ├── permissionsPlugin.js ├── teamPlugin.js └── componentsPlugin.js ├── README.md └── LICENSE /.npmignore: -------------------------------------------------------------------------------- 1 | test 2 | .gitignore 3 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./lib'); 2 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "globalstrict": true, 3 | "node": true, 4 | "mocha": true 5 | } 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "node" 4 | - "iojs" 5 | sudo: false 6 | services: 7 | - mongodb 8 | before_script: 9 | - "until nc -z localhost 27017 ; do echo Waiting for MongoDB; sleep 1; done" 10 | after_success: 11 | - "npm run-script coveralls" 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # vim 2 | .*.swp 3 | 4 | # Logs 5 | logs 6 | *.log 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | 13 | # Directory for instrumented libs generated by jscoverage/JSCover 14 | lib-cov 15 | 16 | # Coverage directory used by tools like istanbul 17 | coverage 18 | 19 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 20 | .grunt 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # Commenting this out is preferred by some people, see 27 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 28 | node_modules 29 | 30 | # Users Environment Variables 31 | .lock-wscript 32 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var _ = require('lodash'); 3 | 4 | module.exports = function (config) { 5 | config = _.defaults(_.clone(config || {}), { 6 | authorizedComponents: 'authorizedComponents', 7 | authorizedToObject: 'authorizedToObject', 8 | authorizedSet: 'authorizedSet', 9 | authorizedArrayPush: 'authorizedArrayPush', 10 | authorizedArrayRemove: 'authorizedArrayRemove', 11 | authorizedArraySet: 'authorizedArraySet', 12 | permissions: 'permissions', 13 | permissionsGet: 'getPermissions', 14 | permissionsHas: 'hasPermissions', 15 | permissionsAssert: 'assertPermission', 16 | permissionsGetComponents: 'getComponents', 17 | teamMembers: 'members', 18 | teamGetUserIds: 'getUserIds', 19 | teamUserModel: 'User', 20 | teamModel: 'Team' 21 | }); 22 | return { 23 | cloneWhitelisted: require('./cloneWhitelisted'), 24 | permissionsPlugin: require('./permissionsPlugin')(config), 25 | componentsPlugin: require('./componentsPlugin')(config), 26 | teamPlugin: require('./teamPlugin')(config) 27 | }; 28 | }; 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mongoose-authorize", 3 | "version": "1.0.0-beta.19", 4 | "description": "Authorization (NOT authentication) plugin for mongoose", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "mocha", 8 | "coveralls": "mocha --require blanket -R mocha-lcov-reporter | coveralls" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/paperhive/mongoose-authorize.git" 13 | }, 14 | "keywords": [ 15 | "mongoose", 16 | "security", 17 | "authorize", 18 | "authorization", 19 | "permission", 20 | "role", 21 | "rbac" 22 | ], 23 | "author": "André Gaul ", 24 | "license": "GPL-3.0", 25 | "bugs": { 26 | "url": "https://github.com/paperhive/mongoose-authorize/issues" 27 | }, 28 | "homepage": "https://github.com/paperhive/mongoose-authorize", 29 | "devDependencies": { 30 | "blanket": "^1.1.9", 31 | "coveralls": "^2.11.4", 32 | "mocha": "^2.2.5", 33 | "mocha-lcov-reporter": "^1.0.0", 34 | "mongoose-erase": "^2.0.7", 35 | "should": "^8.0.0" 36 | }, 37 | "dependencies": { 38 | "async": "^1.4.2", 39 | "lodash": "^3.10.1", 40 | "mongoose": "^4.1.2" 41 | }, 42 | "config": { 43 | "blanket": { 44 | "data-cover-only": "lib", 45 | "data-cover-never": "node_modules" 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /lib/teamPlugin.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var mongoose = require('mongoose'); 3 | var async = require('async'); 4 | var _ = require('lodash'); 5 | 6 | module.exports = function (config) { 7 | // note: options is currently unused 8 | return function (schema, options) { 9 | // add users + teams arrays to schema 10 | var teamSchema = {}; 11 | teamSchema[config.teamMembers] = { 12 | users: [{type: mongoose.Schema.Types.ObjectId, ref: config.teamUserModel}], 13 | teams: [{type: mongoose.Schema.Types.ObjectId, ref: config.teamModel}] 14 | }; 15 | schema.add(teamSchema); 16 | 17 | // add getUserIds function 18 | schema.methods[config.teamGetUserIds] = function (done, visitedTeams) { 19 | // has this team already been processed? 20 | var id = this._id.toString(); 21 | if (visitedTeams && _.contains(visitedTeams, id)) { 22 | return done(null, []); 23 | } 24 | if (!visitedTeams) visitedTeams = []; 25 | visitedTeams.push(id); 26 | 27 | var doc = this; 28 | 29 | // "un-populate" users if necessary in order to get ids 30 | var user_ids = _.map(doc[config.teamMembers].users, function (value) { 31 | return value._id ? value._id : value; 32 | }); 33 | doc.populate(config.teamMembers + '.teams', function (err, doc) { 34 | if (err) return done(err); 35 | async.parallel( 36 | _.map(doc[config.teamMembers].teams, function (team) { 37 | return function (cb) { 38 | team[config.teamGetUserIds](cb, visitedTeams); 39 | }; 40 | }), 41 | function (err, userIdsArray) { 42 | if (err) return done(err); 43 | done(null, user_ids.concat.apply(user_ids, userIdsArray)); 44 | } 45 | ); 46 | }); 47 | }; 48 | }; 49 | }; 50 | -------------------------------------------------------------------------------- /lib/cloneWhitelisted.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var _ = require('lodash'); 3 | 4 | /* 5 | obj may be any of 6 | * null 7 | * boolean 8 | * number 9 | * string 10 | * array 11 | * object 12 | where array and values in an object are again of the above types. 13 | */ 14 | module.exports = function cloneWhitelisted (obj, whitelist) { 15 | if (obj === undefined || !whitelist) return undefined; 16 | 17 | // simply return whitelisted null, boolean, number and string objs 18 | if (whitelist === true) { 19 | if (!_.isNull(obj) && !_.isBoolean(obj) && 20 | !_.isNumber(obj) && !_.isString(obj)) { 21 | throw new Error('obj is not null, boolean, number or string'); 22 | } 23 | return obj; 24 | } 25 | 26 | var clone; 27 | // process array 28 | if (_.isArray(whitelist)) { 29 | if (whitelist.length != 1) { 30 | throw new Error('whitelist arrays have to be of length 1'); 31 | } 32 | if (!_.isArray(obj)) { 33 | throw new Error('whitelist is an array while obj is not'); 34 | } 35 | clone = []; 36 | _.each(obj, function (value) { 37 | var valueClone = cloneWhitelisted(value, whitelist[0]); 38 | // omit element if undefined 39 | if (valueClone !== undefined) { 40 | clone.push(valueClone); 41 | } 42 | }); 43 | return clone; 44 | } 45 | 46 | // process object 47 | if (_.isObject(whitelist) && !_.isFunction(whitelist)) { 48 | if (!_.isObject(obj)) { 49 | throw new Error('whitelist is object while obj is not'); 50 | } 51 | clone = {}; 52 | _.each(obj, function (value, key) { 53 | var valueClone = cloneWhitelisted(value, whitelist[key]); 54 | // omit element if undefined 55 | if (valueClone !== undefined) { 56 | clone[key] = valueClone; 57 | } 58 | }); 59 | return clone; 60 | } 61 | 62 | throw new Error('whitelist has to be undefined, true, an array or an object'); 63 | }; 64 | -------------------------------------------------------------------------------- /test/cloneWhitelisted.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var should = require('should'); 3 | var _ = require('lodash'); 4 | 5 | var utils = require('./utils'); 6 | var authorize = utils.authorize; 7 | var obj = { 8 | field1: 1, 9 | field2: 'foo', 10 | nested: { 11 | field1: 2, 12 | field2: 'bar' 13 | }, 14 | array1: [1, 2, 3], 15 | array2: [{foo: 'bar', fuzz: 'bear'}, {foo: 'baz'}] 16 | }; 17 | 18 | describe('cloneWhitelisted()', function () { 19 | var cloneWhitelisted = authorize.cloneWhitelisted; 20 | 21 | it('should return undefined for a false or undefined whitelist', function () { 22 | _.each( 23 | [null, true, false, 1, 'foo', [null, true, false, 1, 'foo'], obj], 24 | function (value) { 25 | (cloneWhitelisted(value) === undefined).should.equal(true); 26 | (cloneWhitelisted(value, false) === undefined).should.equal(true); 27 | } 28 | ); 29 | }); 30 | 31 | it('should directly return non-array and non-object values', function () { 32 | _.each([true, false, 1, 'foo'], function (value) { 33 | cloneWhitelisted(value, true).should.equal(value); 34 | }); 35 | // null has to be treated differently with should 36 | (cloneWhitelisted(null, true) === null).should.equal(true); 37 | }); 38 | 39 | it('should copy arrays and objects', function () { 40 | _.each([ 41 | {obj: [1, 2, 3], whitelist: [true]}, 42 | {obj: {foo: 'bar'}, whitelist: {foo: true}} 43 | ], function (el) { 44 | var clone = cloneWhitelisted(el.obj, el.whitelist); 45 | clone.should.not.equal(el.obj); 46 | clone.should.eql(el.obj); 47 | }); 48 | }); 49 | 50 | it('should process nested arrays and objects', function () { 51 | var clone = cloneWhitelisted(obj, { 52 | field1: true, 53 | nested: { 54 | field1: true 55 | }, 56 | array2: [{fuzz: true}] 57 | }); 58 | clone.should.eql({ 59 | field1: 1, 60 | nested: { 61 | field1: 2 62 | }, 63 | array2: [{fuzz: 'bear'}, {}] 64 | }); 65 | }); 66 | }); 67 | -------------------------------------------------------------------------------- /test/utils.js: -------------------------------------------------------------------------------- 1 | var dbURI = 'mongodb://localhost/mongoose-authorize-test'; 2 | var mongoose = require('mongoose'); 3 | var async = require('async'); 4 | var _ = require('lodash'); 5 | 6 | var authorize = require('../')(); 7 | 8 | var defineModels = function (done) { 9 | // define User 10 | var userSchema = new mongoose.Schema({name: String}); 11 | mongoose.model('User', userSchema); 12 | 13 | // define Team 14 | var teamSchema = new mongoose.Schema({name: String}); 15 | teamSchema.plugin(authorize.teamPlugin); 16 | mongoose.model('Team', teamSchema); 17 | 18 | // define Organization 19 | var organizationSchema = new mongoose.Schema({name: String}); 20 | organizationSchema.plugin(authorize.permissionsPlugin); 21 | mongoose.model('Organization', organizationSchema); 22 | 23 | done(); 24 | }; 25 | 26 | var insertDocs = function (done) { 27 | async.waterfall( 28 | [ 29 | // create user1 and user2 30 | function (cb) { 31 | mongoose.model('User').create({name: 'nschloe'}, {name: 'andrenarchy'}, cb); 32 | }, 33 | // create team1 with member user1 34 | function (user1, user2, cb) { 35 | mongoose.model('Team').create( 36 | {name: 'team nschloe', members: {users: [user1._id] }}, 37 | function (err, team1) { 38 | if (err) return cb(err); 39 | return cb(null, user1, user2, team1); 40 | } 41 | ); 42 | }, 43 | // create team2 with members user2 and team1 -> user1 and user2 44 | function (user1, user2, team1, cb) { 45 | mongoose.model('Team').create( 46 | { 47 | name: 'team andrenarchy + friends', 48 | members: { 49 | users: [user2._id], 50 | teams: [team1._id] 51 | } 52 | }, 53 | function (err, team2) { 54 | if (err) return cb(err); 55 | return cb(null, user1, user2, team1, team2); 56 | } 57 | ); 58 | }, 59 | // create orga1 with permissions 60 | function (user1, user2, team1, team2, cb) { 61 | mongoose.model('Organization').create( 62 | { 63 | name: 'c-base', 64 | permissions: [ 65 | // team2: user1 and user2 (via team1) 66 | {team: team2, action: 'read', component: 'orgaInfo'}, 67 | // team1: user1 68 | {team: team1, action: 'write', component: 'orgaInfo'} 69 | ] 70 | }, 71 | function (err, orga1) { 72 | if (err) return cb(err); 73 | cb(null, user1, user2, team1, team2, orga1); 74 | } 75 | ); 76 | } 77 | ], 78 | done 79 | ); 80 | }; 81 | 82 | 83 | module.exports = { 84 | authorize: authorize, 85 | defineModels: defineModels, 86 | insertDocs: insertDocs, 87 | dbURI: dbURI 88 | }; 89 | -------------------------------------------------------------------------------- /lib/permissionsPlugin.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var mongoose = require('mongoose'); 3 | var async = require('async'); 4 | var _ = require('lodash'); 5 | 6 | module.exports = function (config) { 7 | return function (schema, options) { 8 | 9 | // add permissions to schema 10 | var permissionsSchema = {}; 11 | permissionsSchema[config.permissions] = [{ 12 | team: {type: mongoose.Schema.Types.ObjectId, ref: config.teamModel}, 13 | action: String, 14 | component: String 15 | }]; 16 | schema.add(permissionsSchema); 17 | 18 | schema.methods[config.permissionsGet] = 19 | function (done) { 20 | // populate permissions[].team 21 | this.populate( 22 | config.permissions + '.team', 23 | function (err, doc) { 24 | if (err) return done(err); 25 | async.parallel( 26 | // get userIds for each permission 27 | _.map(doc[config.permissions], function (permission) { 28 | return function (cb) { 29 | // get userIds for this permission 30 | permission.team[config.teamGetUserIds](function (err, userIds) { 31 | if (err) return cb(err); 32 | // return permission object with userIds (and without team) 33 | return cb(null, { 34 | userIds: _.map(userIds, String), 35 | action: permission.action, 36 | component: permission.component 37 | }); 38 | }); 39 | }; 40 | }), 41 | done 42 | ); 43 | } 44 | ); 45 | }; 46 | 47 | // check if a given user has the provided permission 48 | schema.methods[config.permissionsHas] = 49 | function (userId, action, component, done) { 50 | this[config.permissionsGet](function (err, permissions) { 51 | if (err) return done(err); 52 | // match given parameters 53 | var matches = _.where( 54 | permissions, 55 | {userIds: [userId.toString()], action: action, component: component} 56 | ); 57 | done(null, matches.length > 0); 58 | }); 59 | }; 60 | 61 | // check if a given user has the provided permission 62 | schema.methods[config.permissionsAssert] = 63 | function (userId, action, component, done) { 64 | this.hasPermissions(userId, action, component, function (err, granted) { 65 | if (err) return done(err); 66 | if (!granted) return done(new Error('permission denied')); 67 | done(); 68 | }); 69 | }; 70 | 71 | // get all components where the specified user has the permission to carry 72 | // out the specified action 73 | schema.methods[config.permissionsGetComponents] = 74 | function (userId, action, done) { 75 | this[config.permissionsGet](function (err, permissions) { 76 | if (err) return done(err); 77 | 78 | var components = _.union(_.pluck( 79 | _.where(permissions, {userIds: [userId.toString()], action: action}), 80 | 'component' 81 | )); 82 | 83 | return done(null, components); 84 | }); 85 | }; 86 | }; 87 | }; 88 | -------------------------------------------------------------------------------- /test/permissionsPlugin.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var mongoose = require('mongoose'); 3 | var erase = require('mongoose-erase'); 4 | var should = require('should'); 5 | var async = require('async'); 6 | var _ = require('lodash'); 7 | 8 | var utils = require('./utils'); 9 | 10 | describe('permissionPlugin', function () { 11 | 12 | beforeEach(erase.connectAndErase(mongoose, utils.dbURI)); 13 | beforeEach(utils.defineModels); 14 | 15 | describe('#getPermissions', function () { 16 | it('should return permissions with arrays of userIds', function (done) { 17 | utils.insertDocs(function (err, user1, user2, team1, team2, orga1) { 18 | if (err) return done(err); 19 | orga1.getPermissions(function (err, permissions) { 20 | if (err) return done(err); 21 | permissions.should.eql([ 22 | {userIds: [user2._id.toString(), user1._id.toString()], 23 | action: 'read', component: 'orgaInfo'}, 24 | {userIds: [user1._id.toString()], action: 'write', 25 | component: 'orgaInfo'} 26 | ]); 27 | done(); 28 | }); 29 | }); 30 | }); 31 | }); // getPermissions 32 | 33 | describe('#hasPermissions', function () { 34 | it('should return true/false based on permissions', function (done) { 35 | utils.insertDocs(function (err, user1, user2, team1, team2, orga1) { 36 | if (err) return done(err); 37 | // see definition of teams + permissions in utils.js 38 | 39 | async.series(_.map([ 40 | // check permissions for user1 41 | [user1._id, 'write', 'orgaInfo', true], 42 | [user1._id, 'read', 'orgaInfo', true], 43 | [user1._id, 'hack', 'orgaInfo', false], 44 | // check permission for user2 45 | [user2._id, 'write', 'orgaInfo', false], 46 | [user2._id, 'read', 'orgaInfo', true], 47 | [user2._id, 'hack', 'orgaInfo', false], 48 | // check permission for unknown user 49 | ['nobody', 'write', 'orgaInfo', false], 50 | ['nobody', 'read', 'orgaInfo', false], 51 | ['nobody', 'hack', 'orgaInfo', false] 52 | ], function (arr) { 53 | return function (cb) { 54 | return orga1.hasPermissions(arr[0], arr[1], arr[2], function (err, val) { 55 | if (err) return cb(err); 56 | should(val).equal(arr[3]); 57 | cb(); 58 | }); 59 | }; 60 | }), done); 61 | }); 62 | }); 63 | }); // hasPermission 64 | 65 | describe('#getComponents', function () { 66 | it('should return the list of valid components for an action', function (done) { 67 | 68 | utils.insertDocs(function (err, user1, user2, team1, team2, orga1) { 69 | if (err) return done(err); 70 | // see definition of teams + permissions in utils.js 71 | 72 | function checkComponents(target, userId, action, expected) { 73 | return function (cb) { 74 | target.getComponents(userId, action, function (err, components) { 75 | if (err) return cb(err); 76 | components.should.eql(expected); 77 | cb(); 78 | }); 79 | }; 80 | } 81 | 82 | async.series([ 83 | checkComponents(orga1, user1._id, 'read', ['orgaInfo']), 84 | checkComponents(orga1, user2._id, 'write', []) 85 | ], done); 86 | }); 87 | }); 88 | }); // getComponents 89 | }); 90 | -------------------------------------------------------------------------------- /test/teamPlugin.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var mongoose = require('mongoose'); 3 | var erase = require('mongoose-erase'); 4 | var should = require('should'); 5 | var async = require('async'); 6 | var _ = require('lodash'); 7 | 8 | var utils = require('./utils'); 9 | 10 | describe('teamPlugin', function () { 11 | beforeEach(erase.connectAndErase(mongoose, utils.dbURI)); 12 | beforeEach(utils.defineModels); 13 | 14 | describe('#getUserIds', function () { 15 | it( 16 | 'should allow insertion of users and teams as described in the docs', 17 | function (done) { 18 | async.waterfall([ 19 | // create a user 20 | function (cb) { 21 | mongoose.model('User').create({name: 'hondanz'}, {name: 'halligalli'}, cb); 22 | }, 23 | // create a team 'admins' with member user_hondanz 24 | function(user_hondanz, user_halligalli, cb) { 25 | mongoose.model('Team').create( 26 | { 27 | name: 'admins', 28 | members: { 29 | users: [user_hondanz], 30 | teams: [] 31 | } 32 | }, 33 | function (err, team_admins) { 34 | if (err) return cb(err); 35 | cb(null, user_hondanz, user_halligalli, team_admins); 36 | } 37 | ); 38 | }, 39 | // create a team 'editors' with members user_halligalli and all members of team_admins 40 | function (user_hondanz, user_halligalli, team_admins, cb) { 41 | mongoose.model('Team').create( 42 | { 43 | name: 'editors', 44 | members: { 45 | users: [user_halligalli], 46 | teams: [team_admins] 47 | } 48 | }, 49 | function (err, team_editors) { 50 | if (err) return cb(err); 51 | cb(null, user_hondanz, user_halligalli, team_editors); 52 | } 53 | ); 54 | }], 55 | function (err, user_hondanz, user_halligalli, team_editors) { 56 | should(err).equal(null); 57 | team_editors.getUserIds(function (err, userIds) { 58 | should(err).equal(null); 59 | userIds.should.eql([user_halligalli._id, user_hondanz._id]); 60 | done(); 61 | }); 62 | } 63 | ); 64 | } 65 | ); 66 | 67 | it('should return an empty array without members', function (done) { 68 | var team = new (mongoose.model('Team'))({name: 'andrenarchy\'s friends'}); 69 | team.getUserIds(function (err, userIds) { 70 | if (err) return done(err); 71 | [].should.eql(userIds); 72 | done(); 73 | }); 74 | }); 75 | 76 | it('should return array of user ids without team members', function (done) { 77 | var user1 = new (mongoose.model('User'))({name: 'andrenarchy'}); 78 | var user2 = new (mongoose.model('User'))({name: 'nschloe'}); 79 | var team = new (mongoose.model('Team'))({ 80 | name: 'PaperHub', 81 | members: { 82 | users: [user1._id, user2._id] 83 | } 84 | }); 85 | team.getUserIds(function (err, userIds) { 86 | if (err) return done(err); 87 | [user1._id, user2._id].should.eql(userIds); 88 | done(); 89 | }); 90 | }); 91 | 92 | it('should return array of user ids for nested teams', function (done) { 93 | utils.insertDocs(function (err, user1, user2, team1, team2) { 94 | if (err) return done(err); 95 | team2.getUserIds(function (err, userIds) { 96 | if (err) return done(err); 97 | [user2._id, user1._id].should.eql(userIds); 98 | done(); 99 | }); 100 | }); 101 | }); 102 | it('should detect team cycles', function(done) { 103 | utils.insertDocs(function (err, user1, user2, team1, team2) { 104 | if (err) return done(err); 105 | team1.members.teams.push(team2); 106 | team1.save(function (err, team1) { 107 | if (err) return done(err); 108 | team1.getUserIds(function (err, userIds) { 109 | if (err) return done(err); 110 | [user1._id, user2._id].should.eql(userIds); 111 | done(); 112 | }); 113 | }); 114 | }); 115 | }); 116 | }); // #getUserIds 117 | }); // teamPlugin 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DEPRECATED! 2 | 3 | This module is no longer maintained (March 2016). We recommend the lightweight module [walter-whitelist](https://github.com/paperhive/walter-whitelist) for authorizing read/write access to object properties. 4 | 5 | # mongoose-authorize 6 | [![Build Status](https://travis-ci.org/paperhive/mongoose-authorize.svg)](https://travis-ci.org/paperhive/mongoose-authorize) [![Coverage Status](https://coveralls.io/repos/paperhive/mongoose-authorize/badge.svg?branch=master)](https://coveralls.io/r/paperhive/mongoose-authorize?branch=master) [![Dependency Status](https://gemnasium.com/paperhive/mongoose-authorize.svg)](https://gemnasium.com/paperhive/mongoose-authorize) 7 | 8 | [![NPM](https://nodei.co/npm/mongoose-authorize.png?downloads=true)](https://nodei.co/npm/mongoose-authorize/) 9 | 10 | An **authorization** (*not* authentication) plugin for mongoose. 11 | 12 | Usually not all fields of a document in your database are supposed to be read 13 | or written by all users of your application. This authorization plugin allows 14 | you to 15 | 16 | * group your schema fields into components 17 | * specify permissions: which components can be accessed by whom (either 18 | statically or dynamically and user-configurable in your documents) 19 | * organize multiple users in teams 20 | * serialize a mongoose document: get all fields for which a user has read 21 | access (also takes care of nested schemas and populated referenced documents) 22 | * verify and set user-provided data in a mongoose document: only set the fields 23 | for which a user has write access (note: work in progress) 24 | 25 | The permission module in `mongoose-authorize` can be seen as a 26 | *role-based access control (RBAC)* system. Unlike other modules (e.g., 27 | [mongoose-rbac](https://github.com/bryandragon/mongoose-rbac)), the permissions 28 | in `mongoose-authorize` do not have to be specified globally (e.g., inside the 29 | user model) but can be maintained inside other entities such as organizations. 30 | 31 | ## Example 32 | 33 | The core idea of `mongoose-authorize` is to split a mongoose schema into 34 | *components* for which you can then define permissions. Let's take a look at 35 | the following example: 36 | ```javascript 37 | var userSchema = new mongoose.Schema({ 38 | name: {type: String, component: 'info'}, 39 | passwordHash: String, 40 | father: {type: mongoose.Schema.Types.ObjectId, ref: 'User', component: 'info'}, 41 | settings: { 42 | rememberMe: {type: Boolean, component: 'settings'} 43 | } 44 | }); 45 | ``` 46 | Here we have used two components which are intended to impose the following 47 | permissions: 48 | * *info*: can be read by everyone but only written by the owner 49 | * *settings*: can only be read and written by the owner 50 | 51 | This can be achieved with the `componentsPlugin`: 52 | ```javascript 53 | var authorize = require('mongoose-authorize')(); 54 | userSchema.plugin(authorize.componentsPlugin, { 55 | permissions: { 56 | defaults: {read: ['info']}, 57 | fromFun: function (doc, userId, action, done) { 58 | // owner has full access to info and settings 59 | if (doc._id.equals(userId)) return done(null, ['info', 'settings']); 60 | // otherwise: no access (except the defaults specified above) 61 | done(null, []); 62 | } 63 | } 64 | }); 65 | ``` 66 | 67 | Let's create the model and add two users: 68 | ```javascript 69 | mongoose.model('User', userSchema).create( 70 | {name: 'Luke', passwordHash: '0afb5c', settings: {rememberMe: true}}, 71 | {name: 'Darth', passwordHash: 'd4c18b', settings: {rememberMe: false}}, 72 | function (err, luke, darth) { 73 | luke.father = darth; 74 | luke.save(function (err, luke) { /* ... */ }); 75 | } 76 | ); 77 | ``` 78 | 79 | In order to demonstrate this plugin's ability to properly process referenced 80 | documents we populate Luke's `father` field: 81 | ```javascript 82 | luke.populate('father', function (err, luke) { /* ... */ }); 83 | ``` 84 | 85 | Let's assume that Luke is authenticated and wants to have a representation 86 | of himself: 87 | ```javascript 88 | luke.authorizedToObject(luke._id, function (err, obj) { 89 | console.log(obj); 90 | }); 91 | ``` 92 | Result: 93 | ```javascript 94 | { name: 'Luke', 95 | settings: { rememberMe: true }, 96 | father: { name: 'Darth', _id: '549af64bd25236066b30dbe1' }, 97 | _id: '549af64bd25236066b30dbe0' } 98 | ``` 99 | 100 | Now let's assume that Darth is authenticated and wants to have a 101 | representation of his son: 102 | ```javascript 103 | luke.authorizedToObject(darth._id, function (err, obj) { 104 | console.log(obj); 105 | }); 106 | ``` 107 | Result: 108 | ```javascript 109 | { name: 'Luke', 110 | father: 111 | { name: 'Darth', 112 | settings: { rememberMe: false }, 113 | _id: '549af64bd25236066b30dbe1' }, 114 | _id: '549af64bd25236066b30dbe0' } 115 | ``` 116 | Note that Luke's settings are missing in Darth's representation. However, Darth 117 | is allowed to see his own settings in the populated `father` field. 118 | 119 | 120 | ## Documentation 121 | 122 | `mongoose-authorize` offers the following plugins: 123 | 124 | * [componentsPlugin](#componentsplugin) 125 | * [teamPlugin](#teamplugin) 126 | * [permissionsPlugin](#permissionsplugin) 127 | 128 | 129 | ### componentsPlugin 130 | 131 | *Note: see the [above example](#example) for a brief in-use explanation of this 132 | plugin.* 133 | 134 | The `componentsPlugin` works as follows for a schema 135 | 136 | 1. A `component` can be assigned to each field of the schema. The `component` 137 | can either be 138 | * a string: the static name of the component. 139 | * a function `component(doc, callback)` where `doc` is the document 140 | instance. The function should call the `callback` with a string (the 141 | name of the component). This can be useful, e.g., for controlling the 142 | visibility of fields with a `visible` field in your document. 143 | 2. The `componentPlugin` is loaded into the schema. You have to define 144 | how the permissions of a user (identified by the user's document id, the 145 | `userId`) are obtained. Therefore, the plugin accepts a `permissions` key in 146 | the options object with the following sub-keys: 147 | 148 | * `defaults`: an object mapping action strings to an array of component 149 | strings. Useful for default permissions such as "all users are able to 150 | access the fields belonging to the component `'info'`. 151 | * `fromFun(doc, userId, action, callback)`: a function that computes an 152 | array of components where the `userId` can carry out the specified 153 | `action` on the given `doc`. The `callback` has the signature 154 | `callback(err, components)`. 155 | * `fromDoc`: a boolean that indicates if the permissions should be read 156 | from the document via the [permissionsPlugin](#permissionsplugin). 157 | 158 | For a mongoose document `doc`, the plugin then offers the following methods: 159 | 160 | #### doc.authorizedComponents(userId, action, callback) 161 | 162 | Compile an array of all components where the provided `userId` has the 163 | permission to carry out the specified `action`. 164 | 165 | * `userId`: document id of a user. 166 | * `action`: a string representing an action (such as `'read'` or `'write'`). 167 | * `callback(err, components)`: the callback to be called where `components` is 168 | an array of components. 169 | 170 | #### doc.authorizedToObject(userId, [options], callback) 171 | 172 | Creates an object representation (e.g., for serializing it to JSON via 173 | `JSON.stringify()`) of the document tailored for the provided `userId`, i.e., 174 | an object where only the fields of the components are visible where the 175 | provided `userId` has `'read'` access. 176 | 177 | * `userId`: document id of a user. 178 | * `options`: options passed to 179 | [`toObject()`](http://mongoosejs.com/docs/api.html#document_Document-toObject) 180 | which is used internally to serialize the document. 181 | * `callback(err, obj)`: the callback to be called with the object. 182 | 183 | #### doc.authorizedSet(userId, obj, callback) 184 | 185 | Set the provided object `obj` on the document if the provided `userId` has 186 | `'write'` access for all fields in `obj` (possibly nested, see below). 187 | If the `userId` is not authorized, then the document remains unchanged. 188 | 189 | * `userId`: document id of a user 190 | * `obj`: a plain object. The following values are allowed: 191 | * primitives: String, Number, Boolean, null 192 | * plain objects: must correspond to a nested object (not referenced and 193 | populated documents) 194 | * arrays with primitives (arrays of subdocuments are not allowed and have to 195 | be processed with the `authorizedArray...` methods, see below) 196 | * `callback(err)` 197 | 198 | #### doc.authorizedArrayPush(userId, array, obj, callback) 199 | 200 | Push the provided object `obj` as a subdocument to the array `array` on the 201 | document if the provided `userId` has `'write'` access for all fields in `obj` 202 | (possibly nested, see below) *and* for the array itself. If the `userId` is not 203 | authorized, then the document remains unchanged. 204 | 205 | * `userId`: document id of a user 206 | * `array`: an array that is contained in the document 207 | * `obj`: a plain object. The following values are allowed: 208 | * primitives: String, Number, Boolean, null 209 | * plain objects: must correspond to a nested object (not referenced and 210 | populated documents) 211 | * arrays with primitives (arrays of subdocuments are not allowed in this 212 | method and have to be processed with authorizedArrayPush separately) 213 | * `callback(err)` 214 | 215 | #### doc.authorizedArrayRemove(userId, array, id, callback) 216 | 217 | Remove the subdocument identified by `id` from the array `array` in the 218 | document if the provided `userId` has `'write'` access for the array. If the 219 | `userId` is not authorized, then the document remains unchanged. 220 | 221 | * `userId`: document id of a user 222 | * `array`: an array that is contained in the document 223 | * `id`: a subdocument id in `array` 224 | * `callback(err)` 225 | 226 | #### doc.authorizedArraySet(userId, array, id, obj, callback) 227 | 228 | Update the subdocument identified by `id` with the provided object `obj` as a 229 | subdocument to the array `array` on the document if the provided `userId` has 230 | `'write'` access for all fields in `obj` (possibly nested, see below). If the 231 | `userId` is not authorized, then the document remains unchanged. 232 | 233 | * `userId`: document id of a user 234 | * `array`: an array that is contained in the document 235 | * `id`: a subdocument id in `array` 236 | * `obj`: a plain object. The following values are allowed: 237 | * primitives: String, Number, Boolean, null 238 | * plain objects: must correspond to a nested object (not referenced and 239 | populated documents) 240 | * arrays with primitives (arrays of subdocuments are not allowed in this 241 | method and have to be processed with authorizedArraySet separately) 242 | * `callback(err)` 243 | 244 | ### teamPlugin 245 | * organize users in teams 246 | * teams can be nested arbitrarily (cycles are properly handled) 247 | 248 | Let's take the following simple model of a user: 249 | ```javascript 250 | mongoose.model('User', new mongoose.Schema({name: String})); 251 | ``` 252 | Yours may be arbitrarily more complex, e.g., you may want to store a password hash in order to authenticate users. 253 | 254 | Now assume you want to organize users in teams. Let's create a team model with the `teamPlugin`: 255 | ```javascript 256 | var teamSchema = new mongoose.Schema({name: String}); 257 | teamSchema.plugin(authorize.teamPlugin); 258 | mongoose.model('Team', teamSchema); 259 | ``` 260 | 261 | So let's create an actual user and a team by filling the `members.users` and `members.teams` properties: 262 | ```javascript 263 | var async = require('async'); // makes code more readable 264 | 265 | async.waterfall([ 266 | // create a user 267 | function (cb) { 268 | mongoose.model('User').create({name: 'hondanz'}, {name: 'halligalli'}, cb); 269 | }, 270 | // create a team 'admins' with member user_hondanz 271 | function(user_hondanz, user_halligalli, cb) { 272 | mongoose.model('Team').create( 273 | { 274 | name: 'admins', 275 | members: { 276 | users: [user_hondanz], 277 | teams: [] 278 | } 279 | }, 280 | function (err, team_admins) { 281 | if (err) return cb(err); 282 | cb(null, user_halligalli, team_admins); 283 | } 284 | ); 285 | }, 286 | // create a team 'readers' with members user_halligalli and all members of team_admins 287 | function (user_halligalli, team_admins, cb) { 288 | mongoose.model('Team').create( 289 | { 290 | name: 'readers', 291 | members: { 292 | users: [user_halligalli], 293 | teams: [team_admins] 294 | } 295 | }, 296 | cb 297 | ); 298 | }], 299 | function (err, team_readers) { 300 | if (err) return console.error(err); 301 | // use team_readers, e.g., team_readers.getUserIds(...), see below 302 | } 303 | ); 304 | ``` 305 | #### teamPlugin.getUserIds(callback) 306 | Because teams may have users *and* teams as members, the team plugin offers `getUserIds` to get a flat array of all members' userIds. 307 | 308 | * `callback(err, userIds)` where userIds is an array of all members' userIds (includes members of nested teams). 309 | 310 | ##### Example 311 | ```javascript 312 | team_readers.getUserIds(function (err, userIds) { 313 | if (err) return console.error(err); 314 | // userIds now contains: [user_halligalli._id, user_hondanz._id] 315 | }); 316 | ``` 317 | 318 | ### permissionsPlugin 319 | * grant and check permissions for actions on ressources to teams 320 | 321 | Assume you store articles and you want to grant permissions on this article. Let's use the `permissionsPlugin` for this: 322 | ```javascript 323 | var articleSchema = new mongoose.Schema({title: String, body: String}); 324 | articleSchema.plugin(authorize.permissionsPlugin); 325 | mongoose.model('Article', articleSchema); 326 | ``` 327 | Now we can create an article and assign permissions for the teams created above by filling the property `permissions`: 328 | ```javascript 329 | mongoose.model('Article').create( 330 | { 331 | title: 'most interesting article ever', 332 | body: 'lorem ipsum', 333 | permissions: [ 334 | {team: team_readers, action: 'read', ressource: 'body'}, 335 | {team: team_admins, action: 'write', ressource: 'body'} 336 | ] 337 | }, 338 | function (err, article) { 339 | if (err) return console.error(err); 340 | // use article, e.g., article.getPermissions() or 341 | // article.hasPermissions(userId, action, ressource), see below 342 | } 343 | ); 344 | ``` 345 | 346 | #### permissionsPlugin.getPermissions(callback) 347 | 348 | Returns an array of all permissions with flattened userIds. 349 | 350 | * `callback(err, permissions)` where permissions is an array of permissions, each having the properties 351 | * `userIds`: the provided team is resolved to userIds via [teamPlugin.getUserIds](#teamplugingetuseridscallback) 352 | * `action`: the string as provided in the permission 353 | * `ressource`: the string as provided in the permission 354 | 355 | ##### Example 356 | ```javascript 357 | article.getPermissions(function (err, permissions) { 358 | if (err) return console.error(err); 359 | /* permissions contains: 360 | [ 361 | {userIds: [user_halligalli._id, user_hondanz._id], action: 'read', ressource: 'body'}, 362 | {userIds: [user_hondanz._id], action: 'write', ressource: 'body'}, 363 | ] 364 | */ 365 | }); 366 | ``` 367 | 368 | #### permissionsPlugin.hasPermissions(userId, action, ressource, callback) 369 | 370 | * `userId`: a userId string 371 | * `action`: a string 372 | * `ressource`: a string 373 | * `callback(err, granted)`: `granted` is true if and only if the provided user has the permission to perform the specified action on the specified ressource. 374 | 375 | ##### Example 376 | ```javascript 377 | article.hasPermissions(user_halligalli._id, 'write', 'body', function (err, granted) { 378 | if (err) return console.error(err); 379 | // granted is false 380 | }); 381 | article.hasPermissions(user_hondanz._id, 'read', 'body', function (err, granted) { 382 | if (err) return console.error(err); 383 | // granted is true 384 | }); 385 | ``` 386 | -------------------------------------------------------------------------------- /lib/componentsPlugin.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var mongoose = require('mongoose'); 3 | var async = require('async'); 4 | var _ = require('lodash'); 5 | 6 | module.exports = function (config) { 7 | return function (schema, pluginOptions) { 8 | pluginOptions = _.defaults( 9 | _.cloneDeep(pluginOptions || {}), 10 | { 11 | pathComponents: {} 12 | } 13 | ); 14 | 15 | // compile an array of all components where the provided userId is able 16 | // to carry out the provided action 17 | schema.methods[config.authorizedComponents] = 18 | function (userId, action, done) { 19 | var components = []; 20 | 21 | // fetch default permissions from plugin options 22 | var defaultComponents = 23 | pluginOptions.permissions && 24 | pluginOptions.permissions.defaults && 25 | pluginOptions.permissions.defaults[action]; 26 | if (_.isArray(defaultComponents)) { 27 | components = defaultComponents; 28 | } 29 | 30 | var doc = this; 31 | var tasks = []; 32 | 33 | // fetch permissions from function provided in plugin options 34 | if (pluginOptions.permissions && 35 | _.isFunction(pluginOptions.permissions.fromFun)) { 36 | tasks.push(function (cb) { 37 | return pluginOptions.permissions.fromFun(doc, userId, action, cb); 38 | }); 39 | } 40 | 41 | // fetch permissions from document 42 | if (pluginOptions.permissions && pluginOptions.permissions.fromDoc) { 43 | tasks.push(function (cb) { 44 | return doc[config.permissionsGetComponents](userId, action, cb); 45 | }); 46 | } 47 | 48 | async.parallel(tasks, function (err, results) { 49 | if (err) return done(err); 50 | return done(null, _.union(_.flattenDeep([components, results]))); 51 | }); 52 | }; 53 | 54 | /* Resolve a component (maybe undefined, a string or a function) */ 55 | function componentResolve(component, doc, cb) { 56 | if (!component || _.isString(component)) { 57 | return cb(null, component); 58 | } 59 | return component(doc, cb); 60 | } 61 | 62 | /* toObject-like function that only returns the fields where the user 63 | * has read permissions. 64 | * 65 | * TODO: process virtual fields 66 | */ 67 | schema.methods[config.authorizedToObject] = 68 | function (userId, optionsToObject, done) { 69 | 70 | // allow to omit optionsToObject 71 | if (_.isFunction(optionsToObject)) { 72 | done = optionsToObject; 73 | optionsToObject = undefined; 74 | } 75 | 76 | return authorizedToObject(this, userId, optionsToObject, [], done); 77 | }; 78 | 79 | function authorizedToObject (doc, userId, optionsToObject, visitedDocs, done) { 80 | // has this doc already been processed? 81 | var id = doc._id.toString(); 82 | if (visitedDocs && _.contains(visitedDocs, id)) { 83 | return done(null, id); 84 | } 85 | if (!visitedDocs) visitedDocs = []; 86 | visitedDocs.push(id); 87 | 88 | return async.waterfall([ 89 | function (cb) { 90 | // get components the user has permissions to read 91 | return doc[config.authorizedComponents](userId, 'read', cb); 92 | }, 93 | function (components, cb) { 94 | return docToObject(userId, optionsToObject, doc, components, visitedDocs, 95 | cb); 96 | } 97 | ], done); 98 | } 99 | 100 | function docToObject (userId, optionsToObject, doc, readComponents, visitedDocs, 101 | done) { 102 | 103 | processObj(doc.toObject(optionsToObject), undefined, function (err, obj) { 104 | if (err) return done(err); 105 | if (!obj || _.isEmpty(obj)) return done(); 106 | 107 | // insert _id 108 | obj._id = doc._id.toString(); 109 | return done(null, obj); 110 | }); 111 | 112 | // recursively process objects until a subdocument is reached 113 | function processObj (obj, path, cbObj) { 114 | 115 | // helper function for processing leaf elements 116 | function processLeaf(obj, objdoc, pathOptions, schema, cbLeaf) { 117 | // is sub/embedded document (authorization is checked there) 118 | if (schema) { 119 | return docToObject(userId, optionsToObject, objdoc, readComponents, 120 | _.clone(visitedDocs, true), cbLeaf); 121 | } 122 | 123 | // check access to component 124 | var pathComponent = pathOptions.component || 125 | pluginOptions.pathComponents[path]; 126 | componentResolve(pathComponent, doc, 127 | function (err, component) { 128 | if (err) return cbLeaf(err); 129 | 130 | if (!component || !_.contains(readComponents, component)) { 131 | return cbLeaf(); 132 | } 133 | 134 | // referenced document 135 | if (pathOptions.ref) { 136 | // unpopulated (id only) 137 | if (obj instanceof mongoose.Types.ObjectId) { 138 | return cbLeaf(null, obj.toString()); 139 | } 140 | 141 | // populated 142 | return authorizedToObject(objdoc, userId, optionsToObject, 143 | _.clone(visitedDocs, true), cbLeaf); 144 | } 145 | 146 | // primitive JSON type 147 | if (_.isNull(obj) || _.isString(obj) || 148 | _.isNumber(obj) || _.isBoolean(obj)) { 149 | return cbLeaf(null, obj); 150 | } 151 | 152 | // date 153 | if (_.isDate(obj)) { 154 | return cbLeaf(null, obj.toISOString()); 155 | } 156 | 157 | // should never be reached! 158 | return cbLeaf(new Error('unhandled type!')); 159 | }); // componentFun 160 | } 161 | 162 | var pathComponent; 163 | 164 | // root object or nested object 165 | if (!path || doc.schema.nested[path]) { 166 | return async.parallel( 167 | // process keys 168 | _.mapValues(obj, function (value, key) { 169 | return function (cb) { 170 | var curPath = path ? path + '.' + key : key; 171 | return processObj(value, curPath, cb); 172 | }; 173 | }), 174 | // remove keys with undefined values 175 | function (err, result) { 176 | if (err) return cbObj(err); 177 | result = _.pick(result, function (value) { 178 | return value !== undefined; 179 | }); 180 | // return undefined instead of empty object 181 | return cbObj(null, _.isEmpty(result) ? undefined : result); 182 | } 183 | ); 184 | } 185 | 186 | // 'leaf' path (in this document) 187 | var pathConfig = doc.schema.paths[path]; 188 | if (pathConfig) { 189 | 190 | // is array 191 | if (_.isArray(pathConfig.options.type)) { 192 | 193 | // check access to component 194 | pathComponent = pathConfig.options.component || 195 | pluginOptions.pathComponents[path]; 196 | return componentResolve(pathComponent, doc, function (err, component) { 197 | if (err) return cbObj(err); 198 | 199 | if (!component || !_.contains(readComponents, component)) { 200 | return cbObj(); 201 | } 202 | 203 | // iterate over obj and corresponding mongoose objects 204 | return async.parallel(_.map( 205 | _.zip(obj, doc.get(path)), 206 | function (value) { 207 | return function (cb) { 208 | processLeaf( 209 | value[0], value[1], 210 | pathConfig.options.type[0], pathConfig.schema, 211 | cb 212 | ); 213 | }; 214 | } 215 | ), function (err, results) { 216 | if (err) return cbObj(err); 217 | results = _.compact(results); 218 | cbObj(null, results.length ? results : []); 219 | }); 220 | }); 221 | } 222 | 223 | return processLeaf(obj, doc.get(path), 224 | pathConfig.options, pathConfig.schema, 225 | cbObj 226 | ); 227 | } 228 | 229 | // virtual 230 | var virtualConfig = doc.schema.virtuals[path]; 231 | if (virtualConfig) { 232 | // check access to component 233 | pathComponent = virtualConfig.options.component || 234 | pluginOptions.pathComponents[path]; 235 | return componentResolve(pathComponent, doc, 236 | function (err, component) { 237 | if (err) return cbObj(err); 238 | 239 | if (!component || !_.contains(readComponents, component)) { 240 | return cbObj(); 241 | } 242 | 243 | return cbObj(null, obj); 244 | }); 245 | } 246 | 247 | // should never be reached! 248 | return cbObj(new Error('unhandled type')); 249 | } 250 | } 251 | 252 | /* 253 | * Checks if the provided object can be set by the userId in the provided 254 | * doc and sets the data. If the userId is not authorized to write a field, 255 | * the document is not modified at all. 256 | * 257 | * Parameters: 258 | * * obj: input as a plain object. The following values are allowed: 259 | * * primitives: String, Number, Boolean, null 260 | * * plain objects: must correspond to a nested object (not referenced 261 | * and populated documents) 262 | * * arrays with primitives (arrays of subdocuments are not allowed and 263 | * have to be processed separately with TODO) 264 | */ 265 | schema.methods[config.authorizedSet] = 266 | function (userId, obj, options, done) { 267 | if (_.isUndefined(done)) { 268 | done = options; 269 | options = {}; 270 | } 271 | authorizedSet(this, userId, obj, options, done); 272 | }; 273 | function authorizedSet(doc, userId, obj, options, done) { 274 | options = options || {}; 275 | if (!_.isPlainObject(obj)) { 276 | return done(new Error('obj must be a plain object')); 277 | } 278 | // TODO: check if doc is document 279 | return async.waterfall([ 280 | function (cb) { 281 | // get components the user has permissions to write 282 | // TODO: get components via parent doc if doc is a nested doc 283 | return doc[config.authorizedComponents](userId, 'write', cb); 284 | }, 285 | function (writeComponents, cb) { 286 | // recursively check if obj can be set on the doc 287 | return checkObjectSchema(obj, doc.schema, doc, writeComponents, 288 | function (err) { 289 | if (err) return cb(err); 290 | return cb(null, writeComponents); 291 | } 292 | ); 293 | }, 294 | // (only reached if the check above was successful) 295 | function (writeComponents, cb) { 296 | // overwrite? -> remove all user-writeable fields 297 | if (options.overwrite) { 298 | // check permissions for all paths and overwrite with undefined 299 | // if appropriate 300 | async.parallel( 301 | _.map(doc.schema.paths, function (path, pathName) { 302 | return function (cb) { 303 | // get component of path 304 | var pathComponent = path.options.component || 305 | pluginOptions.pathComponents[pathName]; 306 | return componentResolve(pathComponent, doc, 307 | function (err, component) { 308 | // check permission for this path 309 | if (!component || !_.contains(writeComponents, component)) 310 | return cb(); 311 | 312 | if (_.isArray(path.options.type)) { 313 | // do not touch subdocuments 314 | if (path.schema) return cb(); 315 | } 316 | doc.set(path.path, undefined); 317 | return cb(); 318 | } 319 | ); 320 | }; 321 | }) 322 | ); 323 | } 324 | 325 | // set obj on the document 326 | doc.set(obj); 327 | cb(); 328 | } 329 | ], done); 330 | } 331 | 332 | /* recursively walks the object and checks if it complies with the 333 | * provided document schema and writeComponents 334 | * 335 | * Parameters: 336 | * * obj: see authorizedSet 337 | * * schema: a document schema 338 | * * doc (optional) a document which is passed to component functions 339 | * * writeComponents: see authorizedSet 340 | * * done: function callback(err) 341 | */ 342 | function checkObjectSchema(obj, schema, doc, writeComponents, done) { 343 | 344 | checkObj(obj, null, done); 345 | 346 | /* recursively walk through objects. 347 | * (does not process referenced documents) 348 | * Parameters: 349 | * * obj an object or array with data to be stored 350 | * * path: current path for obj in doc. Either: 351 | * * path is undefined (dst is the root object) 352 | * * path is a string (schema.nested[path] is true, i.e. dst is a nested 353 | * object) 354 | * * cbObj: callback with signature function cbObj(err) 355 | */ 356 | function checkObj (obj, path, cbObj) { 357 | // is obj a plain object? 358 | if (!_.isPlainObject(obj)) { 359 | return cbObj(new Error('plain object expected')); 360 | } 361 | // either no path (root level) or valid path (nested obj) 362 | if (path && !schema.nested[path]) { 363 | return cbObj(new Error('path is not a valid nested doc')); 364 | } 365 | 366 | // iterate over key-value pairs 367 | return async.parallel( 368 | _.map(obj, function (value, key) { 369 | return function (cb) { 370 | var curPath = path ? path + '.' + key : key; 371 | 372 | // 'leaf' path (in this document) 373 | var pathConfig = schema.paths[curPath]; 374 | if (pathConfig) { 375 | 376 | // is array 377 | if (_.isArray(pathConfig.options.type)) { 378 | if (!_.isArray(value)) { 379 | return cb(new Error('array expected at path ' + curPath)); 380 | } 381 | // check that array does not contain subdocuments 382 | if (pathConfig.schema) { 383 | return cb(new Error( 384 | 'setting subdocuments in arrays is not allowed' 385 | )); 386 | } 387 | // iterate over array elements 388 | return async.parallel(_.map(value, function (element) { 389 | return function (cbElement) { 390 | return checkLeaf(element, curPath, 391 | pathConfig.options.type[0].component || 392 | pathConfig.options.component, 393 | cbElement); 394 | }; 395 | }), cb); 396 | } 397 | 398 | // primitive leaf element 399 | return checkLeaf(value, curPath, pathConfig.options.component, cb); 400 | } 401 | 402 | // nested document 403 | if (schema.nested[curPath]) { 404 | return checkObj(value, curPath, cb); 405 | } 406 | 407 | // should never be reached! 408 | return cb(new Error('unhandled type')); 409 | }; 410 | }), 411 | function (err) { 412 | return cbObj(err); 413 | } 414 | ); // async.parallel 415 | } // checkObj 416 | 417 | /* check a 'leaf' value in current document: 418 | * Parameters: 419 | * * value: a primitive (String, Number, Boolean, null) 420 | * * path: the path for this value (doc.schema.paths[path] must be valid) 421 | * * cbKey: callback with signature function cbKey(err) 422 | */ 423 | function checkLeaf(value, path, component, cbLeaf) { 424 | // check access to component 425 | component = component || pluginOptions.pathComponents[path]; 426 | componentResolve(component, doc, function (err, component) { 427 | if (err) return cbLeaf(err); 428 | 429 | if (!component || !_.contains(writeComponents, component)) { 430 | return cbLeaf(new Error('not allowed to write path ' + path)); 431 | } 432 | 433 | // primitive JSON type or undefined 434 | if (_.isNull(value) || _.isString(value) || 435 | _.isNumber(value) || _.isBoolean(value) || 436 | _.isUndefined(value)) { 437 | return cbLeaf(); 438 | } 439 | 440 | // should never be reached! 441 | return cbLeaf(new Error( 442 | 'unhandled type! are you trying to update a populated reference?' 443 | )); 444 | }); // componentFun 445 | } // checkLeaf 446 | } 447 | 448 | schema.methods[config.authorizedArrayPush] = 449 | function (userId, array, obj, done) { 450 | var doc = this; 451 | 452 | if (!_.isPlainObject(obj)) { 453 | return done(new Error('obj must be a plain object')); 454 | } 455 | 456 | return async.waterfall([ 457 | function (cb) { 458 | // get components the user has permissions to write 459 | // TODO: get components via parent doc if doc is a nested doc 460 | return doc[config.authorizedComponents](userId, 'write', cb); 461 | }, 462 | function (writeComponents, cb) { 463 | // resolve array component 464 | return componentResolve( 465 | array._schema.options.component, null, 466 | function (err, component) { 467 | if (err) return cb(err); 468 | // check if the user has write permissions on the array 469 | if (!component || !_.contains(writeComponents, component)) { 470 | return cb(new Error( 471 | 'not allowed to write array at path ' + array._path 472 | )); 473 | } 474 | 475 | // check obj with the subdocument's schema 476 | return checkObjectSchema(obj, array._schema.schema, null, 477 | writeComponents, cb); 478 | } 479 | ); 480 | }, 481 | function (cb) { 482 | // push obj to the array 483 | array.push(obj); 484 | cb(); 485 | } 486 | ], done); 487 | }; // authorizedArrayPush 488 | 489 | schema.methods[config.authorizedArrayRemove] = 490 | function (userId, array, id, done) { 491 | var doc = this; 492 | 493 | return async.waterfall([ 494 | function (cb) { 495 | // get components the user has permissions to write 496 | // TODO: get components via parent doc if doc is a nested doc 497 | return doc[config.authorizedComponents](userId, 'write', cb); 498 | }, 499 | function (writeComponents, cb) { 500 | // resolve array component 501 | return componentResolve( 502 | array._schema.options.component, null, 503 | function (err, component) { 504 | if (err) return cb(err); 505 | // check if the user has write permissions on the array 506 | if (!component || !_.contains(writeComponents, component)) { 507 | return cb(new Error( 508 | 'not allowed to write array at path ' + array._path 509 | )); 510 | } 511 | return cb(); 512 | } 513 | ); 514 | }, 515 | function (cb) { 516 | // remove subdocument from array 517 | var el = array.id(id); 518 | if (!el) { 519 | return cb(new Error('element with id ' + id + ' does not exist')); 520 | } 521 | el.remove(); 522 | cb(); 523 | } 524 | ], done); 525 | }; // authorizedArrayRemove 526 | 527 | schema.methods[config.authorizedArraySet] = 528 | function (userId, array, id, obj, done) { 529 | var doc = this; 530 | 531 | if (!_.isPlainObject(obj)) { 532 | return done(new Error('obj must be a plain object')); 533 | } 534 | 535 | return async.waterfall([ 536 | function (cb) { 537 | // get components the user has permissions to write 538 | // TODO: get components via parent doc if doc is a nested doc 539 | return doc[config.authorizedComponents](userId, 'write', cb); 540 | }, 541 | function (writeComponents, cb) { 542 | // remove subdocument from array 543 | var subdoc = array.id(id); 544 | if (!subdoc) { 545 | return cb(new Error('element with id ' + id + ' does not exist')); 546 | } 547 | // recursively check if obj can be set on the doc 548 | return checkObjectSchema( 549 | obj, array._schema.schema, subdoc, writeComponents, 550 | function (err) { 551 | if (err) return cb(err); 552 | cb(null, subdoc); 553 | } 554 | ); 555 | }, 556 | function (subdoc, cb) { 557 | // update subdocment 558 | subdoc.set(obj); 559 | cb(); 560 | } 561 | ], done); 562 | }; // authorizedArraySet 563 | }; 564 | }; 565 | -------------------------------------------------------------------------------- /test/componentsPlugin.js: -------------------------------------------------------------------------------- 1 | /* jshint expr: true */ 2 | 'use strict'; 3 | var mongoose = require('mongoose'); 4 | var erase = require('mongoose-erase'); 5 | var should = require('should'); 6 | var async = require('async'); 7 | var _ = require('lodash'); 8 | var crypto = require('crypto'); 9 | 10 | var utils = require('./utils'); 11 | var authorize = utils.authorize; 12 | 13 | describe('componentsPlugin', function () { 14 | 15 | // clear database before each run 16 | beforeEach(erase.connectAndErase(mongoose, utils.dbURI)); 17 | 18 | // define models 19 | beforeEach(function (done) { 20 | var getEmailComponent = function (doc, done) { 21 | return done(null, doc.visible ? 'contactVisible' : 'contactHidden'); 22 | }; 23 | var emailSchema = new mongoose.Schema({ 24 | address: {type: String, component: getEmailComponent}, 25 | type: {type: String, component: getEmailComponent}, 26 | visible: {type: Boolean, component: 'contactSettings'} 27 | }); 28 | 29 | var userSchema = new mongoose.Schema({ 30 | name: {type: String, component: 'info'}, 31 | passwordHash: {type: String}, 32 | birthday: {type: Date, component: 'info'}, 33 | emails: [emailSchema], 34 | settings: { 35 | rememberMe: {type: Boolean, component: 'settings'}, 36 | lightsaber: {type: String} 37 | }, 38 | father: {type: mongoose.Schema.Types.ObjectId, ref: 'User', component: 'info'}, 39 | siblings: { 40 | type: [{type: mongoose.Schema.Types.ObjectId, ref: 'User', component: 'info'}], 41 | component: 'info' 42 | }, 43 | tags: { 44 | type: [String], 45 | component: 'tags' 46 | }, 47 | complexTags: { 48 | type: [{ 49 | name: {type: String, component: 'tags'}, 50 | color: {type: String, component: 'tags'}, 51 | secret: String 52 | }], 53 | component: 'tags' 54 | } 55 | }); 56 | userSchema.plugin( 57 | authorize.componentsPlugin, 58 | { 59 | pathComponents: { 60 | 'emails': 'info', 61 | 'settings.lightsaber': 'info' 62 | }, 63 | permissions: { 64 | defaults: { 65 | read: ['info', 'contactVisible'] 66 | }, 67 | fromFun: function (doc, userId, action, done) { 68 | // user has full access to info and settings 69 | if (doc._id.equals(userId)) return done( 70 | null, 71 | ['info', 'settings', 'contactVisible', 'contactHidden', 72 | 'contactSettings', 'accountArray', 'tags'] 73 | ); 74 | // everyone has read access to info 75 | if (action === 'read') return done(null, ['info']); 76 | // everything else is denied 77 | done(null, []); 78 | }, 79 | } 80 | } 81 | ); 82 | // our users love gravatar, so we compute email hashes! 83 | userSchema.virtual('emailsMd5', {component: 'info'}).get(function () { 84 | return _.map(this.emails, function (email) { 85 | var md5 = crypto.createHash('md5'); 86 | md5.update(email.address.trim().toLowerCase()); 87 | return md5.digest('hex'); 88 | }); 89 | }); 90 | userSchema.plugin(authorize.permissionsPlugin, {userModel: 'User'}); 91 | mongoose.model('User', userSchema); 92 | 93 | // define Team 94 | var teamSchema = new mongoose.Schema({name: String}); 95 | teamSchema.plugin(authorize.teamPlugin); 96 | mongoose.model('Team', teamSchema); 97 | 98 | async.waterfall([ 99 | function createUsers (cb) { 100 | mongoose.model('User').create( 101 | { 102 | name: 'Luke', passwordHash: '0afb5c', 103 | settings: {rememberMe: true, lightsaber: 'blue'}, 104 | emails: [ 105 | {address: 'luke@skywalk.er', type: 'family', visible: true} 106 | ], 107 | complexTags: [{name: '+1', color: 'green', secret: 'topsecret'}] 108 | }, 109 | { 110 | name: 'Leia', passwordHash: 'caffee', 111 | settings: {rememberMe: true, lightsaber: 'blue'}, 112 | emails: [ 113 | {address: 'leia@skywalk.er', type: 'family', visible: false}, 114 | {address: 'leia@rebels.io', type: 'work', visible: true} 115 | ] 116 | }, 117 | { 118 | name: 'Darth', passwordHash: 'd4c18b', 119 | birthday: '2022-02-01T16:26:15.642Z', 120 | settings: {rememberMe: false, lightsaber: 'red'} 121 | }, 122 | cb 123 | ); 124 | }, 125 | function setFamily (luke, leia, darth, cb) { 126 | luke.father = darth; 127 | luke.siblings = [leia]; 128 | leia.father = darth; 129 | leia.siblings = [luke]; 130 | async.parallel(_.map([luke, leia], function (doc) { 131 | return function (cb) {doc.save(cb);}; 132 | }), cb); 133 | } 134 | ], done); 135 | }); 136 | 137 | // get the users as key-value pairs 138 | function getUsers(cb) { 139 | async.series({ 140 | // get luke 141 | luke: function (cb) { 142 | mongoose.model('User').findOne({name: 'Luke'}, cb); 143 | }, 144 | // get leia and populate everything 145 | leia: function (cb) { 146 | mongoose.model('User').findOne({name: 'Leia'}). 147 | populate('father siblings').exec(cb); 148 | }, 149 | // get darth and populate everything 150 | darth: function (cb) { 151 | mongoose.model('User').findOne({name: 'Darth'}, cb); 152 | } 153 | }, cb); 154 | } 155 | 156 | function getLukeForEveryone (docs) { 157 | return { 158 | _id: docs.luke._id.toString(), 159 | name: 'Luke', 160 | emails: [{address: 'luke@skywalk.er', type: 'family', 161 | _id: docs.luke.emails[0]._id.toString()}], 162 | father: docs.darth._id.toString(), 163 | settings: {lightsaber: 'blue'}, 164 | siblings: [docs.leia._id.toString()], 165 | }; 166 | } 167 | 168 | function getLukeForLuke (docs) { 169 | var luke = getLukeForEveryone(docs); 170 | luke.settings.rememberMe = true; 171 | luke.emails[0].visible = true; 172 | luke.tags = []; 173 | luke.complexTags = [{name: '+1', color: 'green', 174 | _id: docs.luke.complexTags[0]._id.toString()}]; 175 | return luke; 176 | } 177 | 178 | function getLeiaForEveryone (docs) { 179 | return { 180 | _id: docs.leia._id.toString(), 181 | name: 'Leia', 182 | settings: {lightsaber: 'blue'}, 183 | emails: [{address: 'leia@rebels.io', type: 'work', 184 | _id: docs.leia.emails[1]._id.toString()}], 185 | father: getDarthForEveryone(docs), 186 | siblings: [getLukeForEveryone(docs)], 187 | }; 188 | } 189 | 190 | function getLeiaForLeia (docs) { 191 | var leia = getLeiaForEveryone(docs); 192 | leia.settings.rememberMe = true; 193 | leia.emails = [ 194 | {address: 'leia@skywalk.er', type: 'family', 195 | _id: docs.leia.emails[0]._id.toString(), visible: false}, 196 | {address: 'leia@rebels.io', type: 'work', 197 | _id: docs.leia.emails[1]._id.toString(), visible: true} 198 | ]; 199 | leia.tags = []; 200 | leia.complexTags = []; 201 | return leia; 202 | } 203 | 204 | function getDarthForEveryone (docs) { 205 | return { 206 | _id: docs.darth._id.toString(), 207 | name: 'Darth', 208 | birthday: '2022-02-01T16:26:15.642Z', 209 | settings: {lightsaber: 'red'}, 210 | emails: [], 211 | siblings: [] 212 | }; 213 | } 214 | 215 | describe('#authorizedToObject', function () { 216 | 217 | describe('all documents', function () { 218 | 219 | it('should not return fields without component', function (done) { 220 | getUsers(function (err, docs) { 221 | async.series(_.map(docs, function (doc) { 222 | return function (cb) { 223 | doc.authorizedToObject(doc._id, function (err, obj) { 224 | should.not.exist(obj.passwordHash); 225 | cb(); 226 | }); 227 | }; 228 | }), done); 229 | }); 230 | }); 231 | }); // all docs 232 | 233 | describe('unpopulated document (luke)', function () { 234 | 235 | it('should return authorized fields for everyone', function (done) { 236 | getUsers(function (err, docs) { 237 | docs.luke.authorizedToObject(null, function (err, obj) { 238 | obj.should.eql(getLukeForEveryone(docs)); 239 | done(); 240 | }); 241 | }); 242 | }); 243 | 244 | it('should return authorized fields for luke', function (done) { 245 | getUsers(function (err, docs) { 246 | docs.luke.authorizedToObject(docs.luke._id, function (err, obj) { 247 | obj.should.eql(getLukeForLuke(docs)); 248 | done(); 249 | }); 250 | }); 251 | }); 252 | 253 | it('should return authorized getters for luke', function (done) { 254 | getUsers(function (err, docs) { 255 | docs.luke.authorizedToObject(docs.luke._id, {getters: true}, function (err, obj) { 256 | if (err) return done(err); 257 | var luke = getLukeForLuke(docs); 258 | luke.emailsMd5 = ['180caae72a7848552a5ba45cef614c0c']; 259 | obj.should.eql(luke); 260 | done(); 261 | }); 262 | }); 263 | }); 264 | }); // unpopulated doc 265 | 266 | describe('populated document (leia)', function () { 267 | 268 | it('should return authorized fields for everyone', function (done) { 269 | getUsers(function (err, docs) { 270 | docs.leia.authorizedToObject(null, function (err, obj) { 271 | obj.should.eql(getLeiaForEveryone(docs)); 272 | done(); 273 | }); 274 | }); 275 | }); 276 | 277 | it('should return authorized fields for leia', function (done) { 278 | getUsers(function (err, docs) { 279 | docs.leia.authorizedToObject(docs.leia._id, function (err, obj) { 280 | obj.should.eql(getLeiaForLeia(docs)); 281 | done(); 282 | }); 283 | }); 284 | }); 285 | 286 | it('should detect cycles of populated references', function (done) { 287 | getUsers(function (err, docs) { 288 | // leia -> luke -> leia is a cycle 289 | docs.leia.populate('siblings.0.siblings', function (err, leia) { 290 | docs.leia.authorizedToObject(docs.leia._id, function (err, obj) { 291 | // doc should look exactly like the 'unpopulated' doc above 292 | obj.should.eql(getLeiaForLeia(docs)); 293 | done(); 294 | }); 295 | }); 296 | }); 297 | }); 298 | }); // populated doc 299 | 300 | }); // #authorizedToObject 301 | 302 | describe('#authorizedSet', function () { 303 | 304 | function checkauthorizedSet (doc, userId, obj, done) { 305 | return doc.authorizedSet(userId, obj, function (err) { 306 | if (err) return done(err); 307 | return doc.save(done); 308 | }); 309 | } 310 | 311 | function checkauthorizedSetOverwrite (doc, userId, obj, done) { 312 | return doc.authorizedSet(userId, obj, {overwrite: true}, function (err) { 313 | if (err) return done(err); 314 | return doc.save(done); 315 | }); 316 | } 317 | 318 | describe('unpopulated document (luke)', function () { 319 | 320 | it('should update authorized fields', function (done) { 321 | getUsers(function (err, docs) { 322 | checkauthorizedSet( 323 | docs.luke, docs.luke._id, 324 | { 325 | name: 'Luke Skywalker', 326 | settings: {rememberMe: false}, 327 | tags: ['foo', 'bar'] 328 | }, 329 | function (err, luke) { 330 | if (err) return done(err); 331 | var obj = luke.toObject(); 332 | obj.settings.rememberMe.should.eql(false); 333 | obj.name.should.eql('Luke Skywalker'); 334 | obj.tags.should.eql(['foo', 'bar']); 335 | return done(); 336 | } 337 | ); 338 | }); 339 | }); 340 | 341 | it('should delete authorized fields via undefined', function (done) { 342 | getUsers(function (err, docs) { 343 | checkauthorizedSet( 344 | docs.luke, docs.luke._id, 345 | {name: undefined, settings: {rememberMe: undefined}}, 346 | function (err, luke) { 347 | if (err) return done(err); 348 | var obj = luke.toObject(); 349 | (obj.name === undefined).should.be.true; 350 | (obj.settings.rememberMe === undefined).should.be.true; 351 | return done(); 352 | } 353 | ); 354 | }); 355 | }); 356 | 357 | it('should overwrite doc (authorized fields)', function (done) { 358 | getUsers(function (err, docs) { 359 | var original = docs.luke.toObject(); 360 | checkauthorizedSetOverwrite( 361 | docs.luke, docs.luke._id, 362 | {name: 'Lucky Luke'}, 363 | function (err, luke) { 364 | if (err) return done(err); 365 | original.name = 'Lucky Luke'; 366 | delete original.father; 367 | delete original.tags; 368 | delete original.settings; 369 | delete original.siblings; 370 | original.should.eql(luke.toObject()); 371 | return done(); 372 | } 373 | ); 374 | }); 375 | }); 376 | 377 | it('should deny updating if user has no permissions', function (done) { 378 | getUsers(function (err, docs) { 379 | var original = docs.luke.toObject(); 380 | checkauthorizedSet( 381 | docs.luke, docs.leia._id, 382 | {name: 'Luke Skywalker', settings: {rememberMe: false}}, 383 | function (err, luke) { 384 | should(err).be.an.Error; 385 | original.should.eql(docs.luke.toObject()); 386 | return done(); 387 | } 388 | ); 389 | }); 390 | }); 391 | 392 | it('should deny updating an unauthorized field', function (done) { 393 | getUsers(function (err, docs) { 394 | var original = docs.luke.toObject(); 395 | checkauthorizedSet( 396 | docs.luke, docs.luke._id, {passwordHash: 'foo'}, 397 | function (err, luke) { 398 | should(err).be.an.Error; 399 | original.should.eql(docs.luke.toObject()); 400 | return done(); 401 | } 402 | ); 403 | }); 404 | }); 405 | 406 | it('should deny updating mixed authorized and unauthorized fields', 407 | function (done) { 408 | getUsers(function (err, docs) { 409 | var original = docs.luke.toObject(); 410 | checkauthorizedSet( 411 | docs.luke, docs.luke._id, 412 | {name: 'Luke Skywalker', _id: 'foo'}, 413 | function (err, luke) { 414 | should(err).be.an.Error; 415 | // check that document is unchanged 416 | original.should.eql(docs.luke.toObject()); 417 | return done(); 418 | } 419 | ); 420 | }); 421 | } 422 | ); 423 | 424 | it('should deny updating subdocuments in arrays via the parent doc', 425 | function (done) { 426 | getUsers(function (err, docs) { 427 | var original = docs.luke.toObject(); 428 | checkauthorizedSet( 429 | docs.luke, docs.luke._id, 430 | {emails: [{address: 'foo@bar.io', type: 'work', visible: true}]}, 431 | function (err, luke) { 432 | should(err).be.an.Error; 433 | // check that document is unchanged 434 | original.should.eql(docs.luke.toObject()); 435 | return done(); 436 | } 437 | ); 438 | }); 439 | } 440 | ); 441 | 442 | it('should deny updating subdocuments in arrays via the parent doc', 443 | function (done) { 444 | getUsers(function (err, docs) { 445 | var original = docs.luke.toObject(); 446 | checkauthorizedSet( 447 | docs.luke, docs.luke._id, 448 | {complexTags: [{name: '-1', color: 'red', secret: 'notsecret'}]}, 449 | function (err, luke) { 450 | should(err).be.an.Error; 451 | original.should.eql(docs.luke.toObject()); 452 | return done(); 453 | } 454 | ); 455 | }); 456 | } 457 | ); 458 | 459 | }); // unpopulated docs 460 | 461 | describe('populated document (leia)', function () { 462 | 463 | it('should update populated and authorized references', function (done) { 464 | getUsers(function (err, docs) { 465 | checkauthorizedSet( 466 | docs.leia, docs.leia._id, 467 | {father: docs.luke._id.toString()}, 468 | function (err, leia) { 469 | if (err) return done(err); 470 | should(docs.luke._id.equals(leia.father)).be.true; 471 | return done(); 472 | } 473 | ); 474 | }); 475 | }); 476 | 477 | it('should deny updating populated references', function (done) { 478 | getUsers(function (err, docs) { 479 | var original = docs.leia.toObject(); 480 | checkauthorizedSet( 481 | docs.leia, docs.leia._id, 482 | {father: {name: 'Darthy'}}, 483 | function (err, leia) { 484 | should(err).be.an.Error; 485 | // check that document is unchanged 486 | original.should.eql(docs.leia.toObject()); 487 | return done(); 488 | } 489 | ); 490 | }); 491 | }); 492 | 493 | }); // populated docs 494 | 495 | }); // authorizedSet 496 | 497 | describe('#authorizedArrayPush', function () { 498 | 499 | function checkauthorizedArrayPush (doc, obj, array, userId, done) { 500 | return doc.authorizedArrayPush(userId, array, obj, function (err) { 501 | if (err) return done(err); 502 | return doc.save(done); 503 | }); 504 | } 505 | 506 | describe('unpopulated document (luke)', function () { 507 | 508 | it('should push authorized subdocuments to an array', 509 | function (done) { 510 | getUsers(function (err, docs) { 511 | var original = docs.luke.toObject(); 512 | checkauthorizedArrayPush( 513 | docs.luke, {name: 'todo', color: 'red'}, docs.luke.complexTags, 514 | docs.luke._id, 515 | function (err, luke) { 516 | if (err) return done(err); 517 | luke.complexTags[1].name.should.eql('todo'); 518 | luke.complexTags[1].color.should.eql('red'); 519 | return done(); 520 | } 521 | ); 522 | }); 523 | } 524 | ); 525 | 526 | it('should deny pushing to an unauthorized array', 527 | function (done) { 528 | getUsers(function (err, docs) { 529 | var original = docs.luke.toObject(); 530 | checkauthorizedArrayPush( 531 | docs.luke, {name: 'todo', color: 'red', secret: 'boo'}, 532 | docs.luke.complexTags, docs.luke._id, 533 | function (err, luke) { 534 | should(err).be.an.Error; 535 | // check that document is unchanged 536 | original.should.eql(docs.luke.toObject()); 537 | return done(); 538 | } 539 | ); 540 | }); 541 | } 542 | ); 543 | 544 | it('should deny pushing to an authorized array with unauthorized data', 545 | function (done) { 546 | getUsers(function (err, docs) { 547 | var original = docs.luke.toObject(); 548 | checkauthorizedArrayPush( 549 | docs.luke, {address: 'foo@bar.io', type: 'work', visible: true}, 550 | docs.luke.emails, docs.luke._id, 551 | function (err, luke) { 552 | should(err).be.an.Error; 553 | // check that document is unchanged 554 | original.should.eql(docs.luke.toObject()); 555 | return done(); 556 | } 557 | ); 558 | }); 559 | } 560 | ); 561 | 562 | }); // unpopulated 563 | }); // authorizedArrayPush 564 | 565 | describe('#authorizedArrayRemove', function () { 566 | 567 | function checkauthorizedArrayRemove (doc, id, array, userId, done) { 568 | return doc.authorizedArrayRemove(userId, array, id, function (err) { 569 | if (err) return done(err); 570 | return doc.save(done); 571 | }); 572 | } 573 | 574 | describe('unpopulated document (luke)', function () { 575 | 576 | it('should remove subdocuments from an authorized array', 577 | function (done) { 578 | getUsers(function (err, docs) { 579 | var original = docs.luke.toObject(); 580 | checkauthorizedArrayRemove( 581 | docs.luke, docs.luke.complexTags[0]._id, docs.luke.complexTags, 582 | docs.luke._id, 583 | function (err, luke) { 584 | if (err) return done(err); 585 | docs.luke.toObject().complexTags.should.eql([]); 586 | return done(); 587 | } 588 | ); 589 | }); 590 | } 591 | ); 592 | 593 | it('should deny removing subdocuments from an unauthorized array', 594 | function (done) { 595 | getUsers(function (err, docs) { 596 | var original = docs.luke.toObject(); 597 | checkauthorizedArrayRemove( 598 | docs.luke, docs.luke.emails[0]._id, docs.luke.emails, 599 | docs.luke._id, 600 | function (err, luke) { 601 | should(err).be.an.Error; 602 | docs.luke.toObject().should.eql(original); 603 | return done(); 604 | } 605 | ); 606 | }); 607 | } 608 | ); 609 | 610 | it('should deny removing a non-existing subdocument from an array', 611 | function (done) { 612 | getUsers(function (err, docs) { 613 | var original = docs.luke.toObject(); 614 | checkauthorizedArrayRemove( 615 | docs.luke, 'nonexisting', docs.luke.complexTags, 616 | docs.luke._id, 617 | function (err, luke) { 618 | should(err).be.an.Error; 619 | docs.luke.toObject().should.eql(original); 620 | return done(); 621 | } 622 | ); 623 | }); 624 | } 625 | ); 626 | 627 | }); // unpopulated 628 | }); // authorizedArrayRemove 629 | 630 | describe('#authorizedArraySet', function () { 631 | 632 | function checkauthorizedArraySet (doc, id, obj, array, userId, done) { 633 | return doc.authorizedArraySet(userId, array, id, obj, function (err) { 634 | if (err) return done(err); 635 | return doc.save(done); 636 | }); 637 | } 638 | 639 | describe('unpopulated document (luke)', function () { 640 | 641 | it('should set subdocuments from an authorized array', 642 | function (done) { 643 | getUsers(function (err, docs) { 644 | var original = docs.luke.toObject(); 645 | checkauthorizedArraySet( 646 | docs.luke, docs.luke.complexTags[0]._id, 647 | {name: 'like'}, 648 | docs.luke.complexTags, 649 | docs.luke._id, 650 | function (err, luke) { 651 | if (err) return done(err); 652 | docs.luke.toObject().complexTags[0].name.should.eql('like'); 653 | return done(); 654 | } 655 | ); 656 | }); 657 | } 658 | ); 659 | 660 | it('should deny setting unauthorized fields in subdocuments', 661 | function (done) { 662 | getUsers(function (err, docs) { 663 | var original = docs.luke.toObject(); 664 | checkauthorizedArraySet( 665 | docs.luke, docs.luke.complexTags[0]._id, 666 | {secret: 'h4x0r'}, 667 | docs.luke.complexTags, 668 | docs.luke._id, 669 | function (err, luke) { 670 | should(err).be.an.Error; 671 | docs.luke.toObject().should.eql(original); 672 | return done(); 673 | } 674 | ); 675 | }); 676 | } 677 | ); 678 | 679 | }); // unpopulated 680 | }); // authorizedArraySet 681 | 682 | }); 683 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------