Skip to content

Commit

Permalink
Merge pull request TryGhost#120 from jgable/permissable
Browse files Browse the repository at this point in the history
Implement a permissable interface on models
  • Loading branch information
ErisDS committed Jun 9, 2013
2 parents c158191 + 8ae676e commit 6310326
Show file tree
Hide file tree
Showing 4 changed files with 180 additions and 43 deletions.
36 changes: 36 additions & 0 deletions core/shared/models/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
var Post,
Posts,
_ = require('underscore'),
when = require('when'),
Showdown = require('showdown'),
converter = new Showdown.converter(),
User = require('./user').User,
Expand Down Expand Up @@ -134,6 +135,41 @@
};
});
});
},

permissable: function (postModelOrId, userId, action_type, userPermissions) {
var self = this,
hasPermission,
postModel = postModelOrId;

// If we passed in an id instead of a model, get the model
// then check the permissions
if (_.isNumber(postModelOrId) || _.isString(postModelOrId)) {
return this.read({id: postModelOrId}).then(function (foundPostModel) {
return self.permissable(foundPostModel, userId, action_type, userPermissions);
});
}

// TODO: This logic is temporary, will probably need to be updated

hasPermission = _.any(userPermissions, function (perm) {
if (perm.get('object_type') !== 'post') {
return false;
}

// True, if no object_id specified, or it matches
return !perm.get('object_id') || perm.get('object_id') === postModel.id;
});

// If this is the author of the post, allow it.
hasPermission = hasPermission || userId === postModel.get('author_id');

if (hasPermission) {
return when.resolve();
}

// Otherwise, you shall not pass.
return when.reject();
}

});
Expand Down
65 changes: 42 additions & 23 deletions core/shared/permissions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
var _ = require('underscore'),
when = require('when'),
Models = require('../models'),
objectTypeModelMap = require('./objectTypeModelMap'),
UserProvider = Models.User,
PermissionsProvider = Models.Permission,
init,
Expand All @@ -20,12 +21,13 @@
this.userPermissionLoad = false;
};

