Skip to content

Commit

Permalink
Use current user in models
Browse files Browse the repository at this point in the history
closes TryGhost#2058
- fixed apiContext as suggested in the issue
- added user to options object for models
- added api.users.register() for public registration
- changed models to use options.user for created_by, updated_by,
author_id and published_by
- added override to session model to avoid created_by and updated_by
values
- added user (id: 1) to tests
- added user (id: 1) for registration
- added user (id: 1) for import, fixtures and default settings
- added user (id: 1) for user update
- added user (id: 1) for settings update (dbHash, installedApps, update
check)
- updated bookshelf to version 0.6.8
  • Loading branch information
sebgie committed Apr 16, 2014
1 parent 88d82ff commit 61e94a6
Show file tree
Hide file tree
Showing 24 changed files with 133 additions and 101 deletions.
2 changes: 1 addition & 1 deletion core/server/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ requestHandler = function (apiMethod) {
return function (req, res) {
var options = _.extend(req.body, req.files, req.query, req.params),
apiContext = {
user: req.session && req.session.user
user: (req.session && req.session.user) ? req.session.user : null
};

return apiMethod.call(apiContext, options).then(function (result) {
Expand Down
9 changes: 6 additions & 3 deletions core/server/api/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,11 @@ posts = {
// **takes:** a json object with all the properties which should be updated
edit: function edit(postData) {
// **returns:** a promise for the resulting post in a json object
return canThis(this.user).edit.post(postData.id).then(function () {
var self = this;

return canThis(self.user).edit.post(postData.id).then(function () {
return checkPostData(postData).then(function (checkedPostData) {
return dataProvider.Post.edit(checkedPostData.posts[0]);
return dataProvider.Post.edit(checkedPostData.posts[0], {user: self.user})
}).then(function (result) {
if (result) {
var omitted = result.toJSON();
Expand All @@ -81,10 +83,11 @@ posts = {
// #### Add
// **takes:** a json object representing a post,
add: function add(postData) {
var self = this;
// **returns:** a promise for the resulting post in a json object
return canThis(this.user).create.post().then(function () {
return checkPostData(postData).then(function (checkedPostData) {
return dataProvider.Post.add(checkedPostData.posts[0]);
return dataProvider.Post.add(checkedPostData.posts[0], {user: self.user});
}).then(function (result) {
var omitted = result.toJSON();
omitted.author = _.omit(omitted.author, filteredUserAttributes);
Expand Down
9 changes: 6 additions & 3 deletions core/server/api/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,16 +181,19 @@ settings = {

// **takes:** either a json object representing a collection of settings, or a key and value pair
edit: function edit(key, value) {
var self = this,
type;

// Check for passing a collection of settings first
if (_.isObject(key)) {
//clean data
var type = key.type;
type = key.type;
delete key.type;
delete key.availableThemes;
delete key.availableApps;

key = settingsCollection(key);
return dataProvider.Settings.edit(key).then(function (result) {
return dataProvider.Settings.edit(key, {user: self.user}).then(function (result) {
result.models = result;
return when(readSettingsResult(result)).then(function (settings) {
updateSettingsCache(settings);
Expand All @@ -216,7 +219,7 @@ settings = {
value = JSON.stringify(value);
}
setting.set('value', value);
return dataProvider.Settings.edit(setting).then(function (result) {
return dataProvider.Settings.edit(setting, {user: self.user}).then(function (result) {
settingsCache[_.first(result).attributes.key].value = _.first(result).attributes.value;
}).then(function () {
return config.theme.update(settings, config().url).then(function () {
Expand Down
12 changes: 10 additions & 2 deletions core/server/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ users = {
edit: function edit(userData) {
// **returns:** a promise for the resulting user in a json object
userData.id = this.user;
return dataProvider.User.edit(userData).then(function (result) {
return dataProvider.User.edit(userData, {user: this.user}).then(function (result) {
if (result) {
var omitted = _.omit(result.toJSON(), filteredAttributes);
return omitted;
Expand All @@ -67,7 +67,15 @@ users = {
add: function add(userData) {

// **returns:** a promise for the resulting user in a json object
return dataProvider.User.add(userData);
return dataProvider.User.add(userData, {user: this.user});
},

// #### Register
// **takes:** a json object representing a user
register: function register(userData) {
// TODO: if we want to prevent users from being created with the signup form
// this is the right place to do it
return users.add.call({user: 1}, userData);
},

// #### Check
Expand Down
2 changes: 1 addition & 1 deletion core/server/apps/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function saveInstalledApps(installedApps) {
return getInstalledApps().then(function (currentInstalledApps) {
var updatedAppsInstalled = _.uniq(installedApps.concat(currentInstalledApps));

return api.settings.edit('installedApps', updatedAppsInstalled);
return api.settings.edit.call({user: 1}, 'installedApps', updatedAppsInstalled);
});
}

Expand Down
4 changes: 2 additions & 2 deletions core/server/controllers/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,12 +244,12 @@ adminControllers = {
email = req.body.email,
password = req.body.password;

api.users.add({
api.users.register({
name: name,
email: email,
password: password
}).then(function (user) {
api.settings.edit('email', email).then(function () {
api.settings.edit.call({user: 1}, 'email', email).then(function () {
var message = {
to: email,
subject: 'Your New Ghost Blog',
Expand Down
15 changes: 7 additions & 8 deletions core/server/data/fixtures/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,29 +128,28 @@ var fixtures = {
]
};


populateFixtures = function () {
var ops = [],
relations = [];

_.each(fixtures.posts, function (post) {
ops.push(function () {return Post.add(post); });
ops.push(function () {return Post.add(post, {user: 1}); });
});

_.each(fixtures.tags, function (tag) {
ops.push(function () {return Tag.add(tag); });
ops.push(function () {return Tag.add(tag, {user: 1}); });
});

_.each(fixtures.roles, function (role) {
ops.push(function () {return Role.add(role); });
ops.push(function () {return Role.add(role, {user: 1}); });
});

_.each(fixtures.permissions, function (permission) {
ops.push(function () {return Permission.add(permission); });
ops.push(function () {return Permission.add(permission, {user: 1}); });
});

_.each(fixtures.permissions003, function (permission) {
ops.push(function () {return Permission.add(permission); });
ops.push(function () {return Permission.add(permission, {user: 1}); });
});

// add the tag to the post
Expand Down Expand Up @@ -222,7 +221,7 @@ updateFixtures = function () {
relations = [];

_.each(fixtures.permissions003, function (permission) {
ops.push(function () {return Permission.add(permission); });
ops.push(function () {return Permission.add(permission, {user: 1}); });
});

relations.push(function () {
Expand Down Expand Up @@ -290,4 +289,4 @@ updateFixtures = function () {
module.exports = {
populateFixtures: populateFixtures,
updateFixtures: updateFixtures
};
};
15 changes: 7 additions & 8 deletions core/server/data/import/000.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,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, {transacting: transaction})
return models.Tag.add(tag, {user: 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); });
}
Expand All @@ -96,7 +96,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, {transacting: transaction, importing: true})
ops.push(models.Post.add(post, {user: 1, 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); }));
});
Expand All @@ -106,7 +106,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], {transacting: transaction})
ops.push(models.User.edit(tableData[0], {user: 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); }));
}
Expand All @@ -121,8 +121,7 @@ function importSettings(ops, tableData, transaction) {
tableData = _.filter(tableData, function (data) {
return blackList.indexOf(data.type) === -1;
});

ops.push(models.Settings.edit(tableData, transaction)
ops.push(models.Settings.edit(tableData, {user: 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); }));
}
Expand Down Expand Up @@ -234,10 +233,10 @@ Importer000.prototype.basicImport = function (data) {
rej = true;
}
});
if (rej) {
t.rollback(error);
} else {
if (!rej) {
t.commit();
} else {
t.rollback(error);
}
});
}).then(function () {
Expand Down
2 changes: 1 addition & 1 deletion core/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ function initDbHashAndFirstRun() {

if (dbHash === null) {
var initHash = uuid.v4();
return when(api.settings.edit('dbHash', initHash)).then(function (settings) {
return when(api.settings.edit.call({user: 1}, 'dbHash', initHash)).then(function (settings) {
dbHash = settings.dbHash;
return dbHash;
}).then(doFirstRun);
Expand Down
14 changes: 5 additions & 9 deletions core/server/models/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,16 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
validation.validateSchema(this.tableName, this.toJSON());
},

creating: function () {
creating: function (newObj, attr, options) {
if (!this.get('created_by')) {
this.set('created_by', 1);
this.set('created_by', options.user);
}
},

saving: function () {
// Remove any properties which don't belong on the model
saving: function (newObj, attr, options) {
// Remove any properties which don't belong on the model
this.attributes = this.pick(this.permittedAttributes());

// sessions do not have 'updated_by' column
if (this.tableName !== 'sessions') {
this.set('updated_by', 1);
}
this.set('updated_by', options.user);
},

// Base prototype properties will go here
Expand Down
25 changes: 18 additions & 7 deletions core/server/models/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ Post = ghostBookshelf.Model.extend({
tagsToCheck,
i;

options = options || {};
// keep tags for 'saved' event and deduplicate upper/lowercase tags
tagsToCheck = this.get('tags');
this.myTags = [];
Expand All @@ -65,7 +66,7 @@ Post = ghostBookshelf.Model.extend({
self.myTags.push(item);
});

ghostBookshelf.Model.prototype.saving.call(this);
ghostBookshelf.Model.prototype.saving.call(this, newPage, attr, options);

this.set('html', converter.makeHtml(this.get('markdown')));

Expand All @@ -78,7 +79,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', 1);
this.set('published_by', options.user);
}

if (this.hasChanged('slug') || !this.get('slug')) {
Expand All @@ -94,13 +95,14 @@ Post = ghostBookshelf.Model.extend({

creating: function (newPage, attr, options) {
/*jshint unused:false*/
options = options || {};

// set any dynamic default properties
if (!this.get('author_id')) {
this.set('author_id', 1);
this.set('author_id', options.user);
}

ghostBookshelf.Model.prototype.creating.call(this);
ghostBookshelf.Model.prototype.creating.call(this, newPage, attr, options);
},

updateTags: function (newPost, attr, options) {
Expand Down Expand Up @@ -128,7 +130,9 @@ Post = ghostBookshelf.Model.extend({
});

if (tagsToDetach.length > 0) {
tagOperations.push(newPost.tags().detach(tagsToDetach, options));
// _.omit(options, 'query') is a fix for using bookshelf 0.6.8
// (https://github.com/tgriesser/bookshelf/issues/294)
tagOperations.push(newPost.tags().detach(tagsToDetach, _.omit(options, 'query')));
}

// Next check if new tags are all exactly the same as what is set on the model
Expand All @@ -142,7 +146,9 @@ Post = ghostBookshelf.Model.extend({
if (!_.isEmpty(tagsToAttach)) {
return Tags.forge().query('whereIn', 'name', _.pluck(tagsToAttach, 'name')).fetch(options).then(function (matchingTags) {
_.each(matchingTags.toJSON(), function (matchingTag) {
tagOperations.push(newPost.tags().attach(matchingTag.id, options));
// _.omit(options, 'query') is a fix for using bookshelf 0.6.8
// (https://github.com/tgriesser/bookshelf/issues/294)
tagOperations.push(newPost.tags().attach(matchingTag.id, _.omit(options, 'query')));
tagsToAttach = _.reject(tagsToAttach, function (tagToAttach) {
return tagToAttach.name === matchingTag.name;
});
Expand Down Expand Up @@ -171,7 +177,9 @@ Post = ghostBookshelf.Model.extend({

// Attach each newly created tag
_.each(createdTagsToAttach, function (tagToAttach) {
newPost.tags().attach(tagToAttach.id, tagToAttach.name, options);
// _.omit(options, 'query') is a fix for using bookshelf 0.6.8
// (https://github.com/tgriesser/bookshelf/issues/294)
newPost.tags().attach(tagToAttach.id, tagToAttach.name, _.omit(options, 'query'));
});

}
Expand Down Expand Up @@ -443,13 +451,15 @@ Post = ghostBookshelf.Model.extend({
},
add: function (newPostData, options) {
var self = this;
options = options || {};

return ghostBookshelf.Model.add.call(this, newPostData, options).then(function (post) {
return self.findOne({status: 'all', id: post.id}, options);
});
},
edit: function (editedPost, options) {
var self = this;
options = options || {};

return ghostBookshelf.Model.edit.call(this, editedPost, options).then(function (post) {
if (post) {
Expand All @@ -459,6 +469,7 @@ Post = ghostBookshelf.Model.extend({
},
destroy: function (_identifier, options) {
options = options || {};

return this.forge({id: _identifier}).fetch({withRelated: ['tags']}).then(function destroyTags(post) {
var tagIds = _.pluck(post.related('tags').toJSON(), 'id');
if (tagIds) {
Expand Down
16 changes: 15 additions & 1 deletion core/server/models/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,21 @@ var ghostBookshelf = require('./base'),

Session = ghostBookshelf.Model.extend({

tableName: 'sessions'
tableName: 'sessions',

// override for base function since we don't have
// a created_by field for sessions
creating: function (newObj, attr, options) {
/*jshint unused:false*/
},

// override for base function since we don't have
// a updated_by field for sessions
saving: function (newObj, attr, options) {
/*jshint unused:false*/
// Remove any properties which don't belong on the model
this.attributes = this.pick(this.permittedAttributes());
},

}, {
destroyAll: function (options) {
Expand Down
Loading

0 comments on commit 61e94a6

Please sign in to comment.