mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-21 01:41:46 +03:00
7eb316b786
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in 0e6ed957cd (diff-70f514a06347c048648be464819503c4L67)
i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
333 lines
12 KiB
JavaScript
333 lines
12 KiB
JavaScript
var Promise = require('bluebird'),
|
|
_ = require('lodash'),
|
|
models = require('../../models'),
|
|
errors = require('../../errors'),
|
|
globalUtils = require('../../utils'),
|
|
i18n = require('../../i18n'),
|
|
|
|
internal = {context: {internal: true}},
|
|
utils,
|
|
areEmpty,
|
|
updatedSettingKeys,
|
|
stripProperties;
|
|
|
|
updatedSettingKeys = {
|
|
activePlugins: 'activeApps',
|
|
installedPlugins: 'installedApps'
|
|
};
|
|
|
|
areEmpty = function (object) {
|
|
var fields = _.toArray(arguments).slice(1),
|
|
areEmpty = _.every(fields, function (field) {
|
|
return _.isEmpty(object[field]);
|
|
});
|
|
|
|
return areEmpty;
|
|
};
|
|
|
|
stripProperties = function stripProperties(properties, data) {
|
|
data = _.cloneDeep(data);
|
|
_.each(data, function (obj) {
|
|
_.each(properties, function (property) {
|
|
delete obj[property];
|
|
});
|
|
});
|
|
return data;
|
|
};
|
|
|
|
utils = {
|
|
internal: internal,
|
|
|
|
processUsers: function preProcessUsers(tableData, owner, existingUsers, objs) {
|
|
// We need to:
|
|
// 1. figure out who the owner of the blog is
|
|
// 2. figure out what users we have
|
|
// 3. figure out what users the import data refers to in foreign keys
|
|
// 4. try to map each one to a user
|
|
var userKeys = ['created_by', 'updated_by', 'published_by', 'author_id'],
|
|
userMap = {};
|
|
|
|
// Search the passed in objects for any user foreign keys
|
|
_.each(objs, function (obj) {
|
|
if (tableData[obj]) {
|
|
// For each object in the tableData that matches
|
|
_.each(tableData[obj], function (data) {
|
|
// For each possible user foreign key
|
|
_.each(userKeys, function (key) {
|
|
if (_.has(data, key) && data[key] !== null) {
|
|
userMap[data[key]] = {};
|
|
}
|
|
});
|
|
});
|
|
}
|
|
});
|
|
|
|
// We now have a list of users we need to figure out what their email addresses are
|
|
// tableData.users has id's as numbers (see fixtures/export)
|
|
// userIdToMap === tableData.users, but it's already a string, because it's an object key and they are always strings
|
|
_.each(_.keys(userMap), function (userIdToMap) {
|
|
var foundUser = _.find(tableData.users, function (tableDataUser) {
|
|
return tableDataUser.id.toString() === userIdToMap;
|
|
});
|
|
|
|
// we now know that userToMap's email is foundUser.email - look them up in existing users
|
|
if (foundUser && _.has(foundUser, 'email') && _.has(existingUsers, foundUser.email)) {
|
|
existingUsers[foundUser.email].importId = userIdToMap;
|
|
userMap[userIdToMap] = existingUsers[foundUser.email].realId;
|
|
} else if (models.User.isOwnerUser(userIdToMap)) {
|
|
existingUsers[owner.email].importId = userIdToMap;
|
|
userMap[userIdToMap] = existingUsers[owner.email].realId;
|
|
} else if (models.User.isExternalUser(userIdToMap)) {
|
|
userMap[userIdToMap] = models.User.externalUser;
|
|
} else {
|
|
throw new errors.DataImportError({
|
|
message: i18n.t('errors.data.import.utils.dataLinkedToUnknownUser', {userToMap: userIdToMap}),
|
|
property: 'user.id',
|
|
value: userIdToMap
|
|
});
|
|
}
|
|
});
|
|
|
|
// now replace any user foreign keys
|
|
_.each(objs, function (obj) {
|
|
if (tableData[obj]) {
|
|
// For each object in the tableData that matches
|
|
_.each(tableData[obj], function (data) {
|
|
// For each possible user foreign key
|
|
_.each(userKeys, function (key) {
|
|
if (_.has(data, key) && data[key] !== null) {
|
|
data[key] = userMap[data[key]];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
});
|
|
|
|
return tableData;
|
|
},
|
|
|
|
preProcessPostTags: function preProcessPostTags(tableData) {
|
|
var postTags,
|
|
postsWithTags = {};
|
|
|
|
postTags = tableData.posts_tags;
|
|
_.each(postTags, function (postTag) {
|
|
if (!postsWithTags.hasOwnProperty(postTag.post_id)) {
|
|
postsWithTags[postTag.post_id] = [];
|
|
}
|
|
postsWithTags[postTag.post_id].push(postTag.tag_id);
|
|
});
|
|
|
|
_.each(postsWithTags, function (tagIds, postId) {
|
|
var post, tags;
|
|
post = _.find(tableData.posts, function (post) {
|
|
return post.id === postId;
|
|
});
|
|
|
|
if (post) {
|
|
tags = _.filter(tableData.tags, function (tag) {
|
|
return _.indexOf(tagIds, tag.id) !== -1;
|
|
});
|
|
post.tags = [];
|
|
_.each(tags, function (tag) {
|
|
// names are unique.. this should get the right tags added
|
|
// as long as tags are added first;
|
|
post.tags.push({name: tag.name});
|
|
});
|
|
}
|
|
});
|
|
|
|
return tableData;
|
|
},
|
|
|
|
preProcessRolesUsers: function preProcessRolesUsers(tableData, owner, roles) {
|
|
var validRoles = _.map(roles, 'name');
|
|
if (!tableData.roles || !tableData.roles.length) {
|
|
tableData.roles = roles;
|
|
}
|
|
|
|
_.each(tableData.roles, function (_role) {
|
|
var match = false;
|
|
// Check import data does not contain unknown roles
|
|
_.each(validRoles, function (validRole) {
|
|
if (_role.name === validRole) {
|
|
match = true;
|
|
_role.oldId = _role.id;
|
|
_role.id = _.find(roles, {name: validRole}).id;
|
|
}
|
|
});
|
|
// If unknown role is found then remove role to force down to Author
|
|
if (!match) {
|
|
_role.oldId = _role.id;
|
|
_role.id = _.find(roles, {name: 'Author'}).id;
|
|
}
|
|
});
|
|
|
|
_.each(tableData.roles_users, function (roleUser) {
|
|
var user = _.find(tableData.users, function (user) {
|
|
return user.id === roleUser.user_id;
|
|
});
|
|
|
|
// Map role_id to updated roles id
|
|
roleUser.role_id = _.find(tableData.roles, {oldId: roleUser.role_id}).id;
|
|
|
|
// Check for owner users that do not match current owner and change role to administrator
|
|
if (roleUser.role_id === owner.roles[0].id && user && user.email && user.email !== owner.email) {
|
|
roleUser.role_id = _.find(roles, {name: 'Administrator'}).id;
|
|
user.roles = [roleUser.role_id];
|
|
}
|
|
|
|
// just the one role for now
|
|
if (user && !user.roles) {
|
|
user.roles = [roleUser.role_id];
|
|
}
|
|
});
|
|
|
|
return tableData;
|
|
},
|
|
|
|
importTags: function importTags(tableData, transaction) {
|
|
if (!tableData) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
var ops = [];
|
|
|
|
tableData = stripProperties(['id'], tableData);
|
|
_.each(tableData, function (tag) {
|
|
// Validate minimum tag fields
|
|
if (areEmpty(tag, 'name', 'slug')) {
|
|
return;
|
|
}
|
|
|
|
ops.push(models.Tag.findOne({name: tag.name}, {transacting: transaction}).then(function (_tag) {
|
|
if (!_tag) {
|
|
return models.Tag.add(tag, _.extend({}, internal, {transacting: transaction}))
|
|
.catch(function (error) {
|
|
return Promise.reject({raw: error, model: 'tag', data: tag});
|
|
});
|
|
}
|
|
|
|
return _tag;
|
|
}).reflect());
|
|
});
|
|
|
|
return Promise.all(ops);
|
|
},
|
|
|
|
importPosts: function importPosts(tableData, transaction) {
|
|
if (!tableData) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
var ops = [];
|
|
|
|
tableData = stripProperties(['id'], tableData);
|
|
_.each(tableData, function (post) {
|
|
// Validate minimum post fields
|
|
if (areEmpty(post, 'title', 'slug', 'markdown')) {
|
|
return;
|
|
}
|
|
|
|
// The post importer has auto-timestamping disabled
|
|
if (!post.created_at) {
|
|
post.created_at = Date.now();
|
|
}
|
|
|
|
ops.push(models.Post.add(post, _.extend({}, internal, {transacting: transaction, importing: true}))
|
|
.catch(function (error) {
|
|
return Promise.reject({raw: error, model: 'post', data: post});
|
|
}).reflect()
|
|
);
|
|
});
|
|
|
|
return Promise.all(ops);
|
|
},
|
|
|
|
importUsers: function importUsers(tableData, existingUsers, transaction) {
|
|
var ops = [];
|
|
tableData = stripProperties(['id'], tableData);
|
|
_.each(tableData, function (user) {
|
|
// Validate minimum user fields
|
|
if (areEmpty(user, 'name', 'slug', 'email')) {
|
|
return;
|
|
}
|
|
|
|
if (_.has(existingUsers, user.email)) {
|
|
// User is already present, ignore
|
|
return;
|
|
}
|
|
|
|
// Set password to a random password, and lock the account
|
|
user.password = globalUtils.uid(50);
|
|
user.status = 'locked';
|
|
|
|
ops.push(models.User.add(user, _.extend({}, internal, {transacting: transaction}))
|
|
.catch(function (error) {
|
|
return Promise.reject({raw: error, model: 'user', data: user});
|
|
}));
|
|
});
|
|
|
|
return ops;
|
|
},
|
|
|
|
importSettings: function importSettings(tableData, transaction) {
|
|
if (!tableData) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
// for settings we need to update individual settings, and insert any missing ones
|
|
// settings we MUST NOT update are 'core' and 'theme' settings
|
|
// as all of these will cause side effects which don't make sense for an import
|
|
var blackList = ['core', 'theme'],
|
|
ops = [];
|
|
|
|
tableData = stripProperties(['id'], tableData);
|
|
tableData = _.filter(tableData, function (data) {
|
|
return blackList.indexOf(data.type) === -1;
|
|
});
|
|
|
|
// Clean up legacy plugin setting references
|
|
_.each(tableData, function (datum) {
|
|
datum.key = updatedSettingKeys[datum.key] || datum.key;
|
|
});
|
|
|
|
ops.push(models.Settings.edit(tableData, _.extend({}, internal, {transacting: transaction})).catch(function (error) {
|
|
// Ignore NotFound errors
|
|
if (!(error instanceof errors.NotFoundError)) {
|
|
return Promise.reject({raw: error, model: 'setting', data: tableData});
|
|
}
|
|
}).reflect());
|
|
|
|
return Promise.all(ops);
|
|
},
|
|
|
|
/** For later **/
|
|
importApps: function importApps(tableData, transaction) {
|
|
if (!tableData) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
var ops = [];
|
|
|
|
tableData = stripProperties(['id'], tableData);
|
|
_.each(tableData, function (app) {
|
|
// Avoid duplicates
|
|
ops.push(models.App.findOne({name: app.name}, {transacting: transaction}).then(function (_app) {
|
|
if (!_app) {
|
|
return models.App.add(app, _.extend({}, internal, {transacting: transaction}))
|
|
.catch(function (error) {
|
|
return Promise.reject({raw: error, model: 'app', data: app});
|
|
});
|
|
}
|
|
|
|
return _app;
|
|
}).reflect());
|
|
});
|
|
|
|
return Promise.all(ops);
|
|
}
|
|
};
|
|
|
|
module.exports = utils;
|