CanThisResult.prototype.buildObjectTypeHandlers = function (obj_types, act_type) {
CanThisResult.prototype.buildObjectTypeHandlers = function (obj_types, act_type, userId) {
var self = this,
obj_type_handlers = {};

// Iterate through the object types, i.e. ['post', 'tag', 'user']
_.each(obj_types, function (obj_type) {
var TargetModel = objectTypeModelMap[obj_type];

// Create the 'handler' for the object type;
// the '.post()' in canThis(user).edit.post()
Expand All @@ -42,35 +44,51 @@

// Wait for the user loading to finish
return self.userPermissionLoad.then(function (userPermissions) {

// Iterate through the user permissions looking for an affirmation
var hasPermission = _.any(userPermissions, function (userPermission) {
var permObjId;
var hasPermission;

// Allow for a target model to implement a "Permissable" interface
if (TargetModel && _.isFunction(TargetModel.permissable)) {
return TargetModel.permissable(modelId, userId, act_type, userPermissions);
}

// Look for a matching action type and object type first
if (userPermission.get('action_type') !== act_type || userPermission.get('object_type') !== obj_type) {
return false;
}
// Otherwise, check all the permissions for matching object id
hasPermission = _.any(userPermissions, function (userPermission) {
var permObjId;

// Grab the object id (if specified, could be null)
permObjId = userPermission.get('object_id');
// Look for a matching action type and object type first
if (userPermission.get('action_type') !== act_type || userPermission.get('object_type') !== obj_type) {
return false;
}

// If we didn't specify a model (any thing)
// or the permission didn't have an id scope set
// then the user has permission
if (!modelId || !permObjId) {
return true;
}
// Grab the object id (if specified, could be null)
permObjId = userPermission.get('object_id');

// Otherwise, check if the id's match
// TODO: String vs Int comparison possibility here?
return modelId === permObjId;
});
// If we didn't specify a model (any thing)
// or the permission didn't have an id scope set
// then the user has permission
if (!modelId || !permObjId) {
return true;
}

// Otherwise, check if the id's match
// TODO: String vs Int comparison possibility here?
return modelId === permObjId;
});

if (hasPermission) {
return when.resolve();
}

return when.reject();
}).otherwise(function() {
// No permissions loaded, or error loading permissions

// Still check for permissable without permissions
if (TargetModel && _.isFunction(TargetModel.permissable)) {
return TargetModel.permissable(modelId, userId, act_type, []);
}

return when.reject();
});
};
Expand All @@ -80,20 +98,21 @@
};

CanThisResult.prototype.beginCheck = function (user) {
var self = this;
var self = this,
userId = user.id || user;

// TODO: Switch logic based on object type; user, role, post.

// Kick off the fetching of the user data
this.userPermissionLoad = UserProvider.effectivePermissions(user.id || user);
this.userPermissionLoad = UserProvider.effectivePermissions(userId);

// Iterate through the actions and their related object types
// We should have loaded these through a permissions.init() call previously
// TODO: Throw error if not init() yet?
_.each(exported.actionsMap, function (obj_types, act_type) {
// Build up the object type handlers;
// the '.post()' parts in canThis(user).edit.post()
var obj_type_handlers = self.buildObjectTypeHandlers(obj_types, act_type);
var obj_type_handlers = self.buildObjectTypeHandlers(obj_types, act_type, userId);

// Define a property for the action on the result;
// the '.edit' in canThis(user).edit.post()
Expand Down
11 changes: 11 additions & 0 deletions core/shared/permissions/objectTypeModelMap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
(function () {
"use strict";

module.exports = {
'post': require('../models/post').Post,
'role': require('../models/role').Role,
'user': require('../models/user').User,
'permission': require('../models/permission').Permission,
'setting': require('../models/setting').Setting
};
}());
111 changes: 91 additions & 20 deletions core/test/ghost/permissions_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
var _ = require("underscore"),
when = require('when'),
should = require('should'),
sinon = require('sinon'),
errors = require('../../shared/errorHandling'),
helpers = require('./helpers'),
permissions = require('../../shared/permissions'),
Models = require('../../shared/models'),
UserProvider = Models.User,
PermissionsProvider = Models.Permission;
PermissionsProvider = Models.Permission,
PostProvider = Models.Post;

describe('permissions', function () {

Expand All @@ -33,6 +35,21 @@
{ act: "remove", obj: "user" }
],
currTestPermId = 1,
currTestUserId = 1,
createTestUser = function (email_address) {
if (!email_address) {
currTestUserId += 1;
email_address = "test" + currTestPermId + "@test.com";
}

var newUser = {
id: currTestUserId,
email_address: email_address,
password: "testing123"
};

return UserProvider.add(newUser);
},
createPermission = function (name, act, obj) {
if (!name) {
currTestPermId += 1;
Expand Down Expand Up @@ -129,29 +146,33 @@
description: "test2 description"
});

testRole.save().then(function () {
return testRole.load('permissions');
}).then(function () {
var rolePermission = new Models.Permission({
name: "test edit posts",
action_type: 'edit',
object_type: 'post'
});
testRole.save()
.then(function () {
return testRole.load('permissions');
})
.then(function () {
var rolePermission = new Models.Permission({
name: "test edit posts",
action_type: 'edit',
object_type: 'post'
});

testRole.related('permissions').length.should.equal(0);
testRole.related('permissions').length.should.equal(0);

return rolePermission.save().then(function () {
return testRole.permissions().attach(rolePermission);
});
}).then(function () {
return Models.Role.read({id: testRole.id}, { withRelated: ['permissions']});
}).then(function (updatedRole) {
should.exist(updatedRole);
return rolePermission.save().then(function () {
return testRole.permissions().attach(rolePermission);
});
})
.then(function () {
return Models.Role.read({id: testRole.id}, { withRelated: ['permissions']});
})
.then(function (updatedRole) {
should.exist(updatedRole);

updatedRole.related('permissions').length.should.equal(1);
updatedRole.related('permissions').length.should.equal(1);

done();
});
done();
});
});

it('does not allow edit post without permission', function (done) {
Expand Down Expand Up @@ -221,6 +242,56 @@
});
});

it('can use permissable function on Model to allow something', function (done) {
var testUser,
permissableStub = sinon.stub(PostProvider, 'permissable', function () {
return when.resolve();
});

createTestUser()
.then(function (createdTestUser) {
testUser = createdTestUser;

return permissions.canThis(testUser).edit.post(123);
})
.then(function () {
permissableStub.restore();

permissableStub.calledWith(123, testUser.id, 'edit').should.equal(true);

done();
})
.otherwise(function () {
permissableStub.restore();
errors.logError(new Error("Did not allow testUser"));
});
});

it('can use permissable function on Model to forbid something', function (done) {
var testUser,
permissableStub = sinon.stub(PostProvider, 'permissable', function () {
return when.reject();
});

createTestUser()
.then(function (createdTestUser) {
testUser = createdTestUser;

return permissions.canThis(testUser).edit.post(123);
})
.then(function () {
permissableStub.restore();

errors.logError(new Error("Allowed testUser to edit post"));
})
.otherwise(function () {
permissableStub.restore();
permissableStub.calledWith(123, testUser.id, 'edit').should.equal(true);

done();
});
});

});

}());

0 comments on commit 6310326

Please sign in to comment.