Merge pull request #3319 from ErisDS/issue-3275

Extending context concept to models
This commit is contained in:
Hannah Wolfe 2014-07-19 00:13:19 +01:00
commit 67de186893
27 changed files with 297 additions and 303 deletions

View File

@ -146,7 +146,8 @@ authentication = {
},
setup: function (object) {
var setupUser;
var setupUser,
internal = {context: {internal: true}};
return utils.checkObject(object, 'setup').then(function (checkedSetupData) {
setupUser = {
@ -156,13 +157,14 @@ authentication = {
blogTitle: checkedSetupData.setup[0].blogTitle,
status: 'active'
};
return dataProvider.User.findAll();
}).then(function (users) {
if (users.length > 0) {
return dataProvider.User.setup(setupUser, {id: 1});
return dataProvider.User.findOne({role: 'Owner'});
}).then(function (ownerUser) {
if (ownerUser) {
return dataProvider.User.setup(setupUser, _.extend(internal, {id: ownerUser.id}));
} else {
// TODO: needs to pass owner role when role endpoint is finished!
return dataProvider.User.add(setupUser);
return dataProvider.User.add(setupUser, internal);
}
}).then(function (user) {
var userSettings = [];

View File

@ -23,8 +23,6 @@ function prepareInclude(include) {
return include;
}
/**
* ## Posts API Methods
*
@ -146,7 +144,7 @@ users = {
newUser = checkedUserData.users[0];
if (newUser.email) {
newUser.name = object.users[0].email.substring(0, newUser.email.indexOf("@"));
newUser.name = object.users[0].email.substring(0, newUser.email.indexOf('@'));
newUser.password = globalUtils.uid(50);
newUser.status = 'invited';
// TODO: match user role with db and enforce permissions

View File

@ -17,9 +17,9 @@ var when = require('when'),
// Private
logInfo,
to003,
fetchAdmin,
convertAdminToOwner,
createOwner,
options = {context: {internal: true}},
// Public
populate,
@ -30,21 +30,6 @@ logInfo = function logInfo(message) {
errors.logInfo('Migrations', message);
};
/**
* Fetch Admin
* Find the user with the admin role, who can be upgraded to an owner.
* @returns {Promise|*}
*/
fetchAdmin = function () {
return models.User.forge().fetch({
withRelated: [{
'roles': function (qb) {
qb.where('name', 'Administrator');
}
}]
});
};
/**
* Convert admin to Owner
* Changes an admin user to have the owner role
@ -53,7 +38,7 @@ fetchAdmin = function () {
convertAdminToOwner = function () {
var adminUser;
return fetchAdmin().then(function (user) {
return models.User.findOne({role: 'Administrator'}).then(function (user) {
adminUser = user;
return models.Role.findOne({name: 'Owner'});
}).then(function (ownerRole) {
@ -77,7 +62,7 @@ createOwner = function () {
user.password = utils.uid(50);
logInfo('Creating owner');
return models.User.add(user);
return models.User.add(user, options);
});
};
@ -92,36 +77,38 @@ populate = function () {
logInfo('Populating fixtures');
_.each(fixtures.posts, function (post) {
ops.push(function () { return Post.add(post); });
ops.push(Post.add(post, options));
});
_.each(fixtures.tags, function (tag) {
ops.push(function () { return Tag.add(tag); });
ops.push(Tag.add(tag, options));
});
_.each(fixtures.roles, function (role) {
ops.push(function () { return Role.add(role); });
ops.push(Role.add(role, options));
});
_.each(fixtures.clients, function (client) {
ops.push(function () { return Client.add(client); });
ops.push(Client.add(client, options));
});
// add the tag to the post
relations.push(function () {
return Post.forge({slug: fixtures.posts[0].slug}).fetch({withRelated: ['tags']}).then(function (post) {
return Post.forge({slug: fixtures.posts[0].slug}).fetch().then(function (post) {
return Tag.forge({slug: fixtures.tags[0].slug}).fetch().then(function (tag) {
return post.tags().attach(tag);
return post.related('tags').attach(tag.id);
});
});
});
return sequence(ops).then(function () {
return when.all(ops).then(function () {
return sequence(relations);
}).then(function () {
return permissions.populate();
return permissions.populate(options);
}).then(function () {
return createOwner();
}).catch(function (errs) {
errors.logError(errs);
});
};
@ -139,12 +126,14 @@ to003 = function () {
Role = models.Role,
Client = models.Client;
logInfo('Upgrading fixtures');
// Add the client fixture if missing
upgradeOp = Client.findOne({secret: fixtures.clients[0].secret}).then(function (client) {
if (!client) {
logInfo('Adding client fixture');
_.each(fixtures.clients, function (client) {
return Client.add(client);
return Client.add(client, options);
});
}
});
@ -155,14 +144,14 @@ to003 = function () {
if (!owner) {
logInfo('Adding owner role fixture');
_.each(fixtures.roles.slice(3), function (role) {
return Role.add(role);
return Role.add(role, options);
});
}
});
ops.push(upgradeOp);
return when.all(ops).then(function () {
return permissions.to003();
return permissions.to003(options);
}).then(function () {
return convertAdminToOwner();
});

View File

@ -56,13 +56,13 @@ addAllRolesPermissions = function () {
};
addAllPermissions = function () {
addAllPermissions = function (options) {
var ops = [];
_.each(fixtures.permissions, function (permissions, object_type) {
_.each(permissions, function (permission) {
ops.push(function () {
permission.object_type = object_type;
return models.Permission.add(permission);
return models.Permission.add(permission, options);
});
});
});
@ -71,11 +71,10 @@ addAllPermissions = function () {
};
// ## Populate
populate = function () {
populate = function (options) {
logInfo('Populating permissions');
// ### Ensure all permissions are added
return addAllPermissions().then(function () {
return addAllPermissions(options).then(function () {
// ### Ensure all roles_permissions are added
return addAllRolesPermissions();
});
@ -84,7 +83,7 @@ populate = function () {
// ## Update
// Update permissions to 003
// Need to rename old permissions, and then add all of the missing ones
to003 = function () {
to003 = function (options) {
var ops = [];
logInfo('Upgrading permissions');
@ -102,7 +101,7 @@ to003 = function () {
// Now we can perfom the normal populate
return when.all(ops).then(function () {
return populate();
return populate(options);
});
};

View File

@ -2,14 +2,14 @@ var when = require('when'),
_ = require('lodash'),
models = require('../../models'),
Importer000,
updatedSettingKeys;
updatedSettingKeys,
internal = {context: {internal: true}};
updatedSettingKeys = {
activePlugins: 'activeApps',
installedPlugins: 'installedApps'
};
Importer000 = function () {
_.bindAll(this, 'basicImport');
@ -90,7 +90,7 @@ function importTags(ops, tableData, transaction) {
_.each(tableData, function (tag) {
ops.push(models.Tag.findOne({name: tag.name}, {transacting: transaction}).then(function (_tag) {
if (!_tag) {
return models.Tag.add(tag, {user: 1, transacting: transaction})
return models.Tag.add(tag, _.extend(internal, {transacting: transaction}))
// add pass-through error handling so that bluebird doesn't think we've dropped it
.otherwise(function (error) { return when.reject(error); });
}
@ -102,7 +102,7 @@ function importTags(ops, tableData, transaction) {
function importPosts(ops, tableData, transaction) {
tableData = stripProperties(['id'], tableData);
_.each(tableData, function (post) {
ops.push(models.Post.add(post, {user: 1, transacting: transaction, importing: true})
ops.push(models.Post.add(post, _.extend(internal, {transacting: transaction, importing: true}))
// add pass-through error handling so that bluebird doesn't think we've dropped it
.otherwise(function (error) { return when.reject(error); }));
});
@ -112,7 +112,7 @@ function importUsers(ops, tableData, transaction) {
// don't override the users credentials
tableData = stripProperties(['id', 'email', 'password'], tableData);
tableData[0].id = 1;
ops.push(models.User.edit(tableData[0], {id: 1, user: 1, transacting: transaction})
ops.push(models.User.edit(tableData[0], _.extend(internal, {id: 1, transacting: transaction}))
// add pass-through error handling so that bluebird doesn't think we've dropped it
.otherwise(function (error) { return when.reject(error); }));
}
@ -133,7 +133,7 @@ function importSettings(ops, tableData, transaction) {
datum.key = updatedSettingKeys[datum.key] || datum.key;
});
ops.push(models.Settings.edit(tableData, {user: 1, transacting: transaction})
ops.push(models.Settings.edit(tableData, _.extend(internal, {transacting: transaction}))
// add pass-through error handling so that bluebird doesn't think we've dropped it
.otherwise(function (error) { return when.reject(error); }));
}
@ -144,7 +144,7 @@ function importApps(ops, tableData, transaction) {
// Avoid duplicates
ops.push(models.App.findOne({name: app.name}, {transacting: transaction}).then(function (_app) {
if (!_app) {
return models.App.add(app, {transacting: transaction})
return models.App.add(app, _.extend(internal, {transacting: transaction}))
// add pass-through error handling so that bluebird doesn't think we've dropped it
.otherwise(function (error) { return when.reject(error); });
}

View File

@ -83,14 +83,18 @@ errors = {
},
logError: function (err, context, help) {
if (_.isArray(err)) {
_.each(err, function (e) {
errors.logError(e);
});
return;
}
var stack = err ? err.stack : null,
msgs;
if (err) {
err = err.message || err || 'An unknown error occurred.';
} else {
err = 'An unknown error occurred.';
}
err = _.isString(err) ? err : (_.isObject(err) ? err.message : 'An unknown error occurred.');
// TODO: Logging framework hookup
// Eventually we'll have better logging which will know about envs
if ((process.env.NODE_ENV === 'development' ||
@ -130,6 +134,12 @@ errors = {
this.throwError(err, context, help);
},
logAndRejectError: function (err, context, help) {
this.logError(err, context, help);
this.rejectError(err, context, help);
},
logErrorWithRedirect: function (msg, context, help, redirectTo, req, res) {
/*jshint unused:false*/
var self = this;

View File

@ -15,6 +15,7 @@ var bookshelf = require('bookshelf'),
sanitize = require('validator').sanitize,
schema = require('../data/schema'),
validation = require('../data/validation'),
errors = require('../errors'),
ghostBookshelf;
@ -64,20 +65,18 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
},
creating: function (newObj, attr, options) {
var user = options.context && options.context.user ? options.context.user : 1;
if (!this.get('created_by')) {
this.set('created_by', user);
this.set('created_by', this.contextUser(options));
}
},
saving: function (newObj, attr, options) {
var user = options.context && options.context.user ? options.context.user : 1;
// Remove any properties which don't belong on the model
this.attributes = this.pick(this.permittedAttributes());
// Store the previous attributes so we can tell what was updated later
this._updatedAttributes = newObj.previousAttributes();
this.set('updated_by', user);
this.set('updated_by', this.contextUser(options));
},
// Base prototype properties will go here
@ -99,7 +98,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
fixBools: function (attrs) {
var self = this;
_.each(attrs, function (value, key) {
if (schema.tables[self.tableName][key].type === "bool") {
if (schema.tables[self.tableName][key].type === 'bool') {
attrs[key] = value ? true : false;
}
});
@ -107,6 +106,19 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
return attrs;
},
// Get the user from the options object
contextUser: function (options) {
// Default to context user
if (options.context && options.context.user) {
return options.context.user;
// Other wise use the internal override
} else if (options.context && options.context.internal) {
return 1;
} else {
errors.logAndThrowError(new Error('missing context'));
}
},
// format date before writing to DB, bools work
format: function (attrs) {
return this.fixDates(attrs);
@ -174,7 +186,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
*/
permittedOptions: function () {
// terms to whitelist for all methods.
return ['include', 'transacting'];
return ['context', 'include', 'transacting'];
},
/**

View File

@ -5,9 +5,7 @@ var ghostBookshelf = require('./base'),
Client = ghostBookshelf.Model.extend({
tableName: 'clients'
});
Clients = ghostBookshelf.Collection.extend({

View File

@ -18,27 +18,6 @@ Permission = ghostBookshelf.Model.extend({
apps: function () {
return this.belongsToMany('App');
}
}, {
/**
* Returns an array of keys permitted in a method's `options` hash, depending on the current method.
* @param {String} methodName The name of the method to check valid options for.
* @return {Array} Keys allowed in the `options` hash of the model's method.
*/
permittedOptions: function (methodName) {
var options = ghostBookshelf.Model.permittedOptions(),
// whitelists for the `options` hash argument on methods, by method name.
// these are the only options that can be passed to Bookshelf / Knex.
validOptions = {
add: ['user']
};
if (validOptions[methodName]) {
options = options.concat(validOptions[methodName]);
}
return options;
}
});
Permissions = ghostBookshelf.Collection.extend({

View File

@ -42,8 +42,7 @@ Post = ghostBookshelf.Model.extend({
/*jshint unused:false*/
var self = this,
tagsToCheck,
i,
user = options.context && options.context.user ? options.context.user : 1;
i;
options = options || {};
// keep tags for 'saved' event and deduplicate upper/lowercase tags
@ -73,7 +72,7 @@ Post = ghostBookshelf.Model.extend({
this.set('published_at', new Date());
}
// This will need to go elsewhere in the API layer.
this.set('published_by', user);
this.set('published_by', this.contextUser(options));
}
if (this.hasChanged('slug') || !this.get('slug')) {
@ -91,11 +90,9 @@ Post = ghostBookshelf.Model.extend({
/*jshint unused:false*/
options = options || {};
var user = options.context && options.context.user ? options.context.user : 1;
// set any dynamic default properties
if (!this.get('author_id')) {
this.set('author_id', user);
this.set('author_id', this.contextUser(options));
}
ghostBookshelf.Model.prototype.creating.call(this, newPage, attr, options);
@ -213,10 +210,9 @@ Post = ghostBookshelf.Model.extend({
// these are the only options that can be passed to Bookshelf / Knex.
validOptions = {
findAll: ['withRelated'],
findOne: ['user', 'importing', 'withRelated'],
findOne: ['importing', 'withRelated'],
findPage: ['page', 'limit', 'status', 'staticPages'],
add: ['user', 'importing'],
edit: ['user']
add: ['importing']
};
if (validOptions[methodName]) {

View File

@ -26,8 +26,7 @@ Role = ghostBookshelf.Model.extend({
// whitelists for the `options` hash argument on methods, by method name.
// these are the only options that can be passed to Bookshelf / Knex.
validOptions = {
findOne: ['withRelated'],
add: ['user']
findOne: ['withRelated']
};
if (validOptions[methodName]) {

View File

@ -5,6 +5,7 @@ var Settings,
errors = require('../errors'),
when = require('when'),
validation = require('../data/validation'),
internal = {context: {internal: true}},
defaultSettings;
@ -75,28 +76,6 @@ Settings = ghostBookshelf.Model.extend({
}
}, {
/**
* Returns an array of keys permitted in a method's `options` hash, depending on the current method.
* @param {String} methodName The name of the method to check valid options for.
* @return {Array} Keys allowed in the `options` hash of the model's method.
*/
permittedOptions: function (methodName) {
var options = ghostBookshelf.Model.permittedOptions(),
// whitelists for the `options` hash argument on methods, by method name.
// these are the only options that can be passed to Bookshelf / Knex.
validOptions = {
add: ['user'],
edit: ['user']
};
if (validOptions[methodName]) {
options = options.concat(validOptions[methodName]);
}
return options;
},
findOne: function (options) {
// Allow for just passing the key instead of attributes
if (!_.isObject(options)) {
@ -151,7 +130,7 @@ Settings = ghostBookshelf.Model.extend({
var defaultSetting = _.clone(getDefaultSettings()[key]);
defaultSetting.value = defaultSetting.defaultValue;
return Settings.forge(defaultSetting).save(null, {user: 1});
return Settings.forge(defaultSetting).save(null, internal);
});
},
@ -168,7 +147,7 @@ Settings = ghostBookshelf.Model.extend({
}
if (isMissingFromDB) {
defaultSetting.value = defaultSetting.defaultValue;
insertOperations.push(Settings.forge(defaultSetting).save(null, {user: 1}));
insertOperations.push(Settings.forge(defaultSetting).save(null, internal));
}
});

View File

@ -36,27 +36,6 @@ Tag = ghostBookshelf.Model.extend({
return attrs;
}
}, {
/**
* Returns an array of keys permitted in a method's `options` hash, depending on the current method.
* @param {String} methodName The name of the method to check valid options for.
* @return {Array} Keys allowed in the `options` hash of the model's method.
*/
permittedOptions: function (methodName) {
var options = ghostBookshelf.Model.permittedOptions(),
// whitelists for the `options` hash argument on methods, by method name.
// these are the only options that can be passed to Bookshelf / Knex.
validOptions = {
add: ['user']
};
if (validOptions[methodName]) {
options = options.concat(validOptions[methodName]);
}
return options;
}
});
Tags = ghostBookshelf.Collection.extend({

View File

@ -58,6 +58,22 @@ User = ghostBookshelf.Model.extend({
}
},
// Get the user from the options object
contextUser: function (options) {
// Default to context user
if (options.context && options.context.user) {
return options.context.user;
// Other wise use the internal override
} else if (options.context && options.context.internal) {
return 1;
// This is the user object, so try using this user's id
} else if (this.get('id')) {
return this.get('id');
} else {
errors.logAndThrowError(new Error('missing context'));
}
},
toJSON: function (options) {
var attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options);
// remove password hash for security reasons
@ -92,9 +108,8 @@ User = ghostBookshelf.Model.extend({
validOptions = {
findOne: ['withRelated'],
findAll: ['withRelated'],
add: ['user'],
setup: ['user', 'id'],
edit: ['user', 'withRelated', 'id']
setup: ['id'],
edit: ['withRelated', 'id']
};
if (validOptions[methodName]) {
@ -125,6 +140,16 @@ User = ghostBookshelf.Model.extend({
options = options || {};
options.withRelated = _.union([ 'roles' ], options.include);
// Support finding by role
if (data.role) {
options.withRelated = [{
'roles': function (qb) {
qb.where('name', data.role);
}
}];
delete data.role;
}
return ghostBookshelf.Model.findOne.call(this, data, options);
},
@ -340,7 +365,7 @@ User = ghostBookshelf.Model.extend({
}
var hash = crypto.createHash('sha256'),
text = "";
text = '';
// Token:
// BASE64(TIMESTAMP + email + HASH(TIMESTAMP + email + oldPasswordHash + dbHash ))

View File

@ -33,6 +33,7 @@ var crypto = require('crypto'),
errors = require('./errors'),
packageInfo = require('../../package.json'),
internal = {context: {internal: true}},
allowedCheckEnvironments = ['development', 'production'],
checkEndpoint = 'updates.ghost.org',
currentVersion = packageInfo.version;
@ -40,8 +41,8 @@ var crypto = require('crypto'),
function updateCheckError(error) {
errors.logError(
error,
"Checking for updates failed, your blog will continue to function.",
"If you get this error repeatedly, please seek help from https://ghost.org/forum."
'Checking for updates failed, your blog will continue to function.',
'If you get this error repeatedly, please seek help from https://ghost.org/forum.'
);
}
@ -50,9 +51,9 @@ function updateCheckData() {
ops = [],
mailConfig = config().mail;
ops.push(api.settings.read({context: {internal: true}, key: 'dbHash'}).otherwise(errors.rejectError));
ops.push(api.settings.read({context: {internal: true}, key: 'activeTheme'}).otherwise(errors.rejectError));
ops.push(api.settings.read({context: {internal: true}, key: 'activeApps'})
ops.push(api.settings.read(_.extend(internal, {key: 'dbHash'})).otherwise(errors.rejectError));
ops.push(api.settings.read(_.extend(internal, {key: 'activeTheme'})).otherwise(errors.rejectError));
ops.push(api.settings.read(_.extend(internal, {key: 'activeApps'}))
.then(function (response) {
var apps = response.settings[0];
try {
@ -64,7 +65,7 @@ function updateCheckData() {
return _.reduce(apps, function (memo, item) { return memo === '' ? memo + item : memo + ', ' + item; }, '');
}).otherwise(errors.rejectError));
ops.push(api.posts.browse().otherwise(errors.rejectError));
ops.push(api.users.browse({context: {user: 1}}).otherwise(errors.rejectError));
ops.push(api.users.browse(internal).otherwise(errors.rejectError));
ops.push(nodefn.call(exec, 'npm -v').otherwise(errors.rejectError));
data.ghost_version = currentVersion;
@ -142,18 +143,17 @@ function updateCheckRequest() {
// 1. Updates the time we can next make a check
// 2. Checks if the version in the response is new, and updates the notification setting
function updateCheckResponse(response) {
var ops = [],
internalContext = {context: {internal: true}};
var ops = [];
ops.push(
api.settings.edit(
{settings: [{key: 'nextUpdateCheck', value: response.next_check}]},
internalContext
internal
)
.otherwise(errors.rejectError),
api.settings.edit(
{settings: [{key: 'displayUpdateNotification', value: response.version}]},
internalContext
internal
)
.otherwise(errors.rejectError)
);
@ -179,7 +179,7 @@ function updateCheck() {
// No update check
deferred.resolve();
} else {
api.settings.read({context: {internal: true}, key: 'nextUpdateCheck'}).then(function (result) {
api.settings.read(_.extend(internal, {key: 'nextUpdateCheck'})).then(function (result) {
var nextUpdateCheck = result.settings[0];
if (nextUpdateCheck && nextUpdateCheck.value && nextUpdateCheck.value > moment().unix()) {
@ -199,7 +199,7 @@ function updateCheck() {
}
function showUpdateNotification() {
return api.settings.read({context: {internal: true}, key: 'displayUpdateNotification'}).then(function (response) {
return api.settings.read(_.extend(internal, {key: 'displayUpdateNotification'})).then(function (response) {
var display = response.settings[0];
// Version 0.4 used boolean to indicate the need for an update. This special case is

View File

@ -38,7 +38,7 @@ describe('DB API', function () {
it('delete all content', function (done) {
var options = {context: {user: 1}};
permissions.init().then(function () {
return dbAPI.deleteAllContent({context: {user: 1}});
return dbAPI.deleteAllContent(options);
}).then(function (result) {
should.exist(result.db);
result.db.should.be.instanceof(Array);

View File

@ -159,7 +159,7 @@ describe('Notifications API', function () {
NotificationsAPI.add({ notifications: [msg] }, {context: {internal: true}}).then(function (result) {
var notification = result.notifications[0];
NotificationsAPI.destroy({ id: notification.id, context: {user: 1}}).then(function (result) {
NotificationsAPI.destroy({id: notification.id, context: {user: 1}}).then(function (result) {
should.exist(result);
should.exist(result.notifications);
result.notifications[0].id.should.equal(notification.id);

View File

@ -1,10 +1,10 @@
/*globals describe, before, beforeEach, afterEach, it*/
/*globals describe, before, beforeEach, afterEach, after, it*/
var testUtils = require('../../utils'),
should = require('should'),
_ = require("lodash"),
// Stuff we are testing
Models = require('../../../server/models');
Models = require('../../../server/models'),
context = {context: {user: 1}};
describe('App Fields Model', function () {
@ -63,13 +63,13 @@ describe('App Fields Model', function () {
AppFieldsModel.findOne({id: 1}).then(function (foundAppField) {
should.exist(foundAppField);
return foundAppField.set({value: "350"}).save();
return foundAppField.set({value: '350'}).save(null, context);
}).then(function () {
return AppFieldsModel.findOne({id: 1});
}).then(function (updatedAppField) {
should.exist(updatedAppField);
updatedAppField.get("value").should.equal("350");
updatedAppField.get('value').should.equal('350');
done();
}).catch(done);

View File

@ -1,10 +1,10 @@
/*globals describe, before, beforeEach, afterEach, it*/
/*globals describe, before, beforeEach, afterEach, after, it*/
var testUtils = require('../../utils'),
should = require('should'),
_ = require("lodash"),
// Stuff we are testing
Models = require('../../../server/models');
Models = require('../../../server/models'),
context = {context: {user: 1}};
describe('App Setting Model', function () {
@ -63,13 +63,13 @@ describe('App Setting Model', function () {
AppSettingModel.findOne({id: 1}).then(function (foundAppSetting) {
should.exist(foundAppSetting);
return foundAppSetting.set({value: "350"}).save();
return foundAppSetting.set({value: '350'}).save(null, context);
}).then(function () {
return AppSettingModel.findOne({id: 1});
}).then(function (updatedAppSetting) {
should.exist(updatedAppSetting);
updatedAppSetting.get("value").should.equal("350");
updatedAppSetting.get('value').should.equal('350');
done();
}).catch(done);

View File

@ -1,11 +1,12 @@
/*globals describe, before, beforeEach, afterEach, it*/
/*globals describe, before, beforeEach, afterEach, after, it*/
var testUtils = require('../../utils'),
sequence = require('when/sequence'),
should = require('should'),
_ = require("lodash"),
_ = require('lodash'),
// Stuff we are testing
Models = require('../../../server/models');
Models = require('../../../server/models'),
context = {context: {user: 1}};
describe('App Model', function () {
@ -64,7 +65,7 @@ describe('App Model', function () {
AppModel.findOne({id: 1}).then(function (foundApp) {
should.exist(foundApp);
return foundApp.set({name: 'New App'}).save();
return foundApp.set({name: 'New App'}).save(null, context);
}).then(function () {
return AppModel.findOne({id: 1});
}).then(function (updatedApp) {
@ -79,7 +80,7 @@ describe('App Model', function () {
it('can add', function (done) {
var newApp = testUtils.DataGenerator.forKnex.createApp(testUtils.DataGenerator.Content.apps[1]);
AppModel.add(newApp).then(function (createdApp) {
AppModel.add(newApp, context).then(function (createdApp) {
should.exist(createdApp);
createdApp.attributes.name.should.equal(newApp.name);
@ -115,7 +116,7 @@ describe('App Model', function () {
name: 'Kudos ' + i,
version: '0.0.1',
status: 'installed'
}, {user: 1});
}, context);
};
})).then(function (createdApps) {
// Should have created 12 apps

View File

@ -1,10 +1,10 @@
/*globals describe, it, before, beforeEach, afterEach */
var testUtils = require('../../utils'),
should = require('should'),
errors = require('../../../server/errors'),
// Stuff we are testing
Models = require('../../../server/models');
Models = require('../../../server/models'),
context = {context: {user: 1}};
describe('Permission Model', function () {
@ -53,13 +53,13 @@ describe('Permission Model', function () {
PermissionModel.findOne({id: 1}).then(function (foundPermission) {
should.exist(foundPermission);
return foundPermission.set({name: "updated"}).save();
return foundPermission.set({name: 'updated'}).save(null, context);
}).then(function () {
return PermissionModel.findOne({id: 1});
}).then(function (updatedPermission) {
should.exist(updatedPermission);
updatedPermission.get("name").should.equal("updated");
updatedPermission.get('name').should.equal('updated');
done();
}).catch(done);
@ -72,7 +72,7 @@ describe('Permission Model', function () {
action_type: 'test'
};
PermissionModel.add(newPerm, {user: 1}).then(function (createdPerm) {
PermissionModel.add(newPerm, context).then(function (createdPerm) {
should.exist(createdPerm);
createdPerm.attributes.name.should.equal(newPerm.name);

View File

@ -2,12 +2,12 @@
var testUtils = require('../../utils'),
should = require('should'),
_ = require('lodash'),
when = require('when'),
sequence = require('when/sequence'),
// Stuff we are testing
Models = require('../../../server/models'),
DataGenerator = testUtils.DataGenerator;
DataGenerator = testUtils.DataGenerator,
context = {context: {user: 1}};
describe('Post Model', function () {
@ -152,7 +152,7 @@ describe('Post Model', function () {
post.id.should.equal(firstPost);
post.title.should.not.equal('new title');
return PostModel.edit({title: 'new title'}, {id: firstPost});
return PostModel.edit({title: 'new title'}, _.extend(context, {id: firstPost}));
}).then(function (edited) {
should.exist(edited);
edited.attributes.title.should.equal('new title');
@ -167,7 +167,7 @@ describe('Post Model', function () {
newPost = testUtils.DataGenerator.forModel.posts[2],
newPostDB = testUtils.DataGenerator.Content.posts[2];
PostModel.add(newPost, {user: 1}).then(function (createdPost) {
PostModel.add(newPost, context).then(function (createdPost) {
return new PostModel({id: createdPost.id}).fetch();
}).then(function (createdPost) {
should.exist(createdPost);
@ -199,7 +199,7 @@ describe('Post Model', function () {
createdPostUpdatedDate = createdPost.get('updated_at');
// Set the status to published to check that `published_at` is set.
return createdPost.save({status: 'published'}, {user: 1});
return createdPost.save({status: 'published'}, context);
}).then(function (publishedPost) {
publishedPost.get('published_at').should.be.instanceOf(Date);
publishedPost.get('published_by').should.equal(1);
@ -220,7 +220,7 @@ describe('Post Model', function () {
published_at: previousPublishedAtDate,
title: 'published_at test',
markdown: 'This is some content'
}, {user: 1}).then(function (newPost) {
}, context).then(function (newPost) {
should.exist(newPost);
new Date(newPost.get('published_at')).getTime().should.equal(previousPublishedAtDate.getTime());
@ -238,13 +238,13 @@ describe('Post Model', function () {
markdown: 'Test Content'
};
PostModel.add(newPost, {user: 1}).then(function (createdPost) {
PostModel.add(newPost, context).then(function (createdPost) {
return new PostModel({ id: createdPost.id }).fetch();
}).then(function (createdPost) {
should.exist(createdPost);
createdPost.get('title').should.equal(untrimmedCreateTitle.trim());
return createdPost.save({ title: untrimmedUpdateTitle });
return createdPost.save({ title: untrimmedUpdateTitle }, context);
}).then(function (updatedPost) {
updatedPost.get('title').should.equal(untrimmedUpdateTitle.trim());
@ -259,7 +259,7 @@ describe('Post Model', function () {
return PostModel.add({
title: 'Test Title',
markdown: 'Test Content ' + (i+1)
}, {user: 1});
}, context);
};
})).then(function (createdPosts) {
// Should have created 12 posts
@ -289,7 +289,7 @@ describe('Post Model', function () {
markdown: 'Test Content 1'
};
PostModel.add(newPost, {user: 1}).then(function (createdPost) {
PostModel.add(newPost, context).then(function (createdPost) {
createdPost.get('slug').should.equal('apprehensive-titles-have-too-many-spaces-and-m-dashes-and-also-n-dashes');
@ -303,7 +303,7 @@ describe('Post Model', function () {
markdown: 'Test Content 1'
};
PostModel.add(newPost, {user: 1}).then(function (createdPost) {
PostModel.add(newPost, context).then(function (createdPost) {
createdPost.get('slug').should.not.equal('rss');
done();
});
@ -315,7 +315,7 @@ describe('Post Model', function () {
markdown: 'Test Content 1'
};
PostModel.add(newPost, {user: 1}).then(function (createdPost) {
PostModel.add(newPost, context).then(function (createdPost) {
createdPost.get('slug').should.equal('bhute-dhddkii-bhrvnnaaraa-aahet');
done();
}).catch(done);
@ -332,13 +332,13 @@ describe('Post Model', function () {
};
// Create the first post
PostModel.add(firstPost, {user: 1})
PostModel.add(firstPost, context)
.then(function (createdFirstPost) {
// Store the slug for later
firstPost.slug = createdFirstPost.get('slug');
// Create the second post
return PostModel.add(secondPost, {user: 1});
return PostModel.add(secondPost, context);
}).then(function (createdSecondPost) {
// Store the slug for comparison later
secondPost.slug = createdSecondPost.get('slug');
@ -346,7 +346,7 @@ describe('Post Model', function () {
// Update with a conflicting slug from the first post
return createdSecondPost.save({
slug: firstPost.slug
});
}, context);
}).then(function (updatedSecondPost) {
// Should have updated from original

View File

@ -3,7 +3,8 @@ var testUtils = require('../../utils'),
should = require('should'),
// Stuff we are testing
Models = require('../../../server/models');
Models = require('../../../server/models'),
context = {context: {user: 1}};
describe('Role Model', function () {
@ -52,7 +53,7 @@ describe('Role Model', function () {
RoleModel.findOne({id: 1}).then(function (foundRole) {
should.exist(foundRole);
return foundRole.set({name: 'updated'}).save();
return foundRole.set({name: 'updated'}).save(null, context);
}).then(function () {
return RoleModel.findOne({id: 1});
}).then(function (updatedRole) {
@ -70,7 +71,7 @@ describe('Role Model', function () {
description: 'test1 description'
};
RoleModel.add(newRole, {user: 1}).then(function (createdRole) {
RoleModel.add(newRole, context).then(function (createdRole) {
should.exist(createdRole);
createdRole.attributes.name.should.equal(newRole.name);

View File

@ -1,11 +1,11 @@
/*globals describe, before, beforeEach, afterEach, it*/
/*globals describe, before, beforeEach, afterEach, after, it*/
var testUtils = require('../../utils'),
should = require('should'),
_ = require("lodash"),
// Stuff we are testing
Models = require('../../../server/models'),
config = require('../../../server/config');
config = require('../../../server/config'),
context = {context: {user: 1}};
describe('Settings Model', function () {
@ -81,7 +81,7 @@ describe('Settings Model', function () {
results.length.should.be.above(0);
return SettingsModel.edit({key: "description", value: "new value"});
return SettingsModel.edit({key: 'description', value: 'new value'}, context);
}).then(function (edited) {
@ -110,10 +110,10 @@ describe('Settings Model', function () {
results.length.should.be.above(0);
model1 = {key: "description", value: "another new value"};
model2 = {key: "title", value: "new title"};
model1 = {key: 'description', value: 'another new value'};
model2 = {key: 'title', value: 'new title'};
return SettingsModel.edit([model1, model2]);
return SettingsModel.edit([model1, model2], context);
}).then(function (edited) {
@ -142,13 +142,13 @@ describe('Settings Model', function () {
value: 'Test Content 1'
};
SettingsModel.add(newSetting, {user: 1}).then(function (createdSetting) {
SettingsModel.add(newSetting, context).then(function (createdSetting) {
should.exist(createdSetting);
createdSetting.has('uuid').should.equal(true);
createdSetting.attributes.key.should.equal(newSetting.key, "key is correct");
createdSetting.attributes.value.should.equal(newSetting.value, "value is correct");
createdSetting.attributes.type.should.equal("core");
createdSetting.attributes.key.should.equal(newSetting.key, 'key is correct');
createdSetting.attributes.value.should.equal(newSetting.value, 'value is correct');
createdSetting.attributes.type.should.equal('core');
done();
}).catch(done);
@ -175,7 +175,7 @@ describe('Settings Model', function () {
});
});
describe('populating defaults from settings.json', function (done) {
describe('populating defaults from settings.json', function () {
beforeEach(function (done) {
config().database.knex('settings').truncate().then(function () {
@ -202,7 +202,7 @@ describe('Settings Model', function () {
});
it('doesn\'t overwrite any existing settings', function (done) {
SettingsModel.add({key: 'description', value: 'Adam\'s Blog'}, {user: 1}).then(function () {
SettingsModel.add({key: 'description', value: 'Adam\'s Blog'}, context).then(function () {
return SettingsModel.populateDefaults();
}).then(function () {
return SettingsModel.findOne('description');

View File

@ -6,7 +6,8 @@ var testUtils = require('../../utils'),
should = require('should'),
// Stuff we are testing
Models = require('../../../server/models');
Models = require('../../../server/models'),
context = {context: {user: 1}};
describe('Tag Model', function () {
@ -32,7 +33,7 @@ describe('Tag Model', function () {
});
it('uses Date objects for dateTime fields', function (done) {
TagModel.add(testUtils.DataGenerator.forModel.tags[0], { user: 1 }).then(function (tag) {
TagModel.add(testUtils.DataGenerator.forModel.tags[0], context).then(function (tag) {
return TagModel.findOne({ id: tag.id });
}).then(function (tag) {
should.exist(tag);
@ -45,59 +46,59 @@ describe('Tag Model', function () {
describe('a Post', function () {
var PostModel = Models.Post;
it('can add a tag', function (done) {
var newPost = testUtils.DataGenerator.forModel.posts[0],
newTag = testUtils.DataGenerator.forModel.tags[0],
createdPostID;
when.all([
PostModel.add(newPost, {user: 1}),
TagModel.add(newTag, {user: 1})
]).then(function (models) {
var createdPost = models[0],
createdTag = models[1];
createdPostID = createdPost.id;
return createdPost.tags().attach(createdTag);
}).then(function () {
return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']});
}).then(function (postWithTag) {
postWithTag.related('tags').length.should.equal(1);
done();
}).catch(done);
});
it('can remove a tag', function (done) {
// The majority of this test is ripped from above, which is obviously a Bad Thing.
// Would be nice to find a way to seed data with relations for cases like this,
// because there are more DB hits than needed
var newPost = testUtils.DataGenerator.forModel.posts[0],
newTag = testUtils.DataGenerator.forModel.tags[0],
createdTagID,
createdPostID;
when.all([
PostModel.add(newPost, {user: 1}),
TagModel.add(newTag, {user: 1})
]).then(function (models) {
var createdPost = models[0],
createdTag = models[1];
createdPostID = createdPost.id;
createdTagID = createdTag.id;
return createdPost.tags().attach(createdTag);
}).then(function () {
return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']});
}).then(function (postWithTag) {
return postWithTag.tags().detach(createdTagID);
}).then(function () {
return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']});
}).then(function (postWithoutTag) {
postWithoutTag.related('tags').length.should.equal(0);
done();
}).catch(done);
});
// it('can add a tag', function (done) {
// var newPost = testUtils.DataGenerator.forModel.posts[0],
// newTag = testUtils.DataGenerator.forModel.tags[0],
// createdPostID;
//
// when.all([
// PostModel.add(newPost, context),
// TagModel.add(newTag, context)
// ]).then(function (models) {
// var createdPost = models[0],
// createdTag = models[1];
//
// createdPostID = createdPost.id;
// return createdPost.tags().attach(createdTag);
// }).then(function () {
// return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']});
// }).then(function (postWithTag) {
// postWithTag.related('tags').length.should.equal(1);
// done();
// }).catch(done);
//
// });
//
// it('can remove a tag', function (done) {
// // The majority of this test is ripped from above, which is obviously a Bad Thing.
// // Would be nice to find a way to seed data with relations for cases like this,
// // because there are more DB hits than needed
// var newPost = testUtils.DataGenerator.forModel.posts[0],
// newTag = testUtils.DataGenerator.forModel.tags[0],
// createdTagID,
// createdPostID;
//
// when.all([
// PostModel.add(newPost, context),
// TagModel.add(newTag, context)
// ]).then(function (models) {
// var createdPost = models[0],
// createdTag = models[1];
//
// createdPostID = createdPost.id;
// createdTagID = createdTag.id;
// return createdPost.tags().attach(createdTag);
// }).then(function () {
// return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']});
// }).then(function (postWithTag) {
// return postWithTag.tags().detach(createdTagID);
// }).then(function () {
// return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']});
// }).then(function (postWithoutTag) {
// postWithoutTag.related('tags').length.should.equal(0);
// done();
// }).catch(done);
// });
describe('setting tags from an array on update', function () {
// When a Post is updated, iterate through the existing tags, and detach any that have since been removed.
@ -106,10 +107,10 @@ describe('Tag Model', function () {
function seedTags(tagNames) {
var createOperations = [
PostModel.add(testUtils.DataGenerator.forModel.posts[0], {user: 1})
PostModel.add(testUtils.DataGenerator.forModel.posts[0], context)
];
var tagModels = tagNames.map(function (tagName) { return TagModel.add({name: tagName}, {user: 1}); });
var tagModels = tagNames.map(function (tagName) { return TagModel.add({name: tagName}, context); });
createOperations = createOperations.concat(tagModels);
return when.all(createOperations).then(function (models) {
@ -119,7 +120,7 @@ describe('Tag Model', function () {
attachOperations = [];
for (var i = 1; i < models.length; i++) {
attachOperations.push(postModel.tags().attach(models[i]));
};
}
return when.all(attachOperations).then(function () {
return postModel;
@ -134,9 +135,14 @@ describe('Tag Model', function () {
seedTags(seededTagNames).then(function (postModel) {
// the tag API expects tags to be provided like {id: 1, name: 'draft'}
var existingTagData = seededTagNames.map(function (tagName, i) { return {id: i + 1, name: tagName}; });
postModel.set('tags', existingTagData);
return postModel.save();
var existingTagData = seededTagNames.map(function (tagName, i) {
return {id: i + 1, name: tagName};
});
postModel = postModel.toJSON();
postModel.tags = existingTagData;
return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']}));
}).then(function (postModel) {
var tagNames = postModel.related('tags').models.map(function (t) { return t.attributes.name; });
tagNames.sort().should.eql(seededTagNames);
@ -158,7 +164,11 @@ describe('Tag Model', function () {
// remove the second tag, and save
tagData.splice(1, 1);
return postModel.set('tags', tagData).save();
postModel = postModel.toJSON();
postModel.tags = tagData;
return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']}));
}).then(function (postModel) {
return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']});
}).then(function (reloadedPost) {
@ -175,14 +185,17 @@ describe('Tag Model', function () {
seedTags(seededTagNames).then(function (_postModel) {
postModel = _postModel;
return TagModel.add({name: 'tag3'}, {user: 1});
return TagModel.add({name: 'tag3'}, context);
}).then(function () {
// the tag API expects tags to be provided like {id: 1, name: 'draft'}
var tagData = seededTagNames.map(function (tagName, i) { return {id: i + 1, name: tagName}; });
// add the additional tag, and save
tagData.push({id: 3, name: 'tag3'});
return postModel.set('tags', tagData).save();
postModel = postModel.toJSON();
postModel.tags = tagData;
return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']}));
}).then(function () {
return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']});
}).then(function (reloadedPost) {
@ -208,7 +221,10 @@ describe('Tag Model', function () {
// add the additional tag, and save
tagData.push({id: null, name: 'tag3'});
return postModel.set('tags', tagData).save(null, {user: 1});
postModel = postModel.toJSON();
postModel.tags = tagData;
return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']}));
}).then(function (postModel) {
return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']});
}).then(function (reloadedPost) {
@ -229,7 +245,11 @@ describe('Tag Model', function () {
// add the additional tags, and save
tagData.push({id: null, name: 'tag2'});
tagData.push({id: null, name: 'tag3'});
return postModel.set('tags', tagData).save(null, {user: 1});
postModel = postModel.toJSON();
postModel.tags = tagData;
return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']}));
}).then(function (postModel) {
return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']});
}).then(function (reloadedPost) {
@ -240,13 +260,13 @@ describe('Tag Model', function () {
}).catch(done);
});
it('attaches one tag that exists in the Tags database and one tag that is new to the Tags database', function (done) {
it('attaches one tag that exists in the Tags database and one tag that is new', function (done) {
var seededTagNames = ['tag1'],
postModel;
seedTags(seededTagNames).then(function (_postModel) {
postModel = _postModel;
return TagModel.add({name: 'tag2'}, {user: 1});
return TagModel.add({name: 'tag2'}, context);
}).then(function () {
// the tag API expects tags to be provided like {id: 1, name: 'draft'}
var tagData = seededTagNames.map(function (tagName, i) { return {id: i + 1, name: tagName}; });
@ -257,7 +277,10 @@ describe('Tag Model', function () {
// Add the tag that doesn't exist in the database
tagData.push({id: 3, name: 'tag3'});
return postModel.set('tags', tagData).save(null, {user: 1});
postModel = postModel.toJSON();
postModel.tags = tagData;
return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']}));
}).then(function () {
return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']});
}).then(function (reloadedPost) {
@ -275,13 +298,13 @@ describe('Tag Model', function () {
}).catch(done);
});
it('attaches one tag that exists in the Tags database and two tags that are new to the Tags database', function (done) {
it('attaches one tag that exists in the Tags database and two tags that are new', function (done) {
var seededTagNames = ['tag1'],
postModel;
seedTags(seededTagNames).then(function (_postModel) {
postModel = _postModel;
return TagModel.add({name: 'tag2'}, {user: 1});
return TagModel.add({name: 'tag2'}, context);
}).then(function () {
// the tag API expects tags to be provided like {id: 1, name: 'draft'}
var tagData = seededTagNames.map(function (tagName, i) { return {id: i + 1, name: tagName}; });
@ -293,7 +316,10 @@ describe('Tag Model', function () {
tagData.push({id: 3, name: 'tag3'});
tagData.push({id: 4, name: 'tag4'});
return postModel.set('tags', tagData).save(null, {user: 1});
postModel = postModel.toJSON();
postModel.tags = tagData;
return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']}));
}).then(function () {
return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']});
}).then(function (reloadedPost) {
@ -312,9 +338,9 @@ describe('Tag Model', function () {
});
it('can add a tag to a post on creation', function (done) {
var newPost = _.extend(testUtils.DataGenerator.forModel.posts[0], {tags: [{name: 'test_tag_1'}]})
var newPost = _.extend(testUtils.DataGenerator.forModel.posts[0], {tags: [{name: 'test_tag_1'}]});
PostModel.add(newPost, {user: 1}).then(function (createdPost) {
PostModel.add(newPost, context).then(function (createdPost) {
return PostModel.findOne({id: createdPost.id, status: 'all'}, { withRelated: ['tags']});
}).then(function (postWithTag) {
postWithTag.related('tags').length.should.equal(1);

View File

@ -2,13 +2,12 @@
var testUtils = require('../../utils'),
should = require('should'),
when = require('when'),
_ = require('lodash'),
errors = require('../../../server/errors'),
sinon = require('sinon'),
uuid = require('node-uuid'),
// Stuff we are testing
Models = require('../../../server/models');
Models = require('../../../server/models'),
context = {context: {user: 1}};
describe('User Model', function run() {
@ -39,7 +38,7 @@ describe('User Model', function run() {
return when.resolve(userData);
});
UserModel.add(userData, {user: 1}).then(function (createdUser) {
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.password.should.not.equal(userData.password, "password was hashed");
@ -55,7 +54,7 @@ describe('User Model', function run() {
return when.resolve(userData);
});
UserModel.add(userData, {user: 1}).then(function (createdUser) {
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.email.should.eql(userData.email, "email address correct");
@ -71,7 +70,7 @@ describe('User Model', function run() {
return when.resolve(userData);
});
UserModel.add(userData, {user: 1}).then(function (createdUser) {
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.image.should.eql('http://www.gravatar.com/avatar/2fab21a4c4ed88e76add10650c73bae1?d=404', 'Gravatar found');
@ -86,7 +85,7 @@ describe('User Model', function run() {
return when.resolve(userData);
});
UserModel.add(userData, {user: 1}).then(function (createdUser) {
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
should.not.exist(createdUser.image);
@ -99,7 +98,7 @@ describe('User Model', function run() {
var userData = testUtils.DataGenerator.forModel.users[2],
email = testUtils.DataGenerator.forModel.users[2].email;
UserModel.add(userData, {user: 1}).then(function () {
UserModel.add(userData, context).then(function () {
// Test same case
return UserModel.getByEmail(email).then(function (user) {
should.exist(user);

View File

@ -5,11 +5,13 @@ var testUtils = require('../utils'),
sinon = require('sinon'),
when = require('when'),
_ = require('lodash'),
Models = require('../../server/models'),
// Stuff we are testing
permissions = require('../../server/permissions'),
effectivePerms = require('../../server/permissions/effective'),
Models = require('../../server/models');
context = {context: {user: 1}};
describe('Permissions', function () {
@ -60,7 +62,7 @@ describe('Permissions', function () {
object_type: obj
};
return Models.Permission.add(newPerm, {user: 1});
return Models.Permission.add(newPerm, context);
},
createTestPermissions = function () {
var createActions = _.map(testPerms, function (testPerm) {
@ -111,7 +113,7 @@ describe('Permissions', function () {
existingUserRoles = foundUser.related('roles').length;
return testRole.save(null, {user: 1}).then(function () {
return testRole.save(null, context).then(function () {
return foundUser.roles().attach(testRole);
});
}).then(function () {
@ -135,7 +137,7 @@ describe('Permissions', function () {
testUser.related('permissions').length.should.equal(0);
return testPermission.save(null, {user: 1}).then(function () {
return testPermission.save(null, context).then(function () {
return testUser.permissions().attach(testPermission);
});
}).then(function () {
@ -155,7 +157,7 @@ describe('Permissions', function () {
description: 'test2 description'
});
testRole.save(null, {user: 1})
testRole.save(null, context)
.then(function () {
return testRole.load('permissions');
})
@ -168,7 +170,7 @@ describe('Permissions', function () {
testRole.related('permissions').length.should.equal(0);
return rolePermission.save(null, {user: 1}).then(function () {
return rolePermission.save(null, context).then(function () {
return testRole.permissions().attach(rolePermission);
});
})
@ -239,7 +241,7 @@ describe('Permissions', function () {
object_type: 'post'
});
return newPerm.save(null, {user: 1}).then(function () {
return newPerm.save(null, context).then(function () {
return foundUser.permissions().attach(newPerm);
});
})
@ -342,7 +344,7 @@ describe('Permissions', function () {
it('does not allow an app to edit a post without permission', function (done) {
// Change the author of the post so the author override doesn't affect the test
Models.Post.edit({'author_id': 2}, {id: 1})
Models.Post.edit({'author_id': 2}, _.extend(context, {id: 1}))
.then(function (updatedPost) {
// Add user permissions
return Models.User.findOne({id: 1})
@ -353,7 +355,7 @@ describe('Permissions', function () {
object_type: 'post'
});
return newPerm.save(null, {user: 1}).then(function () {
return newPerm.save(null, context).then(function () {
return foundUser.permissions().attach(newPerm).then(function () {
return when.all([updatedPost, foundUser]);
});