mirror of
https://github.com/TryGhost/Ghost.git
synced 2025-04-08 02:52:39 -05:00
Import lib/common only
refs #9178 - avoid importing 4 modules (logging, errors, events and i18n) - simply require common in each file
This commit is contained in:
parent
ac2578b419
commit
6f6c8f4521
166 changed files with 1283 additions and 1297 deletions
|
@ -3,8 +3,7 @@ var util = require('util'),
|
|||
request = require('superagent'),
|
||||
debug = require('ghost-ignition').debug('scheduling-default'),
|
||||
SchedulingBase = require('./SchedulingBase'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
logging = require('../../lib/common/logging');
|
||||
common = require('../../lib/common');
|
||||
|
||||
/**
|
||||
* allJobs is a sorted list by time attribute
|
||||
|
@ -237,7 +236,7 @@ SchedulingDefault.prototype._pingUrl = function (object) {
|
|||
}, self.retryTimeoutInMs);
|
||||
}
|
||||
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
level: 'critical'
|
||||
}));
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
var Promise = require('bluebird'),
|
||||
moment = require('moment'),
|
||||
localUtils = require('../utils'),
|
||||
events = require('../../../lib/common/events'),
|
||||
errors = require('../../../lib/common/errors'),
|
||||
common = require('../../../lib/common'),
|
||||
models = require('../../../models'),
|
||||
schedules = require('../../../api/schedules'),
|
||||
urlService = require('../../../services/url'),
|
||||
|
@ -41,11 +40,11 @@ exports.init = function init(options) {
|
|||
client = null;
|
||||
|
||||
if (!config) {
|
||||
return Promise.reject(new errors.IncorrectUsageError({message: 'post-scheduling: no config was provided'}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({message: 'post-scheduling: no config was provided'}));
|
||||
}
|
||||
|
||||
if (!apiUrl) {
|
||||
return Promise.reject(new errors.IncorrectUsageError({message: 'post-scheduling: no apiUrl was provided'}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({message: 'post-scheduling: no apiUrl was provided'}));
|
||||
}
|
||||
|
||||
return _private.loadClient()
|
||||
|
@ -73,21 +72,21 @@ exports.init = function init(options) {
|
|||
adapter.run();
|
||||
})
|
||||
.then(function () {
|
||||
events.onMany([
|
||||
common.events.onMany([
|
||||
'post.scheduled',
|
||||
'page.scheduled'
|
||||
], function (object) {
|
||||
adapter.schedule(_private.normalize({object: object, apiUrl: apiUrl, client: client}));
|
||||
});
|
||||
|
||||
events.onMany([
|
||||
common.events.onMany([
|
||||
'post.rescheduled',
|
||||
'page.rescheduled'
|
||||
], function (object) {
|
||||
adapter.reschedule(_private.normalize({object: object, apiUrl: apiUrl, client: client}));
|
||||
});
|
||||
|
||||
events.onMany([
|
||||
common.events.onMany([
|
||||
'post.unscheduled',
|
||||
'page.unscheduled'
|
||||
], function (object) {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
SchedulingBase = require('./SchedulingBase'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
common = require('../../lib/common'),
|
||||
cache = {};
|
||||
|
||||
exports.createAdapter = function (options) {
|
||||
|
@ -13,7 +13,9 @@ exports.createAdapter = function (options) {
|
|||
contentPath = options.contentPath;
|
||||
|
||||
if (!activeAdapter) {
|
||||
return Promise.reject(new errors.IncorrectUsageError({message: 'Please provide an active adapter.'}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({
|
||||
message: 'Please provide an active adapter.'
|
||||
}));
|
||||
}
|
||||
|
||||
if (cache.hasOwnProperty(activeAdapter)) {
|
||||
|
@ -27,7 +29,7 @@ exports.createAdapter = function (options) {
|
|||
adapter = new (require(activeAdapter))(options);
|
||||
} catch (err) {
|
||||
if (err.code !== 'MODULE_NOT_FOUND') {
|
||||
return Promise.reject(new errors.IncorrectUsageError({err: err}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({err: err}));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -39,10 +41,13 @@ exports.createAdapter = function (options) {
|
|||
} catch (err) {
|
||||
// CASE: only throw error if module does exist
|
||||
if (err.code !== 'MODULE_NOT_FOUND') {
|
||||
return Promise.reject(new errors.IncorrectUsageError({err: err}));
|
||||
// CASE: if module not found it can be an error within the adapter (cannot find bluebird for example)
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({err: err}));
|
||||
// CASE: if module not found it can be an error within the adapter (cannot find bluebird for example)
|
||||
} else if (err.code === 'MODULE_NOT_FOUND' && err.message.indexOf(contentPath + activeAdapter) === -1) {
|
||||
return Promise.reject(new errors.IncorrectUsageError({err: err, help: 'Please check the imports are valid in ' + contentPath + activeAdapter}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({
|
||||
err: err,
|
||||
help: 'Please check the imports are valid in ' + contentPath + activeAdapter
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -54,22 +59,30 @@ exports.createAdapter = function (options) {
|
|||
} catch (err) {
|
||||
// CASE: only throw error if module does exist
|
||||
if (err.code === 'MODULE_NOT_FOUND') {
|
||||
return Promise.reject(new errors.IncorrectUsageError({message: 'We cannot find your adapter in: ' + contentPath + ' or: ' + internalPath}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({
|
||||
message: 'We cannot find your adapter in: ' + contentPath + ' or: ' + internalPath
|
||||
}));
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.IncorrectUsageError({err: err}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({err: err}));
|
||||
}
|
||||
|
||||
if (!(adapter instanceof SchedulingBase)) {
|
||||
return Promise.reject(new errors.IncorrectUsageError({message: 'Your adapter does not inherit from the SchedulingBase.'}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({
|
||||
message: 'Your adapter does not inherit from the SchedulingBase.'
|
||||
}));
|
||||
}
|
||||
|
||||
if (!adapter.requiredFns) {
|
||||
return Promise.reject(new errors.IncorrectUsageError({message: 'Your adapter does not provide the minimum required functions.'}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({
|
||||
message: 'Your adapter does not provide the minimum required functions.'
|
||||
}));
|
||||
}
|
||||
|
||||
if (_.xor(adapter.requiredFns, Object.keys(_.pick(Object.getPrototypeOf(adapter), adapter.requiredFns))).length) {
|
||||
return Promise.reject(new errors.IncorrectUsageError({message: 'Your adapter does not provide the minimum required functions.'}));
|
||||
return Promise.reject(new common.errors.IncorrectUsageError({
|
||||
message: 'Your adapter does not provide the minimum required functions.'
|
||||
}));
|
||||
}
|
||||
|
||||
cache[activeAdapter] = adapter;
|
||||
|
|
|
@ -9,11 +9,9 @@ var serveStatic = require('express').static,
|
|||
Promise = require('bluebird'),
|
||||
moment = require('moment'),
|
||||
config = require('../../config'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
globalUtils = require('../../utils'),
|
||||
urlService = require('../../services/url'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
StorageBase = require('ghost-storage-base');
|
||||
|
||||
class LocalFileStore extends StorageBase {
|
||||
|
@ -89,20 +87,20 @@ class LocalFileStore extends StorageBase {
|
|||
maxAge: globalUtils.ONE_YEAR_MS,
|
||||
fallthrough: false,
|
||||
onEnd: function onEnd() {
|
||||
logging.info('LocalFileStorage.serve', req.path, moment().diff(startedAtMoment, 'ms') + 'ms');
|
||||
common.logging.info('LocalFileStorage.serve', req.path, moment().diff(startedAtMoment, 'ms') + 'ms');
|
||||
}
|
||||
}
|
||||
)(req, res, function (err) {
|
||||
if (err) {
|
||||
if (err.statusCode === 404) {
|
||||
return next(new errors.NotFoundError({
|
||||
message: i18n.t('errors.errors.imageNotFound'),
|
||||
return next(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.errors.imageNotFound'),
|
||||
code: 'STATIC_FILE_NOT_FOUND',
|
||||
property: err.path
|
||||
}));
|
||||
}
|
||||
|
||||
return next(new errors.GhostError({err: err}));
|
||||
return next(new common.errors.GhostError({err: err}));
|
||||
}
|
||||
|
||||
next();
|
||||
|
@ -136,15 +134,15 @@ class LocalFileStore extends StorageBase {
|
|||
fs.readFile(targetPath, function (err, bytes) {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
return reject(new errors.NotFoundError({
|
||||
return reject(new common.errors.NotFoundError({
|
||||
err: err,
|
||||
message: i18n.t('errors.errors.imageNotFoundWithRef', {img: options.path})
|
||||
message: common.i18n.t('errors.errors.imageNotFoundWithRef', {img: options.path})
|
||||
}));
|
||||
}
|
||||
|
||||
return reject(new errors.GhostError({
|
||||
return reject(new common.errors.GhostError({
|
||||
err: err,
|
||||
message: i18n.t('errors.errors.cannotReadImage', {img: options.path})
|
||||
message: common.i18n.t('errors.errors.cannotReadImage', {img: options.path})
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var errors = require('../../lib/common/errors'),
|
||||
config = require('../../config'),
|
||||
var _ = require('lodash'),
|
||||
StorageBase = require('ghost-storage-base'),
|
||||
_ = require('lodash'),
|
||||
config = require('../../config'),
|
||||
common = require('../../lib/common'),
|
||||
storage = {};
|
||||
|
||||
/**
|
||||
|
@ -17,7 +17,7 @@ function getStorage() {
|
|||
|
||||
// CASE: type does not exist
|
||||
if (!storageChoice) {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
message: 'No adapter found'
|
||||
});
|
||||
}
|
||||
|
@ -32,20 +32,20 @@ function getStorage() {
|
|||
CustomStorage = require(config.getContentPath('storage') + storageChoice);
|
||||
} catch (err) {
|
||||
if (err.message.match(/strict mode/gi)) {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
message: 'Your custom storage adapter must use strict mode.',
|
||||
help: 'Add \'use strict\'; on top of your adapter.',
|
||||
err: err
|
||||
});
|
||||
// CASE: if module not found it can be an error within the adapter (cannot find bluebird for example)
|
||||
// CASE: if module not found it can be an error within the adapter (cannot find bluebird for example)
|
||||
} else if (err.code === 'MODULE_NOT_FOUND' && err.message.indexOf(config.getContentPath('storage') + storageChoice) === -1) {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
message: 'We have detected an error in your custom storage adapter.',
|
||||
err: err
|
||||
});
|
||||
// CASE: only throw error if module does exist
|
||||
// CASE: only throw error if module does exist
|
||||
} else if (err.code !== 'MODULE_NOT_FOUND') {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
message: 'We have detected an unknown error in your custom storage adapter.',
|
||||
err: err
|
||||
});
|
||||
|
@ -57,12 +57,12 @@ function getStorage() {
|
|||
CustomStorage = CustomStorage || require(config.get('paths').internalStoragePath + storageChoice);
|
||||
} catch (err) {
|
||||
if (err.code === 'MODULE_NOT_FOUND') {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
err: err,
|
||||
context: 'We cannot find your adapter in: ' + config.getContentPath('storage') + ' or: ' + config.get('paths').internalStoragePath
|
||||
});
|
||||
} else {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
message: 'We have detected an error in your custom storage adapter.',
|
||||
err: err
|
||||
});
|
||||
|
@ -73,19 +73,19 @@ function getStorage() {
|
|||
|
||||
// CASE: if multiple StorageBase modules are installed, instanceof could return false
|
||||
if (Object.getPrototypeOf(CustomStorage).name !== StorageBase.name) {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
message: 'Your storage adapter does not inherit from the Storage Base.'
|
||||
});
|
||||
}
|
||||
|
||||
if (!customStorage.requiredFns) {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
message: 'Your storage adapter does not provide the minimum required functions.'
|
||||
});
|
||||
}
|
||||
|
||||
if (_.xor(customStorage.requiredFns, Object.keys(_.pick(Object.getPrototypeOf(customStorage), customStorage.requiredFns))).length) {
|
||||
throw new errors.IncorrectUsageError({
|
||||
throw new common.errors.IncorrectUsageError({
|
||||
message: 'Your storage adapter does not provide the minimum required functions.'
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
config = require('./config'),
|
||||
events = require('./lib/common/events'),
|
||||
Analytics = require('analytics-node'),
|
||||
config = require('./config'),
|
||||
common = require('./lib/common'),
|
||||
analytics;
|
||||
|
||||
module.exports.init = function () {
|
||||
|
@ -62,7 +62,7 @@ module.exports.init = function () {
|
|||
];
|
||||
|
||||
_.each(toTrack, function (track) {
|
||||
events.on(track.event, function () {
|
||||
common.events.on(track.event, function () {
|
||||
analytics.track(_.extend(trackDefaults, {event: prefix + track.name}));
|
||||
});
|
||||
});
|
||||
|
|
|
@ -8,10 +8,7 @@ var Promise = require('bluebird'),
|
|||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
config = require('../config'),
|
||||
errors = require('../lib/common/errors'),
|
||||
events = require('../lib/common/events'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
logging = require('../lib/common/logging'),
|
||||
common = require('../lib/common'),
|
||||
spamPrevention = require('../web/middleware/api/spam-prevention'),
|
||||
mailAPI = require('./mail'),
|
||||
settingsAPI = require('./settings'),
|
||||
|
@ -42,11 +39,11 @@ function assertSetupCompleted(status) {
|
|||
return __;
|
||||
}
|
||||
|
||||
var completed = i18n.t('errors.api.authentication.setupAlreadyCompleted'),
|
||||
notCompleted = i18n.t('errors.api.authentication.setupMustBeCompleted');
|
||||
var completed = common.i18n.t('errors.api.authentication.setupAlreadyCompleted'),
|
||||
notCompleted = common.i18n.t('errors.api.authentication.setupMustBeCompleted');
|
||||
|
||||
function throwReason(reason) {
|
||||
throw new errors.NoPermissionError({message: reason});
|
||||
throw new common.errors.NoPermissionError({message: reason});
|
||||
}
|
||||
|
||||
if (isSetup) {
|
||||
|
@ -81,8 +78,8 @@ function setupTasks(setupData) {
|
|||
|
||||
return User.findOne({role: 'Owner', status: 'all'}).then(function then(owner) {
|
||||
if (!owner) {
|
||||
throw new errors.GhostError({
|
||||
message: i18n.t('errors.api.authentication.setupUnableToRun')
|
||||
throw new common.errors.GhostError({
|
||||
message: common.i18n.t('errors.api.authentication.setupUnableToRun')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -107,7 +104,7 @@ function setupTasks(setupData) {
|
|||
|
||||
userSettings = [
|
||||
{key: 'title', value: blogTitle.trim()},
|
||||
{key: 'description', value: i18n.t('common.api.authentication.sampleBlogDescription')}
|
||||
{key: 'description', value: common.i18n.t('common.api.authentication.sampleBlogDescription')}
|
||||
];
|
||||
|
||||
return settingsAPI.edit({settings: userSettings}, context).return(user);
|
||||
|
@ -146,8 +143,8 @@ authentication = {
|
|||
var email = data.passwordreset[0].email;
|
||||
|
||||
if (typeof email !== 'string' || !validator.isEmail(email)) {
|
||||
throw new errors.BadRequestError({
|
||||
message: i18n.t('errors.api.authentication.noEmailProvided')
|
||||
throw new common.errors.BadRequestError({
|
||||
message: common.i18n.t('errors.api.authentication.noEmailProvided')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -167,7 +164,7 @@ authentication = {
|
|||
})
|
||||
.then(function fetchedUser(user) {
|
||||
if (!user) {
|
||||
throw new errors.NotFoundError({message: i18n.t('errors.api.users.userNotFound')});
|
||||
throw new common.errors.NotFoundError({message: common.i18n.t('errors.api.users.userNotFound')});
|
||||
}
|
||||
|
||||
token = globalUtils.tokens.resetToken.generateHash({
|
||||
|
@ -198,7 +195,7 @@ authentication = {
|
|||
mail: [{
|
||||
message: {
|
||||
to: data.email,
|
||||
subject: i18n.t('common.api.authentication.mail.resetPassword'),
|
||||
subject: common.i18n.t('common.api.authentication.mail.resetPassword'),
|
||||
html: content.html,
|
||||
text: content.text
|
||||
},
|
||||
|
@ -213,7 +210,7 @@ authentication = {
|
|||
function formatResponse() {
|
||||
return {
|
||||
passwordreset: [
|
||||
{message: i18n.t('common.api.authentication.mail.checkEmailForInstructions')}
|
||||
{message: common.i18n.t('common.api.authentication.mail.checkEmailForInstructions')}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
@ -244,8 +241,8 @@ authentication = {
|
|||
var data = options.data.passwordreset[0];
|
||||
|
||||
if (data.newPassword !== data.ne2Password) {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('errors.models.user.newPasswordsDoNotMatch')
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.models.user.newPasswordsDoNotMatch')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -261,8 +258,8 @@ authentication = {
|
|||
});
|
||||
|
||||
if (!tokenParts) {
|
||||
return Promise.reject(new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.api.common.invalidTokenStructure')
|
||||
return Promise.reject(new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.api.common.invalidTokenStructure')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -273,8 +270,8 @@ authentication = {
|
|||
function protectBruteForce(options) {
|
||||
if (tokenSecurity[tokenParts.email + '+' + tokenParts.expires] &&
|
||||
tokenSecurity[tokenParts.email + '+' + tokenParts.expires].count >= 10) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
message: i18n.t('errors.models.user.tokenLocked')
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.models.user.tokenLocked')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -295,7 +292,7 @@ authentication = {
|
|||
})
|
||||
.then(function fetchedUser(user) {
|
||||
if (!user) {
|
||||
throw new errors.NotFoundError({message: i18n.t('errors.api.users.userNotFound')});
|
||||
throw new common.errors.NotFoundError({message: common.i18n.t('errors.api.users.userNotFound')});
|
||||
}
|
||||
|
||||
tokenIsCorrect = globalUtils.tokens.resetToken.compare({
|
||||
|
@ -305,8 +302,8 @@ authentication = {
|
|||
});
|
||||
|
||||
if (!tokenIsCorrect) {
|
||||
return Promise.reject(new errors.BadRequestError({
|
||||
message: i18n.t('errors.api.common.invalidTokenStructure')
|
||||
return Promise.reject(new common.errors.BadRequestError({
|
||||
message: common.i18n.t('errors.api.common.invalidTokenStructure')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -322,21 +319,21 @@ authentication = {
|
|||
updatedUser.set('status', 'active');
|
||||
return updatedUser.save(options);
|
||||
})
|
||||
.catch(errors.ValidationError, function (err) {
|
||||
.catch(common.errors.ValidationError, function (err) {
|
||||
return Promise.reject(err);
|
||||
})
|
||||
.catch(function (err) {
|
||||
if (errors.utils.isIgnitionError(err)) {
|
||||
if (common.errors.utils.isIgnitionError(err)) {
|
||||
return Promise.reject(err);
|
||||
}
|
||||
return Promise.reject(new errors.UnauthorizedError({err: err}));
|
||||
return Promise.reject(new common.errors.UnauthorizedError({err: err}));
|
||||
});
|
||||
}
|
||||
|
||||
function formatResponse() {
|
||||
return {
|
||||
passwordreset: [
|
||||
{message: i18n.t('common.api.authentication.mail.passwordChanged')}
|
||||
{message: common.i18n.t('common.api.authentication.mail.passwordChanged')}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
@ -365,19 +362,19 @@ authentication = {
|
|||
return apiUtils.checkObject(invitation, 'invitation')
|
||||
.then(function () {
|
||||
if (!invitation.invitation[0].token) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.authentication.noTokenProvided')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.authentication.noTokenProvided')}));
|
||||
}
|
||||
|
||||
if (!invitation.invitation[0].email) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.authentication.noEmailProvided')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.authentication.noEmailProvided')}));
|
||||
}
|
||||
|
||||
if (!invitation.invitation[0].password) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.authentication.noPasswordProvided')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.authentication.noPasswordProvided')}));
|
||||
}
|
||||
|
||||
if (!invitation.invitation[0].name) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.authentication.noNameProvided')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.authentication.noNameProvided')}));
|
||||
}
|
||||
|
||||
return invitation;
|
||||
|
@ -392,11 +389,11 @@ authentication = {
|
|||
invite = _invite;
|
||||
|
||||
if (!invite) {
|
||||
throw new errors.NotFoundError({message: i18n.t('errors.api.invites.inviteNotFound')});
|
||||
throw new common.errors.NotFoundError({message: common.i18n.t('errors.api.invites.inviteNotFound')});
|
||||
}
|
||||
|
||||
if (invite.get('expires') < Date.now()) {
|
||||
throw new errors.NotFoundError({message: i18n.t('errors.api.invites.inviteExpired')});
|
||||
throw new common.errors.NotFoundError({message: common.i18n.t('errors.api.invites.inviteExpired')});
|
||||
}
|
||||
|
||||
return models.User.add({
|
||||
|
@ -414,7 +411,7 @@ authentication = {
|
|||
function formatResponse() {
|
||||
return {
|
||||
invitation: [
|
||||
{message: i18n.t('common.api.authentication.mail.invitationAccepted')}
|
||||
{message: common.i18n.t('common.api.authentication.mail.invitationAccepted')}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
@ -442,8 +439,8 @@ authentication = {
|
|||
var email = options.email;
|
||||
|
||||
if (typeof email !== 'string' || !validator.isEmail(email)) {
|
||||
throw new errors.BadRequestError({
|
||||
message: i18n.t('errors.api.authentication.invalidEmailReceived')
|
||||
throw new common.errors.BadRequestError({
|
||||
message: common.i18n.t('errors.api.authentication.invalidEmailReceived')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -486,15 +483,17 @@ authentication = {
|
|||
}
|
||||
|
||||
function formatResponse(isSetup) {
|
||||
return {setup: [
|
||||
{
|
||||
status: isSetup,
|
||||
// Pre-populate from config if, and only if the values exist in config.
|
||||
title: config.title || undefined,
|
||||
name: config.user_name || undefined,
|
||||
email: config.user_email || undefined
|
||||
}
|
||||
]};
|
||||
return {
|
||||
setup: [
|
||||
{
|
||||
status: isSetup,
|
||||
// Pre-populate from config if, and only if the values exist in config.
|
||||
title: config.title || undefined,
|
||||
name: config.user_name || undefined,
|
||||
email: config.user_email || undefined
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
tasks = [
|
||||
|
@ -522,13 +521,13 @@ authentication = {
|
|||
ownerEmail: setupUser.email
|
||||
};
|
||||
|
||||
events.emit('setup.completed', setupUser);
|
||||
common.events.emit('setup.completed', setupUser);
|
||||
|
||||
return mail.utils.generateContent({data: data, template: 'welcome'})
|
||||
.then(function then(content) {
|
||||
var message = {
|
||||
to: setupUser.email,
|
||||
subject: i18n.t('common.api.authentication.mail.yourNewGhostBlog'),
|
||||
subject: common.i18n.t('common.api.authentication.mail.yourNewGhostBlog'),
|
||||
html: content.html,
|
||||
text: content.text
|
||||
},
|
||||
|
@ -541,8 +540,8 @@ authentication = {
|
|||
|
||||
mailAPI.send(payload, {context: {internal: true}})
|
||||
.catch(function (err) {
|
||||
err.context = i18n.t('errors.api.authentication.unableToSendWelcomeEmail');
|
||||
logging.error(err);
|
||||
err.context = common.i18n.t('errors.api.authentication.unableToSendWelcomeEmail');
|
||||
common.logging.error(err);
|
||||
});
|
||||
})
|
||||
.return(setupUser);
|
||||
|
@ -574,7 +573,7 @@ authentication = {
|
|||
|
||||
function processArgs(setupDetails, options) {
|
||||
if (!options.context || !options.context.user) {
|
||||
throw new errors.NoPermissionError({message: i18n.t('errors.api.authentication.notTheBlogOwner')});
|
||||
throw new common.errors.NoPermissionError({message: common.i18n.t('errors.api.authentication.notTheBlogOwner')});
|
||||
}
|
||||
|
||||
return _.assign({setupDetails: setupDetails}, options);
|
||||
|
@ -584,7 +583,7 @@ authentication = {
|
|||
return models.User.findOne({role: 'Owner', status: 'all'})
|
||||
.then(function (owner) {
|
||||
if (owner.id !== options.context.user) {
|
||||
throw new errors.NoPermissionError({message: i18n.t('errors.api.authentication.notTheBlogOwner')});
|
||||
throw new common.errors.NoPermissionError({message: common.i18n.t('errors.api.authentication.notTheBlogOwner')});
|
||||
}
|
||||
|
||||
return options.setupDetails;
|
||||
|
@ -634,15 +633,15 @@ authentication = {
|
|||
if (!providers.length) {
|
||||
return {
|
||||
token: tokenDetails.token,
|
||||
error: i18n.t('errors.api.authentication.invalidTokenProvided')
|
||||
error: common.i18n.t('errors.api.authentication.invalidTokenProvided')
|
||||
};
|
||||
}
|
||||
|
||||
return destroyToken(providers.pop(), options, providers);
|
||||
})
|
||||
.catch(function () {
|
||||
throw new errors.TokenRevocationError({
|
||||
message: i18n.t('errors.api.authentication.tokenRevocationFailed')
|
||||
throw new common.errors.TokenRevocationError({
|
||||
message: common.i18n.t('errors.api.authentication.tokenRevocationFailed')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -5,8 +5,7 @@ var Promise = require('bluebird'),
|
|||
pipeline = require('../utils/pipeline'),
|
||||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
docName = 'clients',
|
||||
clients;
|
||||
|
||||
|
@ -39,8 +38,8 @@ clients = {
|
|||
return models.Client.findOne(options.data, _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('common.api.clients.clientNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('common.api.clients.clientNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
|
@ -39,7 +39,7 @@ function getBaseConfig() {
|
|||
*
|
||||
* We need to load the client credentials dynamically.
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
configuration = {
|
||||
|
||||
|
|
|
@ -10,7 +10,7 @@ var Promise = require('bluebird'),
|
|||
backupDatabase = require('../data/db/backup'),
|
||||
models = require('../models'),
|
||||
config = require('../config'),
|
||||
errors = require('../lib/common/errors'),
|
||||
common = require('../lib/common'),
|
||||
urlService = require('../services/url'),
|
||||
docName = 'db',
|
||||
db;
|
||||
|
@ -18,7 +18,7 @@ var Promise = require('bluebird'),
|
|||
/**
|
||||
* ## DB API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
db = {
|
||||
/**
|
||||
|
@ -62,7 +62,7 @@ db = {
|
|||
return exporter.doExport().then(function (exportedData) {
|
||||
return {db: [exportedData]};
|
||||
}).catch(function (err) {
|
||||
return Promise.reject(new errors.GhostError({err: err}));
|
||||
return Promise.reject(new common.errors.GhostError({err: err}));
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -124,7 +124,7 @@ db = {
|
|||
return Collection.invokeThen('destroy', queryOpts);
|
||||
}).return({db: []})
|
||||
.catch(function (err) {
|
||||
throw new errors.GhostError({err: err});
|
||||
throw new common.errors.GhostError({err: err});
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -6,9 +6,7 @@ var Promise = require('bluebird'),
|
|||
urlService = require('../services/url'),
|
||||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
logging = require('../lib/common/logging'),
|
||||
common = require('../lib/common'),
|
||||
mailAPI = require('./mail'),
|
||||
settingsAPI = require('./settings'),
|
||||
docName = 'invites',
|
||||
|
@ -41,8 +39,8 @@ invites = {
|
|||
return models.Invite.findOne(options.data, _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.invites.inviteNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.invites.inviteNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -69,7 +67,7 @@ invites = {
|
|||
return models.Invite.findOne({id: options.id}, _.omit(options, ['data']))
|
||||
.then(function (invite) {
|
||||
if (!invite) {
|
||||
throw new errors.NotFoundError({message: i18n.t('errors.api.invites.inviteNotFound')});
|
||||
throw new common.errors.NotFoundError({message: common.i18n.t('errors.api.invites.inviteNotFound')});
|
||||
}
|
||||
|
||||
return invite.destroy(options).return(null);
|
||||
|
@ -118,7 +116,7 @@ invites = {
|
|||
mail: [{
|
||||
message: {
|
||||
to: invite.get('email'),
|
||||
subject: i18n.t('common.api.users.mail.invitedByName', {
|
||||
subject: common.i18n.t('common.api.users.mail.invitedByName', {
|
||||
invitedByName: emailData.invitedByName,
|
||||
blogName: emailData.blogName
|
||||
}),
|
||||
|
@ -142,9 +140,9 @@ invites = {
|
|||
};
|
||||
}).catch(function (error) {
|
||||
if (error && error.errorType === 'EmailError') {
|
||||
error.message = i18n.t('errors.api.invites.errorSendingEmail.error', {message: error.message}) + ' ' +
|
||||
i18n.t('errors.api.invites.errorSendingEmail.help');
|
||||
logging.warn(error.message);
|
||||
error.message = common.i18n.t('errors.api.invites.errorSendingEmail.error', {message: error.message}) + ' ' +
|
||||
common.i18n.t('errors.api.invites.errorSendingEmail.help');
|
||||
common.logging.warn(error.message);
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
|
@ -169,11 +167,11 @@ invites = {
|
|||
|
||||
function validation(options) {
|
||||
if (!options.data.invites[0].email) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.invites.emailIsRequired')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.invites.emailIsRequired')}));
|
||||
}
|
||||
|
||||
if (!options.data.invites[0].role_id) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.invites.roleIsRequired')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.invites.roleIsRequired')}));
|
||||
}
|
||||
|
||||
// @TODO remove when we have a new permission unit
|
||||
|
@ -183,11 +181,11 @@ invites = {
|
|||
// As we are looking forward to replace the permission system completely, we do not add a hack here
|
||||
return models.Role.findOne({id: options.data.invites[0].role_id}).then(function (roleToInvite) {
|
||||
if (!roleToInvite) {
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.invites.roleNotFound')}));
|
||||
return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.api.invites.roleNotFound')}));
|
||||
}
|
||||
|
||||
if (roleToInvite.get('name') === 'Owner') {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.api.invites.notAllowedToInviteOwner')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.api.invites.notAllowedToInviteOwner')}));
|
||||
}
|
||||
|
||||
var loggedInUserRole = loggedInUser.related('roles').models[0].get('name'),
|
||||
|
@ -200,8 +198,8 @@ invites = {
|
|||
}
|
||||
|
||||
if (allowed.indexOf(roleToInvite.get('name')) === -1) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
message: i18n.t('errors.api.invites.notAllowedToInvite')
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.api.invites.notAllowedToInvite')
|
||||
}));
|
||||
}
|
||||
}).then(function () {
|
||||
|
@ -213,8 +211,8 @@ invites = {
|
|||
return models.User.findOne({email: options.data.invites[0].email}, options)
|
||||
.then(function (user) {
|
||||
if (user) {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('errors.api.users.userAlreadyRegistered')
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.api.users.userAlreadyRegistered')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -226,7 +224,7 @@ invites = {
|
|||
return models.User.findOne({id: loggedInUser}, _.merge({}, options, {include: ['roles']}))
|
||||
.then(function (user) {
|
||||
if (!user) {
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.users.userNotFound')}));
|
||||
return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.api.users.userNotFound')}));
|
||||
}
|
||||
|
||||
loggedInUser = user;
|
||||
|
|
|
@ -5,7 +5,7 @@ var Promise = require('bluebird'),
|
|||
pipeline = require('../utils/pipeline'),
|
||||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
mail = require('../mail'),
|
||||
notificationsAPI = require('./notifications'),
|
||||
docName = 'mail',
|
||||
|
@ -23,14 +23,16 @@ function sendMail(object) {
|
|||
return mailer.send(object.mail[0].message).catch(function (err) {
|
||||
if (mailer.state.usingDirect) {
|
||||
notificationsAPI.add(
|
||||
{notifications: [{
|
||||
type: 'warn',
|
||||
message: [
|
||||
i18n.t('warnings.index.unableToSendEmail'),
|
||||
i18n.t('common.seeLinkForInstructions',
|
||||
{link: '<a href=\'https://docs.ghost.org/v1/docs/mail-config\' target=\'_blank\'>Checkout our mail configuration docs!</a>'})
|
||||
].join(' ')
|
||||
}]},
|
||||
{
|
||||
notifications: [{
|
||||
type: 'warn',
|
||||
message: [
|
||||
common.i18n.t('warnings.index.unableToSendEmail'),
|
||||
common.i18n.t('common.seeLinkForInstructions',
|
||||
{link: '<a href=\'https://docs.ghost.org/v1/docs/mail-config\' target=\'_blank\'>Checkout our mail configuration docs!</a>'})
|
||||
].join(' ')
|
||||
}]
|
||||
},
|
||||
{context: {internal: true}}
|
||||
);
|
||||
}
|
||||
|
@ -42,7 +44,7 @@ function sendMail(object) {
|
|||
/**
|
||||
* ## Mail API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
* @typedef Mail
|
||||
* @param mail
|
||||
*/
|
||||
|
@ -120,7 +122,7 @@ apiMail = {
|
|||
mail: [{
|
||||
message: {
|
||||
to: result.get('email'),
|
||||
subject: i18n.t('common.api.mail.testGhostEmail'),
|
||||
subject: common.i18n.t('common.api.mail.testGhostEmail'),
|
||||
html: content.html,
|
||||
text: content.text
|
||||
}
|
||||
|
|
|
@ -7,8 +7,7 @@ var Promise = require('bluebird'),
|
|||
permissions = require('../permissions'),
|
||||
canThis = permissions.canThis,
|
||||
apiUtils = require('./utils'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
settingsAPI = require('./settings'),
|
||||
// Holds the persistent notifications
|
||||
notificationsStore = [],
|
||||
|
@ -17,7 +16,7 @@ var Promise = require('bluebird'),
|
|||
/**
|
||||
* ## Notification API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
notifications = {
|
||||
|
||||
|
@ -30,7 +29,7 @@ notifications = {
|
|||
return canThis(options.context).browse.notification().then(function () {
|
||||
return {notifications: notificationsStore};
|
||||
}, function () {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.api.notifications.noPermissionToBrowseNotif')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.api.notifications.noPermissionToBrowseNotif')}));
|
||||
});
|
||||
},
|
||||
|
||||
|
@ -70,7 +69,7 @@ notifications = {
|
|||
return canThis(options.context).add.notification().then(function () {
|
||||
return options;
|
||||
}, function () {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.api.notifications.noPermissionToAddNotif')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.api.notifications.noPermissionToAddNotif')}));
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -137,7 +136,12 @@ notifications = {
|
|||
return settingsAPI.read({key: 'seen_notifications', context: context}).then(function then(response) {
|
||||
var seenNotifications = JSON.parse(response.settings[0].value);
|
||||
seenNotifications = _.uniqBy(seenNotifications.concat([notification.id]));
|
||||
return settingsAPI.edit({settings: [{key: 'seen_notifications', value: seenNotifications}]}, {context: context});
|
||||
return settingsAPI.edit({
|
||||
settings: [{
|
||||
key: 'seen_notifications',
|
||||
value: seenNotifications
|
||||
}]
|
||||
}, {context: context});
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -151,7 +155,7 @@ notifications = {
|
|||
return canThis(options.context).destroy.notification().then(function () {
|
||||
return options;
|
||||
}, function () {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.api.notifications.noPermissionToDestroyNotif')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.api.notifications.noPermissionToDestroyNotif')}));
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -162,12 +166,12 @@ notifications = {
|
|||
|
||||
if (notification && !notification.dismissible) {
|
||||
return Promise.reject(
|
||||
new errors.NoPermissionError({message: i18n.t('errors.api.notifications.noPermissionToDismissNotif')})
|
||||
new common.errors.NoPermissionError({message: common.i18n.t('errors.api.notifications.noPermissionToDismissNotif')})
|
||||
);
|
||||
}
|
||||
|
||||
if (!notification) {
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.notifications.notificationDoesNotExist')}));
|
||||
return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.api.notifications.notificationDoesNotExist')}));
|
||||
}
|
||||
|
||||
notificationsStore = _.reject(notificationsStore, function (element) {
|
||||
|
@ -200,9 +204,9 @@ notifications = {
|
|||
notificationsStore = [];
|
||||
return notificationsStore;
|
||||
}, function (err) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
err: err,
|
||||
context: i18n.t('errors.api.notifications.noPermissionToDestroyNotif')
|
||||
context: common.i18n.t('errors.api.notifications.noPermissionToDestroyNotif')
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
|
|
@ -5,8 +5,7 @@ var Promise = require('bluebird'),
|
|||
pipeline = require('../utils/pipeline'),
|
||||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
docName = 'posts',
|
||||
allowedIncludes = [
|
||||
'created_by', 'updated_by', 'published_by', 'author', 'tags', 'fields'
|
||||
|
@ -17,7 +16,7 @@ var Promise = require('bluebird'),
|
|||
/**
|
||||
* ### Posts API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
|
||||
posts = {
|
||||
|
@ -93,8 +92,8 @@ posts = {
|
|||
return models.Post.findOne(options.data, _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.posts.postNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.posts.postNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -140,8 +139,8 @@ posts = {
|
|||
return models.Post.edit(options.data.posts[0], _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.posts.postNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.posts.postNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -239,7 +238,7 @@ posts = {
|
|||
return Post.findOne(data, fetchOpts).then(function () {
|
||||
return Post.destroy(options).return(null);
|
||||
}).catch(Post.NotFoundError, function () {
|
||||
throw new errors.NotFoundError({message: i18n.t('errors.api.posts.postNotFound')});
|
||||
throw new common.errors.NotFoundError({message: common.i18n.t('errors.api.posts.postNotFound')});
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -5,8 +5,7 @@ const fs = require('fs-extra'),
|
|||
moment = require('moment'),
|
||||
path = require('path'),
|
||||
config = require('../config'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
globalUtils = require('../utils'),
|
||||
apiUtils = require('./utils'),
|
||||
customRedirectsMiddleware = require('../web/middleware/custom-redirects');
|
||||
|
@ -22,8 +21,8 @@ _private.readRedirectsFile = function readRedirectsFile(customRedirectsPath) {
|
|||
try {
|
||||
content = JSON.parse(content);
|
||||
} catch (err) {
|
||||
throw new errors.BadRequestError({
|
||||
message: i18n.t('errors.general.jsonParse', {context: err.message})
|
||||
throw new common.errors.BadRequestError({
|
||||
message: common.i18n.t('errors.general.jsonParse', {context: err.message})
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -34,11 +33,11 @@ _private.readRedirectsFile = function readRedirectsFile(customRedirectsPath) {
|
|||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
if (errors.utils.isIgnitionError(err)) {
|
||||
if (common.errors.utils.isIgnitionError(err)) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
throw new errors.NotFoundError({
|
||||
throw new common.errors.NotFoundError({
|
||||
err: err
|
||||
});
|
||||
});
|
||||
|
|
|
@ -12,7 +12,7 @@ var Promise = require('bluebird'),
|
|||
/**
|
||||
* ## Roles API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
roles = {
|
||||
/**
|
||||
|
|
|
@ -5,8 +5,7 @@ var Promise = require('bluebird'),
|
|||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
config = require('../config'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
postsAPI = require('../api/posts');
|
||||
|
||||
/**
|
||||
|
@ -29,7 +28,7 @@ exports.publishPost = function publishPost(object, options) {
|
|||
|
||||
// CASE: only the scheduler client is allowed to publish (hardcoded because of missing client permission system)
|
||||
if (!options.context || !options.context.client || options.context.client !== 'ghost-scheduler') {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.permissions.noPermissionToAction')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.permissions.noPermissionToAction')}));
|
||||
}
|
||||
|
||||
options.context = {internal: true};
|
||||
|
@ -52,11 +51,11 @@ exports.publishPost = function publishPost(object, options) {
|
|||
publishedAtMoment = moment(post.published_at);
|
||||
|
||||
if (publishedAtMoment.diff(moment(), 'minutes') > publishAPostBySchedulerToleranceInMinutes) {
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.job.notFound')}));
|
||||
return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.api.job.notFound')}));
|
||||
}
|
||||
|
||||
if (publishedAtMoment.diff(moment(), 'minutes') < publishAPostBySchedulerToleranceInMinutes * -1 && object.force !== true) {
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.job.publishInThePast')}));
|
||||
return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.api.job.publishInThePast')}));
|
||||
}
|
||||
|
||||
return postsAPI.edit(
|
||||
|
|
|
@ -5,8 +5,7 @@ var Promise = require('bluebird'),
|
|||
models = require('../models'),
|
||||
canThis = require('../permissions').canThis,
|
||||
apiUtils = require('./utils'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
settingsCache = require('../settings/cache'),
|
||||
docName = 'settings',
|
||||
settings,
|
||||
|
@ -83,28 +82,28 @@ canEditAllSettings = function (settingsInfo, options) {
|
|||
var checkSettingPermissions = function checkSettingPermissions(setting) {
|
||||
if (setting.type === 'core' && !(options.context && options.context.internal)) {
|
||||
return Promise.reject(
|
||||
new errors.NoPermissionError({message: i18n.t('errors.api.settings.accessCoreSettingFromExtReq')})
|
||||
new common.errors.NoPermissionError({message: common.i18n.t('errors.api.settings.accessCoreSettingFromExtReq')})
|
||||
);
|
||||
}
|
||||
|
||||
return canThis(options.context).edit.setting(setting.key).catch(function () {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.api.settings.noPermissionToEditSettings')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.api.settings.noPermissionToEditSettings')}));
|
||||
});
|
||||
},
|
||||
checks = _.map(settingsInfo, function (settingInfo) {
|
||||
var setting = settingsCache.get(settingInfo.key, {resolve: false});
|
||||
|
||||
if (!setting) {
|
||||
return Promise.reject(new errors.NotFoundError(
|
||||
{message: i18n.t('errors.api.settings.problemFindingSetting', {key: settingInfo.key})}
|
||||
return Promise.reject(new common.errors.NotFoundError(
|
||||
{message: common.i18n.t('errors.api.settings.problemFindingSetting', {key: settingInfo.key})}
|
||||
));
|
||||
}
|
||||
|
||||
if (setting.key === 'active_theme') {
|
||||
return Promise.reject(
|
||||
new errors.BadRequestError({
|
||||
message: i18n.t('errors.api.settings.activeThemeSetViaAPI.error'),
|
||||
help: i18n.t('errors.api.settings.activeThemeSetViaAPI.help')
|
||||
new common.errors.BadRequestError({
|
||||
message: common.i18n.t('errors.api.settings.activeThemeSetViaAPI.error'),
|
||||
help: common.i18n.t('errors.api.settings.activeThemeSetViaAPI.help')
|
||||
})
|
||||
);
|
||||
}
|
||||
|
@ -118,7 +117,7 @@ canEditAllSettings = function (settingsInfo, options) {
|
|||
/**
|
||||
* ## Settings API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
settings = {
|
||||
|
||||
|
@ -134,14 +133,18 @@ settings = {
|
|||
|
||||
// If there is no context, return only blog settings
|
||||
if (!options.context) {
|
||||
return Promise.resolve(_.filter(result.settings, function (setting) { return setting.type === 'blog'; }));
|
||||
return Promise.resolve(_.filter(result.settings, function (setting) {
|
||||
return setting.type === 'blog';
|
||||
}));
|
||||
}
|
||||
|
||||
// Otherwise return whatever this context is allowed to browse
|
||||
return canThis(options.context).browse.setting().then(function () {
|
||||
// Omit core settings unless internal request
|
||||
if (!options.context.internal) {
|
||||
result.settings = _.filter(result.settings, function (setting) { return setting.type !== 'core'; });
|
||||
result.settings = _.filter(result.settings, function (setting) {
|
||||
return setting.type !== 'core';
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
|
@ -162,8 +165,8 @@ settings = {
|
|||
result = {};
|
||||
|
||||
if (!setting) {
|
||||
return Promise.reject(new errors.NotFoundError(
|
||||
{message: i18n.t('errors.api.settings.problemFindingSetting', {key: options.key})}
|
||||
return Promise.reject(new common.errors.NotFoundError(
|
||||
{message: common.i18n.t('errors.api.settings.problemFindingSetting', {key: options.key})}
|
||||
));
|
||||
}
|
||||
|
||||
|
@ -171,7 +174,7 @@ settings = {
|
|||
|
||||
if (setting.type === 'core' && !(options.context && options.context.internal)) {
|
||||
return Promise.reject(
|
||||
new errors.NoPermissionError({message: i18n.t('errors.api.settings.accessCoreSettingFromExtReq')})
|
||||
new common.errors.NoPermissionError({message: common.i18n.t('errors.api.settings.accessCoreSettingFromExtReq')})
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -182,7 +185,7 @@ settings = {
|
|||
return canThis(options.context).read.setting(options.key).then(function () {
|
||||
return settingsResult(result);
|
||||
}, function () {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.api.settings.noPermissionToReadSettings')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.api.settings.noPermissionToReadSettings')}));
|
||||
});
|
||||
},
|
||||
|
||||
|
@ -210,7 +213,9 @@ settings = {
|
|||
}
|
||||
});
|
||||
|
||||
type = _.find(object.settings, function (setting) { return setting.key === 'type'; });
|
||||
type = _.find(object.settings, function (setting) {
|
||||
return setting.key === 'type';
|
||||
});
|
||||
if (_.isObject(type)) {
|
||||
type = type.value;
|
||||
}
|
||||
|
|
|
@ -1,13 +1,13 @@
|
|||
// # Slack API
|
||||
// API for sending Test Notifications to Slack
|
||||
var Promise = require('bluebird'),
|
||||
events = require('../lib/common/events'),
|
||||
common = require('../lib/common'),
|
||||
slack;
|
||||
|
||||
/**
|
||||
* ## Slack API Method
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
* @typedef Slack
|
||||
* @param slack
|
||||
*/
|
||||
|
@ -19,7 +19,7 @@ slack = {
|
|||
* @public
|
||||
*/
|
||||
sendTest: function () {
|
||||
events.emit('slack.test');
|
||||
common.events.emit('slack.test');
|
||||
return Promise.resolve();
|
||||
}
|
||||
};
|
||||
|
|
|
@ -4,8 +4,7 @@ var Promise = require('bluebird'),
|
|||
pipeline = require('../utils/pipeline'),
|
||||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
docName = 'slugs',
|
||||
slugs,
|
||||
allowedTypes;
|
||||
|
@ -13,7 +12,7 @@ var Promise = require('bluebird'),
|
|||
/**
|
||||
* ## Slugs API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
slugs = {
|
||||
|
||||
|
@ -45,7 +44,7 @@ slugs = {
|
|||
*/
|
||||
function checkAllowedTypes(options) {
|
||||
if (allowedTypes[options.type] === undefined) {
|
||||
return Promise.reject(new errors.BadRequestError({message: i18n.t('errors.api.slugs.unknownSlugType', {type: options.type})}));
|
||||
return Promise.reject(new common.errors.BadRequestError({message: common.i18n.t('errors.api.slugs.unknownSlugType', {type: options.type})}));
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
@ -60,8 +59,8 @@ slugs = {
|
|||
return models.Base.Model.generateSlug(allowedTypes[options.type], options.data.name, {status: 'all'})
|
||||
.then(function onModelResponse(slug) {
|
||||
if (!slug) {
|
||||
return Promise.reject(new errors.GhostError({
|
||||
message: i18n.t('errors.api.slugs.couldNotGenerateSlug')
|
||||
return Promise.reject(new common.errors.GhostError({
|
||||
message: common.i18n.t('errors.api.slugs.couldNotGenerateSlug')
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
|
@ -7,15 +7,14 @@ var Promise = require('bluebird'),
|
|||
globalUtils = require('../utils'),
|
||||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
docName = 'subscribers',
|
||||
subscribers;
|
||||
|
||||
/**
|
||||
* ### Subscribers API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
subscribers = {
|
||||
/**
|
||||
|
@ -66,8 +65,8 @@ subscribers = {
|
|||
return models.Subscriber.findOne(options.data, _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.subscribers.subscriberNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.subscribers.subscriberNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -109,12 +108,12 @@ subscribers = {
|
|||
// we don't expose this information
|
||||
return Promise.resolve(subscriber);
|
||||
} else if (subscriber) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.subscribers.subscriberAlreadyExists')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.subscribers.subscriberAlreadyExists')}));
|
||||
}
|
||||
|
||||
return models.Subscriber.add(options.data.subscribers[0], _.omit(options, ['data'])).catch(function (error) {
|
||||
if (error.code && error.message.toLowerCase().indexOf('unique') !== -1) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.subscribers.subscriberAlreadyExists')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.subscribers.subscriberAlreadyExists')}));
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
|
@ -158,8 +157,8 @@ subscribers = {
|
|||
return models.Subscriber.edit(options.data.subscribers[0], _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.subscribers.subscriberNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.subscribers.subscriberNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -200,8 +199,8 @@ subscribers = {
|
|||
return models.Subscriber.getByEmail(options.email, options)
|
||||
.then(function (subscriber) {
|
||||
if (!subscriber) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.subscribers.subscriberNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.subscribers.subscriberNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -275,7 +274,7 @@ subscribers = {
|
|||
return models.Subscriber.findAll(options).then(function (data) {
|
||||
return formatCSV(data.toJSON(options));
|
||||
}).catch(function (err) {
|
||||
return Promise.reject(new errors.GhostError({err: err}));
|
||||
return Promise.reject(new common.errors.GhostError({err: err}));
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -318,7 +317,7 @@ subscribers = {
|
|||
if (inspection.isFulfilled()) {
|
||||
fulfilled = fulfilled + 1;
|
||||
} else {
|
||||
if (inspection.reason() instanceof errors.ValidationError) {
|
||||
if (inspection.reason() instanceof common.errors.ValidationError) {
|
||||
duplicates = duplicates + 1;
|
||||
} else {
|
||||
invalid = invalid + 1;
|
||||
|
|
|
@ -5,8 +5,7 @@ var Promise = require('bluebird'),
|
|||
pipeline = require('../utils/pipeline'),
|
||||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
docName = 'tags',
|
||||
allowedIncludes = ['count.posts'],
|
||||
tags;
|
||||
|
@ -14,7 +13,7 @@ var Promise = require('bluebird'),
|
|||
/**
|
||||
* ### Tags API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
tags = {
|
||||
/**
|
||||
|
@ -66,8 +65,8 @@ tags = {
|
|||
return models.Tag.findOne(options.data, _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.tags.tagNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.tags.tagNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -144,8 +143,8 @@ tags = {
|
|||
return models.Tag.edit(options.data.tags[0], _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.tags.tagNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.tags.tagNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
|
@ -4,10 +4,7 @@ var debug = require('ghost-ignition').debug('api:themes'),
|
|||
Promise = require('bluebird'),
|
||||
fs = require('fs-extra'),
|
||||
apiUtils = require('./utils'),
|
||||
errors = require('../lib/common/errors'),
|
||||
events = require('../lib/common/events'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
logging = require('../lib/common/logging'),
|
||||
common = require('../lib/common'),
|
||||
settingsModel = require('../models/settings').Settings,
|
||||
settingsCache = require('../settings/cache'),
|
||||
themeUtils = require('../themes'),
|
||||
|
@ -17,7 +14,7 @@ var debug = require('ghost-ignition').debug('api:themes'),
|
|||
/**
|
||||
* ## Themes API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
themes = {
|
||||
/**
|
||||
|
@ -28,7 +25,7 @@ themes = {
|
|||
*/
|
||||
browse: function browse(options) {
|
||||
return apiUtils
|
||||
// Permissions
|
||||
// Permissions
|
||||
.handlePermissions('themes', 'browse')(options)
|
||||
// Main action
|
||||
.then(function makeApiResult() {
|
||||
|
@ -47,15 +44,15 @@ themes = {
|
|||
checkedTheme;
|
||||
|
||||
return apiUtils
|
||||
// Permissions
|
||||
// Permissions
|
||||
.handlePermissions('themes', 'activate')(options)
|
||||
// Validation
|
||||
.then(function validateTheme() {
|
||||
loadedTheme = themeList.get(themeName);
|
||||
|
||||
if (!loadedTheme) {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('notices.data.validation.index.themeCannotBeActivated', {themeName: themeName}),
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('notices.data.validation.index.themeCannotBeActivated', {themeName: themeName}),
|
||||
context: 'active_theme'
|
||||
}));
|
||||
}
|
||||
|
@ -94,11 +91,11 @@ themes = {
|
|||
|
||||
// check if zip name is casper.zip
|
||||
if (zip.name === 'casper.zip') {
|
||||
throw new errors.ValidationError({message: i18n.t('errors.api.themes.overrideCasper')});
|
||||
throw new common.errors.ValidationError({message: common.i18n.t('errors.api.themes.overrideCasper')});
|
||||
}
|
||||
|
||||
return apiUtils
|
||||
// Permissions
|
||||
// Permissions
|
||||
.handlePermissions('themes', 'add')(options)
|
||||
// Validation
|
||||
.then(function validateTheme() {
|
||||
|
@ -118,7 +115,7 @@ themes = {
|
|||
}
|
||||
})
|
||||
.then(function storeNewTheme() {
|
||||
events.emit('theme.uploaded', zip.shortName);
|
||||
common.events.emit('theme.uploaded', zip.shortName);
|
||||
// store extracted theme
|
||||
return themeUtils.storage.save({
|
||||
name: zip.shortName,
|
||||
|
@ -148,7 +145,7 @@ themes = {
|
|||
// happens in background
|
||||
Promise.promisify(fs.remove)(zip.path)
|
||||
.catch(function (err) {
|
||||
logging.error(new errors.GhostError({err: err}));
|
||||
common.logging.error(new common.errors.GhostError({err: err}));
|
||||
});
|
||||
|
||||
// @TODO we should probably do this as part of saving the theme
|
||||
|
@ -157,7 +154,7 @@ themes = {
|
|||
if (checkedTheme) {
|
||||
Promise.promisify(fs.remove)(checkedTheme.path)
|
||||
.catch(function (err) {
|
||||
logging.error(new errors.GhostError({err: err}));
|
||||
common.logging.error(new common.errors.GhostError({err: err}));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
@ -168,14 +165,14 @@ themes = {
|
|||
theme = themeList.get(themeName);
|
||||
|
||||
if (!theme) {
|
||||
return Promise.reject(new errors.BadRequestError({message: i18n.t('errors.api.themes.invalidRequest')}));
|
||||
return Promise.reject(new common.errors.BadRequestError({message: common.i18n.t('errors.api.themes.invalidRequest')}));
|
||||
}
|
||||
|
||||
return apiUtils
|
||||
// Permissions
|
||||
// Permissions
|
||||
.handlePermissions('themes', 'read')(options)
|
||||
.then(function sendTheme() {
|
||||
events.emit('theme.downloaded', themeName);
|
||||
common.events.emit('theme.downloaded', themeName);
|
||||
return themeUtils.storage.serve({
|
||||
name: themeName
|
||||
});
|
||||
|
@ -191,22 +188,22 @@ themes = {
|
|||
theme;
|
||||
|
||||
return apiUtils
|
||||
// Permissions
|
||||
// Permissions
|
||||
.handlePermissions('themes', 'destroy')(options)
|
||||
// Validation
|
||||
.then(function validateTheme() {
|
||||
if (themeName === 'casper') {
|
||||
throw new errors.ValidationError({message: i18n.t('errors.api.themes.destroyCasper')});
|
||||
throw new common.errors.ValidationError({message: common.i18n.t('errors.api.themes.destroyCasper')});
|
||||
}
|
||||
|
||||
if (themeName === settingsCache.get('active_theme')) {
|
||||
throw new errors.ValidationError({message: i18n.t('errors.api.themes.destroyActive')});
|
||||
throw new common.errors.ValidationError({message: common.i18n.t('errors.api.themes.destroyActive')});
|
||||
}
|
||||
|
||||
theme = themeList.get(themeName);
|
||||
|
||||
if (!theme) {
|
||||
throw new errors.NotFoundError({message: i18n.t('errors.api.themes.themeDoesNotExist')});
|
||||
throw new common.errors.NotFoundError({message: common.i18n.t('errors.api.themes.themeDoesNotExist')});
|
||||
}
|
||||
|
||||
// Actually do the deletion here
|
||||
|
@ -215,7 +212,7 @@ themes = {
|
|||
// And some extra stuff to maintain state here
|
||||
.then(function deleteTheme() {
|
||||
themeList.del(themeName);
|
||||
events.emit('theme.deleted', themeName);
|
||||
common.events.emit('theme.deleted', themeName);
|
||||
// Delete returns an empty 204 response
|
||||
});
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ var Promise = require('bluebird'),
|
|||
/**
|
||||
* ## Upload API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
upload = {
|
||||
|
||||
|
|
|
@ -6,8 +6,7 @@ var Promise = require('bluebird'),
|
|||
apiUtils = require('./utils'),
|
||||
canThis = require('../permissions').canThis,
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
docName = 'users',
|
||||
// TODO: implement created_by, updated_by
|
||||
allowedIncludes = ['count.posts', 'permissions', 'roles', 'roles.permissions'],
|
||||
|
@ -16,7 +15,7 @@ var Promise = require('bluebird'),
|
|||
/**
|
||||
* ### Users API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
users = {
|
||||
/**
|
||||
|
@ -76,8 +75,8 @@ users = {
|
|||
return models.User.findOne(options.data, _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.users.userNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.users.userNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -137,8 +136,8 @@ users = {
|
|||
// CASE: can't edit my own status to inactive or locked
|
||||
if (options.id === options.context.user) {
|
||||
if (models.User.inactiveStates.indexOf(options.data.users[0].status) !== -1) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
message: i18n.t('errors.api.users.cannotChangeStatus')
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.api.users.cannotChangeStatus')
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
@ -159,8 +158,8 @@ users = {
|
|||
var contextRoleId = contextUser.related('roles').toJSON(options)[0].id;
|
||||
|
||||
if (roleId !== contextRoleId && editedUserId === contextUser.id) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
message: i18n.t('errors.api.users.cannotChangeOwnRole')
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.api.users.cannotChangeOwnRole')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -168,8 +167,8 @@ users = {
|
|||
if (contextUser.id !== owner.id) {
|
||||
if (editedUserId === owner.id) {
|
||||
if (owner.related('roles').at(0).id !== roleId) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
message: i18n.t('errors.api.users.cannotChangeOwnersRole')
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.api.users.cannotChangeOwnersRole')
|
||||
}));
|
||||
}
|
||||
} else if (roleId !== contextRoleId) {
|
||||
|
@ -183,9 +182,9 @@ users = {
|
|||
});
|
||||
});
|
||||
}).catch(function handleError(err) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
err: err,
|
||||
context: i18n.t('errors.api.users.noPermissionToEditUser')
|
||||
context: common.i18n.t('errors.api.users.noPermissionToEditUser')
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
@ -200,8 +199,8 @@ users = {
|
|||
return models.User.edit(options.data.users[0], _.omit(options, ['data']))
|
||||
.then(function onModelResponse(model) {
|
||||
if (!model) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.users.userNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.users.userNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -241,9 +240,9 @@ users = {
|
|||
options.status = 'all';
|
||||
return options;
|
||||
}).catch(function handleError(err) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
err: err,
|
||||
context: i18n.t('errors.api.users.noPermissionToDestroyUser')
|
||||
context: common.i18n.t('errors.api.users.noPermissionToDestroyUser')
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
@ -265,7 +264,7 @@ users = {
|
|||
return models.User.destroy(options);
|
||||
}).return(null);
|
||||
}).catch(function (err) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
err: err
|
||||
}));
|
||||
});
|
||||
|
@ -298,8 +297,8 @@ users = {
|
|||
var data = options.data.password[0];
|
||||
|
||||
if (data.newPassword !== data.ne2Password) {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('errors.models.user.newPasswordsDoNotMatch')
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.models.user.newPasswordsDoNotMatch')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -317,9 +316,9 @@ users = {
|
|||
return canThis(options.context).edit.user(options.data.password[0].user_id).then(function permissionGranted() {
|
||||
return options;
|
||||
}).catch(function (err) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
err: err,
|
||||
context: i18n.t('errors.api.users.noPermissionToChangeUsersPwd')
|
||||
context: common.i18n.t('errors.api.users.noPermissionToChangeUsersPwd')
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
@ -336,7 +335,7 @@ users = {
|
|||
_.omit(options, ['data'])
|
||||
).then(function onModelResponse() {
|
||||
return Promise.resolve({
|
||||
password: [{message: i18n.t('notices.api.users.pwdChangedSuccessfully')}]
|
||||
password: [{message: common.i18n.t('notices.api.users.pwdChangedSuccessfully')}]
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -5,8 +5,7 @@ var Promise = require('bluebird'),
|
|||
path = require('path'),
|
||||
permissions = require('../permissions'),
|
||||
validation = require('../data/validation'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
utils;
|
||||
|
||||
utils = {
|
||||
|
@ -214,12 +213,15 @@ utils = {
|
|||
return permsPromise.then(function permissionGranted() {
|
||||
return options;
|
||||
}).catch(function handleNoPermissionError(err) {
|
||||
if (err instanceof errors.NoPermissionError) {
|
||||
err.message = i18n.t('errors.api.utils.noPermissionToCall', {method: method, docName: docName});
|
||||
if (err instanceof common.errors.NoPermissionError) {
|
||||
err.message = common.i18n.t('errors.api.utils.noPermissionToCall', {
|
||||
method: method,
|
||||
docName: docName
|
||||
});
|
||||
return Promise.reject(err);
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.GhostError({
|
||||
return Promise.reject(new common.errors.GhostError({
|
||||
err: err
|
||||
}));
|
||||
});
|
||||
|
@ -291,8 +293,8 @@ utils = {
|
|||
*/
|
||||
checkObject: function checkObject(object, docName, editId) {
|
||||
if (_.isEmpty(object) || _.isEmpty(object[docName]) || _.isEmpty(object[docName][0])) {
|
||||
return Promise.reject(new errors.BadRequestError({
|
||||
message: i18n.t('errors.api.utils.noRootKeyProvided', {docName: docName})
|
||||
return Promise.reject(new common.errors.BadRequestError({
|
||||
message: common.i18n.t('errors.api.utils.noRootKeyProvided', {docName: docName})
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -314,8 +316,8 @@ utils = {
|
|||
});
|
||||
|
||||
if (editId && object[docName][0].id && editId !== object[docName][0].id) {
|
||||
return Promise.reject(new errors.BadRequestError({
|
||||
message: i18n.t('errors.api.utils.invalidIdProvided')
|
||||
return Promise.reject(new common.errors.BadRequestError({
|
||||
message: common.i18n.t('errors.api.utils.invalidIdProvided')
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
|
@ -8,9 +8,7 @@ var Promise = require('bluebird'),
|
|||
pipeline = require('../utils/pipeline'),
|
||||
apiUtils = require('./utils'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
logging = require('../lib/common/logging'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
docName = 'webhooks',
|
||||
webhooks;
|
||||
|
||||
|
@ -27,19 +25,19 @@ function makeRequest(webhook, payload, options) {
|
|||
|
||||
reqPayload = JSON.stringify(payload);
|
||||
|
||||
logging.info('webhook.trigger', event, targetUrl);
|
||||
common.logging.info('webhook.trigger', event, targetUrl);
|
||||
req = https.request(reqOptions);
|
||||
|
||||
req.write(reqPayload);
|
||||
req.on('error', function (err) {
|
||||
// when a webhook responds with a 410 Gone response we should remove the hook
|
||||
if (err.status === 410) {
|
||||
logging.info('webhook.destroy (410 response)', event, targetUrl);
|
||||
common.logging.info('webhook.destroy (410 response)', event, targetUrl);
|
||||
return models.Webhook.destroy({id: webhookId}, options);
|
||||
}
|
||||
|
||||
// TODO: use i18n?
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
context: {
|
||||
id: webhookId,
|
||||
|
@ -61,7 +59,7 @@ function makeRequests(webhooksCollection, payload, options) {
|
|||
/**
|
||||
* ## Webhook API Methods
|
||||
*
|
||||
* **See:** [API Methods](events.js.html#api%20methods)
|
||||
* **See:** [API Methods](index.js.html#api%20methods)
|
||||
*/
|
||||
webhooks = {
|
||||
|
||||
|
@ -83,7 +81,7 @@ webhooks = {
|
|||
return models.Webhook.getByEventAndTarget(options.data.webhooks[0].event, options.data.webhooks[0].target_url, _.omit(options, ['data']))
|
||||
.then(function (webhook) {
|
||||
if (webhook) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.webhooks.webhookAlreadyExists')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.api.webhooks.webhookAlreadyExists')}));
|
||||
}
|
||||
|
||||
return models.Webhook.add(options.data.webhooks[0], _.omit(options, ['data']));
|
||||
|
|
|
@ -1,12 +1,11 @@
|
|||
var path = require('path'),
|
||||
express = require('express'),
|
||||
ampRouter = express.Router(),
|
||||
i18n = require('../../../lib/common/i18n'),
|
||||
var path = require('path'),
|
||||
express = require('express'),
|
||||
ampRouter = express.Router(),
|
||||
|
||||
// Dirty requires
|
||||
errors = require('../../../lib/common/errors'),
|
||||
postLookup = require('../../../controllers/frontend/post-lookup'),
|
||||
renderer = require('../../../controllers/frontend/renderer'),
|
||||
common = require('../../../lib/common'),
|
||||
postLookup = require('../../../controllers/frontend/post-lookup'),
|
||||
renderer = require('../../../controllers/frontend/renderer'),
|
||||
|
||||
templateName = 'amp';
|
||||
|
||||
|
@ -25,7 +24,7 @@ function _renderer(req, res, next) {
|
|||
|
||||
// CASE: we only support amp pages for posts that are not static pages
|
||||
if (!data.post || data.post.page) {
|
||||
return next(new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')}));
|
||||
return next(new common.errors.NotFoundError({message: common.i18n.t('errors.errors.pageNotFound')}));
|
||||
}
|
||||
|
||||
// Render Call
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
var config = require('../../config'),
|
||||
urlService = require('../../services/url'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
middleware = require('./lib/middleware'),
|
||||
router = require('./lib/router'),
|
||||
registerHelpers = require('./lib/helpers'),
|
||||
|
@ -15,10 +13,10 @@ checkSubdir = function checkSubdir() {
|
|||
paths = urlService.utils.getSubdir().split('/');
|
||||
|
||||
if (paths.pop() === config.get('routeKeywords').private) {
|
||||
logging.error(new errors.GhostError({
|
||||
message: i18n.t('errors.config.urlCannotContainPrivateSubdir.error'),
|
||||
context: i18n.t('errors.config.urlCannotContainPrivateSubdir.description'),
|
||||
help: i18n.t('errors.config.urlCannotContainPrivateSubdir.help')
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
message: common.i18n.t('errors.config.urlCannotContainPrivateSubdir.error'),
|
||||
context: common.i18n.t('errors.config.urlCannotContainPrivateSubdir.description'),
|
||||
help: common.i18n.t('errors.config.urlCannotContainPrivateSubdir.help')
|
||||
}));
|
||||
|
||||
// @TODO: why
|
||||
|
|
|
@ -5,8 +5,7 @@ var fs = require('fs'),
|
|||
config = require('../../../config'),
|
||||
urlService = require('../../../services/url'),
|
||||
globalUtils = require('../../../utils'),
|
||||
errors = require('../../../lib/common/errors'),
|
||||
i18n = require('../../../lib/common/i18n'),
|
||||
common = require('../../../lib/common'),
|
||||
settingsCache = require('../../../settings/cache'),
|
||||
privateRoute = '/' + config.get('routeKeywords').private + '/',
|
||||
privateBlogging;
|
||||
|
@ -71,8 +70,8 @@ privateBlogging = {
|
|||
privateBlogging.authenticatePrivateSession(req, res, function onSessionVerified() {
|
||||
// CASE: RSS is disabled for private blogging e.g. they create overhead
|
||||
if (req.path.lastIndexOf('/rss/', 0) === 0 || req.path.lastIndexOf('/rss/') === req.url.length - 5) {
|
||||
return next(new errors.NotFoundError({
|
||||
message: i18n.t('errors.errors.pageNotFound')
|
||||
return next(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.errors.pageNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -133,7 +132,7 @@ privateBlogging = {
|
|||
return res.redirect(urlService.utils.urlFor({relativeUrl: decodeURIComponent(forward)}));
|
||||
} else {
|
||||
res.error = {
|
||||
message: i18n.t('errors.middleware.privateblogging.wrongPassword')
|
||||
message: common.i18n.t('errors.middleware.privateblogging.wrongPassword')
|
||||
};
|
||||
return next();
|
||||
}
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
var path = require('path'),
|
||||
express = require('express'),
|
||||
_ = require('lodash'),
|
||||
subscribeRouter = express.Router(),
|
||||
bodyParser = require('body-parser'),
|
||||
var path = require('path'),
|
||||
express = require('express'),
|
||||
_ = require('lodash'),
|
||||
subscribeRouter = express.Router(),
|
||||
bodyParser = require('body-parser'),
|
||||
|
||||
// Dirty requires
|
||||
api = require('../../../api'),
|
||||
errors = require('../../../lib/common/errors'),
|
||||
validator = require('../../../data/validation').validator,
|
||||
postLookup = require('../../../controllers/frontend/post-lookup'),
|
||||
renderer = require('../../../controllers/frontend/renderer'),
|
||||
api = require('../../../api'),
|
||||
common = require('../../../lib/common'),
|
||||
validator = require('../../../data/validation').validator,
|
||||
postLookup = require('../../../controllers/frontend/post-lookup'),
|
||||
renderer = require('../../../controllers/frontend/renderer'),
|
||||
|
||||
templateName = 'subscribe';
|
||||
|
||||
|
@ -75,7 +75,7 @@ function handleSource(req, res, next) {
|
|||
next();
|
||||
})
|
||||
.catch(function (err) {
|
||||
if (err instanceof errors.NotFoundError) {
|
||||
if (err instanceof common.errors.NotFoundError) {
|
||||
return next();
|
||||
}
|
||||
|
||||
|
@ -87,9 +87,9 @@ function storeSubscriber(req, res, next) {
|
|||
req.body.status = 'subscribed';
|
||||
|
||||
if (_.isEmpty(req.body.email)) {
|
||||
return next(new errors.ValidationError({message: 'Email cannot be blank.'}));
|
||||
return next(new common.errors.ValidationError({message: 'Email cannot be blank.'}));
|
||||
} else if (!validator.isEmail(req.body.email)) {
|
||||
return next(new errors.ValidationError({message: 'Invalid email.'}));
|
||||
return next(new common.errors.ValidationError({message: 'Invalid email.'}));
|
||||
}
|
||||
|
||||
return api.subscribers.add({subscribers: [req.body]}, {context: {external: true}})
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
models = require('../models'),
|
||||
globalUtils = require('../utils'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
errors = require('../lib/common/errors'),
|
||||
common = require('../lib/common'),
|
||||
strategies;
|
||||
|
||||
strategies = {
|
||||
|
@ -50,8 +49,8 @@ strategies = {
|
|||
}
|
||||
|
||||
if (!model.isActive()) {
|
||||
throw new errors.NoPermissionError({
|
||||
message: i18n.t('errors.models.user.accountSuspended')
|
||||
throw new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.models.user.accountSuspended')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -88,7 +87,7 @@ strategies = {
|
|||
|
||||
// CASE: socket hangs up for example
|
||||
if (!ghostAuthAccessToken || !profile) {
|
||||
return done(new errors.NoPermissionError({
|
||||
return done(new common.errors.NoPermissionError({
|
||||
help: 'Please try again.'
|
||||
}));
|
||||
}
|
||||
|
@ -102,14 +101,14 @@ strategies = {
|
|||
invite = _invite;
|
||||
|
||||
if (!invite) {
|
||||
throw new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.invites.inviteNotFound')
|
||||
throw new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.invites.inviteNotFound')
|
||||
});
|
||||
}
|
||||
|
||||
if (invite.get('expires') < Date.now()) {
|
||||
throw new errors.NotFoundError({
|
||||
message: i18n.t('errors.api.invites.inviteExpired')
|
||||
throw new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.api.invites.inviteExpired')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -135,8 +134,8 @@ strategies = {
|
|||
return models.User.findOne({slug: 'ghost-owner', status: 'inactive'}, options)
|
||||
.then(function fetchedOwner(owner) {
|
||||
if (!owner) {
|
||||
throw new errors.NotFoundError({
|
||||
message: i18n.t('errors.models.user.userNotFound')
|
||||
throw new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.models.user.userNotFound')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -160,12 +159,12 @@ strategies = {
|
|||
user = _user;
|
||||
|
||||
if (!user) {
|
||||
throw new errors.NotFoundError();
|
||||
throw new common.errors.NotFoundError();
|
||||
}
|
||||
|
||||
if (!user.isActive()) {
|
||||
throw new errors.NoPermissionError({
|
||||
message: i18n.t('errors.models.user.accountSuspended')
|
||||
throw new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.models.user.accountSuspended')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -196,7 +195,7 @@ strategies = {
|
|||
done(null, user, profile);
|
||||
})
|
||||
.catch(function (err) {
|
||||
if (!(err instanceof errors.NotFoundError)) {
|
||||
if (!(err instanceof common.errors.NotFoundError)) {
|
||||
return done(err);
|
||||
}
|
||||
|
||||
|
|
|
@ -1,9 +1,7 @@
|
|||
var passport = require('passport'),
|
||||
authUtils = require('./utils'),
|
||||
errors = require('../lib/common/errors'),
|
||||
models = require('../models'),
|
||||
events = require('../lib/common/events'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
authenticate;
|
||||
|
||||
authenticate = {
|
||||
|
@ -39,10 +37,10 @@ authenticate = {
|
|||
}
|
||||
|
||||
if (!req.body.client_id || !req.body.client_secret) {
|
||||
return next(new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.middleware.auth.accessDenied'),
|
||||
context: i18n.t('errors.middleware.auth.clientCredentialsNotProvided'),
|
||||
help: i18n.t('errors.middleware.auth.forInformationRead', {url: 'http://api.ghost.org/docs/client-authentication'})
|
||||
return next(new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.middleware.auth.accessDenied'),
|
||||
context: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided'),
|
||||
help: common.i18n.t('errors.middleware.auth.forInformationRead', {url: 'http://api.ghost.org/docs/client-authentication'})
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -57,16 +55,16 @@ authenticate = {
|
|||
delete req.body.client_secret;
|
||||
|
||||
if (!client) {
|
||||
return next(new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.middleware.auth.accessDenied'),
|
||||
context: i18n.t('errors.middleware.auth.clientCredentialsNotValid'),
|
||||
help: i18n.t('errors.middleware.auth.forInformationRead', {url: 'http://api.ghost.org/docs/client-authentication'})
|
||||
return next(new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.middleware.auth.accessDenied'),
|
||||
context: common.i18n.t('errors.middleware.auth.clientCredentialsNotValid'),
|
||||
help: common.i18n.t('errors.middleware.auth.forInformationRead', {url: 'http://api.ghost.org/docs/client-authentication'})
|
||||
}));
|
||||
}
|
||||
|
||||
req.client = client;
|
||||
|
||||
events.emit('client.authenticated', client);
|
||||
common.events.emit('client.authenticated', client);
|
||||
return next(null, client);
|
||||
}
|
||||
)(req, res, next);
|
||||
|
@ -84,19 +82,19 @@ authenticate = {
|
|||
req.authInfo = info;
|
||||
req.user = user;
|
||||
|
||||
events.emit('user.authenticated', user);
|
||||
common.events.emit('user.authenticated', user);
|
||||
return next(null, user, info);
|
||||
} else if (authUtils.getBearerAutorizationToken(req)) {
|
||||
return next(new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.middleware.auth.accessDenied')
|
||||
return next(new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.middleware.auth.accessDenied')
|
||||
}));
|
||||
} else if (req.client) {
|
||||
req.user = {id: models.User.externalUser};
|
||||
return next();
|
||||
}
|
||||
|
||||
return next(new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.middleware.auth.accessDenied')
|
||||
return next(new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.middleware.auth.accessDenied')
|
||||
}));
|
||||
}
|
||||
)(req, res, next);
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
var errors = require('../lib/common/errors'),
|
||||
labs = require('../utils/labs'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
var labs = require('../utils/labs'),
|
||||
common = require('../lib/common'),
|
||||
authorize;
|
||||
|
||||
authorize = {
|
||||
|
@ -10,7 +9,7 @@ authorize = {
|
|||
if (req.user && req.user.id) {
|
||||
return next();
|
||||
} else {
|
||||
return next(new errors.NoPermissionError({message: i18n.t('errors.middleware.auth.pleaseSignIn')}));
|
||||
return next(new common.errors.NoPermissionError({message: common.i18n.t('errors.middleware.auth.pleaseSignIn')}));
|
||||
}
|
||||
},
|
||||
|
||||
|
@ -22,7 +21,7 @@ authorize = {
|
|||
if (req.user && req.user.id) {
|
||||
return next();
|
||||
} else {
|
||||
return next(new errors.NoPermissionError({message: i18n.t('errors.middleware.auth.pleaseSignIn')}));
|
||||
return next(new common.errors.NoPermissionError({message: common.i18n.t('errors.middleware.auth.pleaseSignIn')}));
|
||||
}
|
||||
}
|
||||
},
|
||||
|
@ -31,7 +30,7 @@ authorize = {
|
|||
requiresAuthorizedClient: function requiresAuthorizedClient(client) {
|
||||
return function doAuthorizedClient(req, res, next) {
|
||||
if (!req.client || !req.client.name || req.client.name !== client) {
|
||||
return next(new errors.NoPermissionError({message: i18n.t('errors.permissions.noPermissionToAction')}));
|
||||
return next(new common.errors.NoPermissionError({message: common.i18n.t('errors.permissions.noPermissionToAction')}));
|
||||
}
|
||||
|
||||
return next();
|
||||
|
|
|
@ -2,10 +2,9 @@ var oauth2orize = require('oauth2orize'),
|
|||
_ = require('lodash'),
|
||||
passport = require('passport'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
authUtils = require('./utils'),
|
||||
spamPrevention = require('../web/middleware/api/spam-prevention'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
knex = require('../data/db').knex,
|
||||
oauthServer,
|
||||
oauth;
|
||||
|
@ -19,16 +18,16 @@ function exchangeRefreshToken(client, refreshToken, scope, body, authInfo, done)
|
|||
return models.Refreshtoken.findOne({token: refreshToken}, _.merge({forUpdate: true}, options))
|
||||
.then(function then(model) {
|
||||
if (!model) {
|
||||
throw new errors.NoPermissionError({
|
||||
message: i18n.t('errors.middleware.oauth.invalidRefreshToken')
|
||||
throw new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.middleware.oauth.invalidRefreshToken')
|
||||
});
|
||||
}
|
||||
|
||||
var token = model.toJSON();
|
||||
|
||||
if (token.expires <= Date.now()) {
|
||||
throw new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.middleware.oauth.refreshTokenExpired')
|
||||
throw new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.middleware.oauth.refreshTokenExpired')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -51,11 +50,11 @@ function exchangeRefreshToken(client, refreshToken, scope, body, authInfo, done)
|
|||
}).then(function (response) {
|
||||
done(null, response.access_token, {expires_in: response.expires_in});
|
||||
}).catch(function (err) {
|
||||
if (errors.utils.isIgnitionError(err)) {
|
||||
if (common.errors.utils.isIgnitionError(err)) {
|
||||
return done(err, false);
|
||||
}
|
||||
|
||||
done(new errors.InternalServerError({
|
||||
done(new common.errors.InternalServerError({
|
||||
err: err
|
||||
}), false);
|
||||
});
|
||||
|
@ -64,8 +63,8 @@ function exchangeRefreshToken(client, refreshToken, scope, body, authInfo, done)
|
|||
// We are required to pass in authInfo in order to reset spam counter for user login
|
||||
function exchangePassword(client, username, password, scope, body, authInfo, done) {
|
||||
if (!client || !client.id) {
|
||||
return done(new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.middleware.auth.clientCredentialsNotProvided')
|
||||
return done(new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided')
|
||||
}), false);
|
||||
}
|
||||
|
||||
|
@ -88,8 +87,8 @@ function exchangePassword(client, username, password, scope, body, authInfo, don
|
|||
|
||||
function exchangeAuthorizationCode(req, res, next) {
|
||||
if (!req.body.authorizationCode) {
|
||||
return next(new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.middleware.auth.accessDenied')
|
||||
return next(new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.middleware.auth.accessDenied')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -101,8 +100,8 @@ function exchangeAuthorizationCode(req, res, next) {
|
|||
}
|
||||
|
||||
if (!user) {
|
||||
return next(new errors.UnauthorizedError({
|
||||
message: i18n.t('errors.middleware.auth.accessDenied')
|
||||
return next(new common.errors.UnauthorizedError({
|
||||
message: common.i18n.t('errors.middleware.auth.accessDenied')
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
var _ = require('lodash'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
filters = require('../filters'),
|
||||
safeString = require('../utils').safeString,
|
||||
handleError = require('./frontend/error'),
|
||||
|
@ -25,7 +24,7 @@ module.exports = function channelController(req, res, next) {
|
|||
return fetchData(res.locals.channel).then(function handleResult(result) {
|
||||
// If page is greater than number of pages we have, go straight to 404
|
||||
if (pageParam > result.meta.pagination.pages) {
|
||||
return next(new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')}));
|
||||
return next(new common.errors.NotFoundError({message: common.i18n.t('errors.errors.pageNotFound')}));
|
||||
}
|
||||
|
||||
// Format data 1
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
var _ = require('lodash'),
|
||||
url = require('url'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
safeString = require('../utils').safeString,
|
||||
settingsCache = require('../settings/cache'),
|
||||
|
||||
|
@ -20,10 +19,10 @@ function getBaseUrlForRSSReq(originalUrl, pageParam) {
|
|||
// @TODO: is this really correct? Should we be using meta data title?
|
||||
function getTitle(relatedData) {
|
||||
relatedData = relatedData || {};
|
||||
var titleStart = _.get(relatedData, 'author[0].name') || _.get(relatedData, 'tag[0].name') || '';
|
||||
var titleStart = _.get(relatedData, 'author[0].name') || _.get(relatedData, 'tag[0].name') || '';
|
||||
|
||||
titleStart += titleStart ? ' - ' : '';
|
||||
return titleStart + settingsCache.get('title');
|
||||
return titleStart + settingsCache.get('title');
|
||||
}
|
||||
|
||||
// @TODO: merge this with the rest of the data processing for RSS
|
||||
|
@ -60,7 +59,7 @@ generate = function generate(req, res, next) {
|
|||
return getData(res.locals.channel).then(function handleResult(data) {
|
||||
// If page is greater than number of pages we have, go straight to 404
|
||||
if (pageParam > data.meta.pagination.pages) {
|
||||
return next(new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')}));
|
||||
return next(new common.errors.NotFoundError({message: common.i18n.t('errors.errors.pageNotFound')}));
|
||||
}
|
||||
|
||||
// Render call - to a special RSS renderer
|
||||
|
|
|
@ -4,7 +4,7 @@ var fs = require('fs'),
|
|||
path = require('path'),
|
||||
Promise = require('bluebird'),
|
||||
config = require('../../config'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
common = require('../../lib/common'),
|
||||
urlService = require('../../services/url'),
|
||||
exporter = require('../export'),
|
||||
|
||||
|
@ -23,7 +23,7 @@ writeExportFile = function writeExportFile(exportResult) {
|
|||
* @returns {Promise<*>}
|
||||
*/
|
||||
backup = function backup(options) {
|
||||
logging.info('Creating database backup');
|
||||
common.logging.info('Creating database backup');
|
||||
options = options || {};
|
||||
|
||||
var props = {
|
||||
|
@ -34,7 +34,7 @@ backup = function backup(options) {
|
|||
return Promise.props(props)
|
||||
.then(writeExportFile)
|
||||
.then(function successMessage(filename) {
|
||||
logging.info('Database backup written to: ' + filename);
|
||||
common.logging.info('Database backup written to: ' + filename);
|
||||
});
|
||||
};
|
||||
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
var knex = require('knex'),
|
||||
config = require('../../config'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
common = require('../../lib/common'),
|
||||
knexInstance;
|
||||
|
||||
// @TODO:
|
||||
|
@ -20,7 +19,7 @@ function configure(dbConfig) {
|
|||
dbConfig.connection.charset = 'utf8mb4';
|
||||
|
||||
dbConfig.connection.loggingHook = function loggingHook(err) {
|
||||
logging.error(new errors.InternalServerError({
|
||||
common.logging.error(new common.errors.InternalServerError({
|
||||
code: 'MYSQL_LOGGING_HOOK',
|
||||
err: err
|
||||
}));
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
var KnexMigrator = require('knex-migrator'),
|
||||
config = require('../../config'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
common = require('../../lib/common'),
|
||||
models = require('../../models');
|
||||
|
||||
module.exports.check = function healthCheck() {
|
||||
|
@ -22,7 +22,7 @@ module.exports.check = function healthCheck() {
|
|||
throw outerErr;
|
||||
}
|
||||
|
||||
throw new errors.DatabaseVersionError({
|
||||
throw new common.errors.DatabaseVersionError({
|
||||
message: 'Your database version is not compatible with Ghost 1.0.0 (master branch)',
|
||||
context: 'Want to keep your DB? Use Ghost < 1.0.0 or the "stable" branch. Otherwise please delete your DB and restart Ghost.',
|
||||
help: 'More information on the Ghost 1.0.0 at https://docs.ghost.org/docs/introduction'
|
||||
|
|
|
@ -4,10 +4,8 @@ var _ = require('lodash'),
|
|||
commands = require('../schema').commands,
|
||||
globalUtils = require('../../utils'),
|
||||
ghostVersion = require('../../utils/ghost-version'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
common = require('../../lib/common'),
|
||||
models = require('../../models'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
excludedTables = ['accesstokens', 'refreshtokens', 'clients', 'client_trusted_domains'],
|
||||
modelOptions = {context: {internal: true}},
|
||||
|
||||
|
@ -30,7 +28,7 @@ exportFileName = function exportFileName(options) {
|
|||
|
||||
return title + 'ghost.' + datetime + '.json';
|
||||
}).catch(function (err) {
|
||||
logging.error(new errors.GhostError({err: err}));
|
||||
common.logging.error(new common.errors.GhostError({err: err}));
|
||||
return 'ghost.' + datetime + '.json';
|
||||
});
|
||||
};
|
||||
|
@ -79,9 +77,9 @@ doExport = function doExport(options) {
|
|||
|
||||
return exportData;
|
||||
}).catch(function (err) {
|
||||
return Promise.reject(new errors.DataExportError({
|
||||
return Promise.reject(new common.errors.DataExportError({
|
||||
err: err,
|
||||
context: i18n.t('errors.data.export.errorExportingData')
|
||||
context: common.i18n.t('errors.data.export.errorExportingData')
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
fs = require('fs-extra'),
|
||||
errors = require('../../../lib/common/errors'),
|
||||
i18n = require('../../../lib/common/i18n'),
|
||||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
fs = require('fs-extra'),
|
||||
common = require('../../../lib/common'),
|
||||
JSONHandler;
|
||||
|
||||
JSONHandler = {
|
||||
|
@ -23,8 +22,8 @@ JSONHandler = {
|
|||
// if importData follows JSON-API format `{ db: [exportedData] }`
|
||||
if (_.keys(importData).length === 1) {
|
||||
if (!importData.db || !Array.isArray(importData.db)) {
|
||||
throw new errors.GhostError({
|
||||
message: i18n.t('errors.data.importer.handlers.json.invalidJsonFormat')
|
||||
throw new common.errors.GhostError({
|
||||
message: common.i18n.t('errors.data.importer.handlers.json.invalidJsonFormat')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -33,10 +32,10 @@ JSONHandler = {
|
|||
|
||||
return importData;
|
||||
} catch (err) {
|
||||
return Promise.reject(new errors.BadRequestError({
|
||||
return Promise.reject(new common.errors.BadRequestError({
|
||||
err: err,
|
||||
message: err.message,
|
||||
help: i18n.t('errors.data.importer.handlers.json.checkImportJsonIsValid')
|
||||
help: common.i18n.t('errors.data.importer.handlers.json.checkImportJsonIsValid')
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const debug = require('ghost-ignition').debug('importer:base'),
|
||||
errors = require('../../../../lib/common/errors'),
|
||||
common = require('../../../../lib/common'),
|
||||
models = require('../../../../models'),
|
||||
_ = require('lodash'),
|
||||
Promise = require('bluebird');
|
||||
|
@ -103,14 +103,14 @@ class Base {
|
|||
});
|
||||
}
|
||||
} else {
|
||||
errorsToReject.push(new errors.DataImportError({
|
||||
errorsToReject.push(new common.errors.DataImportError({
|
||||
message: 'Detected duplicated entry.',
|
||||
help: self.modelName,
|
||||
context: JSON.stringify(obj),
|
||||
err: err
|
||||
}));
|
||||
}
|
||||
} else if (err instanceof errors.NotFoundError) {
|
||||
} else if (err instanceof common.errors.NotFoundError) {
|
||||
if (self.showNotFoundWarning) {
|
||||
problems.push({
|
||||
message: 'Entry was not imported and ignored. Could not find entry.',
|
||||
|
@ -120,8 +120,8 @@ class Base {
|
|||
});
|
||||
}
|
||||
} else {
|
||||
if (!errors.utils.isIgnitionError(err)) {
|
||||
err = new errors.DataImportError({
|
||||
if (!common.errors.utils.isIgnitionError(err)) {
|
||||
err = new common.errors.DataImportError({
|
||||
message: err.message,
|
||||
context: JSON.stringify(obj),
|
||||
help: self.modelName,
|
||||
|
|
|
@ -1,21 +1,19 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
sequence = require('../../utils/sequence'),
|
||||
pipeline = require('../../utils/pipeline'),
|
||||
fs = require('fs-extra'),
|
||||
path = require('path'),
|
||||
os = require('os'),
|
||||
glob = require('glob'),
|
||||
uuid = require('uuid'),
|
||||
extract = require('extract-zip'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
ImageHandler = require('./handlers/image'),
|
||||
JSONHandler = require('./handlers/json'),
|
||||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
fs = require('fs-extra'),
|
||||
path = require('path'),
|
||||
os = require('os'),
|
||||
glob = require('glob'),
|
||||
uuid = require('uuid'),
|
||||
extract = require('extract-zip'),
|
||||
sequence = require('../../utils/sequence'),
|
||||
pipeline = require('../../utils/pipeline'),
|
||||
common = require('../../lib/common'),
|
||||
ImageHandler = require('./handlers/image'),
|
||||
JSONHandler = require('./handlers/json'),
|
||||
MarkdownHandler = require('./handlers/markdown'),
|
||||
ImageImporter = require('./importers/image'),
|
||||
DataImporter = require('./importers/data'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
ImageImporter = require('./importers/image'),
|
||||
DataImporter = require('./importers/data'),
|
||||
|
||||
// Glob levels
|
||||
ROOT_ONLY = 0,
|
||||
|
@ -73,7 +71,7 @@ _.extend(ImportManager.prototype, {
|
|||
*/
|
||||
getGlobPattern: function (items) {
|
||||
return '+(' + _.reduce(items, function (memo, ext) {
|
||||
return memo !== '' ? memo + '|' + ext : ext;
|
||||
return memo !== '' ? memo + '|' + ext : ext;
|
||||
}, '') + ')';
|
||||
},
|
||||
/**
|
||||
|
@ -109,10 +107,10 @@ _.extend(ImportManager.prototype, {
|
|||
_.each(filesToDelete, function (fileToDelete) {
|
||||
fs.remove(fileToDelete, function (err) {
|
||||
if (err) {
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
context: i18n.t('errors.data.importer.index.couldNotCleanUpFile.error'),
|
||||
help: i18n.t('errors.data.importer.index.couldNotCleanUpFile.context')
|
||||
context: common.i18n.t('errors.data.importer.index.couldNotCleanUpFile.error'),
|
||||
help: common.i18n.t('errors.data.importer.index.couldNotCleanUpFile.context')
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
@ -138,9 +136,7 @@ _.extend(ImportManager.prototype, {
|
|||
*/
|
||||
isValidZip: function (directory) {
|
||||
// Globs match content in the root or inside a single directory
|
||||
var extMatchesBase = glob.sync(
|
||||
this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}
|
||||
),
|
||||
var extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}),
|
||||
extMatchesAll = glob.sync(
|
||||
this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory}
|
||||
),
|
||||
|
@ -152,7 +148,7 @@ _.extend(ImportManager.prototype, {
|
|||
|
||||
// This is a temporary extra message for the old format roon export which doesn't work with Ghost
|
||||
if (oldRoonMatches.length > 0) {
|
||||
throw new errors.UnsupportedMediaTypeError({message: i18n.t('errors.data.importer.index.unsupportedRoonExport')});
|
||||
throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.unsupportedRoonExport')});
|
||||
}
|
||||
|
||||
// If this folder contains importable files or a content or images directory
|
||||
|
@ -161,10 +157,10 @@ _.extend(ImportManager.prototype, {
|
|||
}
|
||||
|
||||
if (extMatchesAll.length < 1) {
|
||||
throw new errors.UnsupportedMediaTypeError({message: i18n.t('errors.data.importer.index.noContentToImport')});
|
||||
throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.noContentToImport')});
|
||||
}
|
||||
|
||||
throw new errors.UnsupportedMediaTypeError({message: i18n.t('errors.data.importer.index.invalidZipStructure')});
|
||||
throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.invalidZipStructure')});
|
||||
},
|
||||
/**
|
||||
* Use the extract module to extract the given zip file to a temp directory & return the temp directory path
|
||||
|
@ -211,7 +207,7 @@ _.extend(ImportManager.prototype, {
|
|||
this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory}
|
||||
);
|
||||
if (extMatchesAll.length < 1 || extMatchesAll[0].split('/') < 1) {
|
||||
throw new errors.ValidationError({message: i18n.t('errors.data.importer.index.invalidZipFileBaseDirectory')});
|
||||
throw new common.errors.ValidationError({message: common.i18n.t('errors.data.importer.index.invalidZipFileBaseDirectory')});
|
||||
}
|
||||
|
||||
return extMatchesAll[0].split('/')[0];
|
||||
|
@ -239,8 +235,8 @@ _.extend(ImportManager.prototype, {
|
|||
_.each(self.handlers, function (handler) {
|
||||
if (importData.hasOwnProperty(handler.type)) {
|
||||
// This limitation is here to reduce the complexity of the importer for now
|
||||
return Promise.reject(new errors.UnsupportedMediaTypeError({
|
||||
message: i18n.t('errors.data.importer.index.zipContainsMultipleDataFormats')
|
||||
return Promise.reject(new common.errors.UnsupportedMediaTypeError({
|
||||
message: common.i18n.t('errors.data.importer.index.zipContainsMultipleDataFormats')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -256,8 +252,8 @@ _.extend(ImportManager.prototype, {
|
|||
});
|
||||
|
||||
if (ops.length === 0) {
|
||||
return Promise.reject(new errors.UnsupportedMediaTypeError({
|
||||
message: i18n.t('errors.data.importer.index.noContentToImport')
|
||||
return Promise.reject(new common.errors.UnsupportedMediaTypeError({
|
||||
message: common.i18n.t('errors.data.importer.index.noContentToImport')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -373,7 +369,7 @@ _.extend(ImportManager.prototype, {
|
|||
}).then(function (importData) {
|
||||
// Step 4: Report on the import
|
||||
return self.generateReport(importData)
|
||||
// Step 5: Cleanup any files
|
||||
// Step 5: Cleanup any files
|
||||
.finally(self.cleanUp());
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var Promise = require('bluebird'),
|
||||
settingsCache = require('../../settings/cache'),
|
||||
urlService = require('../../services/url'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
common = require('../../lib/common'),
|
||||
getUrl = require('./url'),
|
||||
getImageDimensions = require('./image-dimensions'),
|
||||
getCanonicalUrl = require('./canonical_url'),
|
||||
|
@ -100,7 +100,7 @@ function getMetaData(data, root) {
|
|||
|
||||
return metaData;
|
||||
}).catch(function (err) {
|
||||
logging.error(err);
|
||||
common.logging.error(err);
|
||||
return metaData;
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,29 +1,30 @@
|
|||
var Promise = require('bluebird'),
|
||||
commands = require('../../schema').commands,
|
||||
logging = require('../../../lib/common/logging'),
|
||||
schema = require('../../schema').tables,
|
||||
common = require('../../../lib/common'),
|
||||
schemaTables = Object.keys(schema);
|
||||
|
||||
module.exports.up = function createTables(options) {
|
||||
var connection = options.connection;
|
||||
|
||||
return Promise.mapSeries(schemaTables, function createTable(table) {
|
||||
logging.info('Creating table: ' + table);
|
||||
common.logging.info('Creating table: ' + table);
|
||||
return commands.createTable(table, connection);
|
||||
});
|
||||
};
|
||||
|
||||
/*
|
||||
@TODO: This works, but is very dangerous in the current state of the knex-migrator v3.
|
||||
@TODO: Enable if knex-migrator v3 is stable.
|
||||
module.exports.down = function dropTables(options) {
|
||||
var connection = options.connection;
|
||||
/**
|
||||
*
|
||||
@TODO: This works, but is very dangerous in the current state of the knex-migrator v3.
|
||||
@TODO: Enable if knex-migrator v3 is stable.
|
||||
module.exports.down = function dropTables(options) {
|
||||
var connection = options.connection;
|
||||
|
||||
// Reference between tables!
|
||||
schemaTables.reverse();
|
||||
return Promise.mapSeries(schemaTables, function dropTable(table) {
|
||||
logging.info('Drop table: ' + table);
|
||||
return commands.deleteTable(table, connection);
|
||||
});
|
||||
};
|
||||
*/
|
||||
// Reference between tables!
|
||||
schemaTables.reverse();
|
||||
return Promise.mapSeries(schemaTables, function dropTable(table) {
|
||||
common.logging.info('Drop table: ' + table);
|
||||
return commands.deleteTable(table, connection);
|
||||
});
|
||||
};
|
||||
*/
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var Promise = require('bluebird'),
|
||||
_ = require('lodash'),
|
||||
fixtures = require('../../schema/fixtures'),
|
||||
logging = require('../../../lib/common/logging');
|
||||
common = require('../../../lib/common');
|
||||
|
||||
module.exports.config = {
|
||||
transaction: true
|
||||
|
@ -13,12 +13,12 @@ module.exports.up = function insertFixtures(options) {
|
|||
}, options);
|
||||
|
||||
return Promise.mapSeries(fixtures.models, function (model) {
|
||||
logging.info('Model: ' + model.name);
|
||||
common.logging.info('Model: ' + model.name);
|
||||
|
||||
return fixtures.utils.addFixturesForModel(model, localOptions);
|
||||
}).then(function () {
|
||||
return Promise.mapSeries(fixtures.relations, function (relation) {
|
||||
logging.info('Relation: ' + relation.from.model + ' to ' + relation.to.model);
|
||||
common.logging.info('Relation: ' + relation.from.model + ' to ' + relation.to.model);
|
||||
return fixtures.utils.addFixturesForRelation(relation, localOptions);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const Promise = require('bluebird'),
|
||||
logging = require('../../../../lib/common/logging'),
|
||||
common = require('../../../../lib/common'),
|
||||
commands = require('../../../schema').commands,
|
||||
table = 'posts',
|
||||
columns = ['custom_template'],
|
||||
|
@ -25,11 +25,11 @@ _private.handle = function handle(options) {
|
|||
return connection.schema.hasColumn(table, column)
|
||||
.then(function (exists) {
|
||||
if (exists && isAdding || !exists && !isAdding) {
|
||||
logging.warn(`${type} column ${table}.${column}`);
|
||||
common.logging.warn(`${type} column ${table}.${column}`);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
logging.info(`${type} column ${table}.${column}`);
|
||||
common.logging.info(`${type} column ${table}.${column}`);
|
||||
return operation(table, column, connection);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
utils = require('../../../schema/fixtures/utils'),
|
||||
permissions = require('../../../../permissions'),
|
||||
logging = require('../../../../lib/common/logging'),
|
||||
common = require('../../../../lib/common'),
|
||||
resource = 'theme',
|
||||
_private = {};
|
||||
|
||||
|
@ -15,9 +15,9 @@ _private.getRelations = function getRelations() {
|
|||
|
||||
_private.printResult = function printResult(result, message) {
|
||||
if (result.done === result.expected) {
|
||||
logging.info(message);
|
||||
common.logging.info(message);
|
||||
} else {
|
||||
logging.warn('(' + result.done + '/' + result.expected + ') ' + message);
|
||||
common.logging.warn('(' + result.done + '/' + result.expected + ') ' + message);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const logging = require('../../../../lib/common/logging'),
|
||||
var Promise = require('bluebird'),
|
||||
common = require('../../../../lib/common'),
|
||||
commands = require('../../../schema').commands,
|
||||
table = 'webhooks',
|
||||
message1 = 'Adding table: ' + table,
|
||||
|
@ -12,11 +13,11 @@ module.exports.up = function addWebhooksTable(options) {
|
|||
return connection.schema.hasTable(table)
|
||||
.then(function (exists) {
|
||||
if (exists) {
|
||||
logging.warn(message1);
|
||||
common.logging.warn(message1);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
logging.info(message1);
|
||||
common.logging.info(message1);
|
||||
return commands.createTable(table, connection);
|
||||
});
|
||||
};
|
||||
|
@ -27,11 +28,11 @@ module.exports.down = function removeWebhooksTable(options) {
|
|||
return connection.schema.hasTable(table)
|
||||
.then(function (exists) {
|
||||
if (!exists) {
|
||||
logging.warn(message2);
|
||||
common.logging.warn(message2);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
logging.info(message2);
|
||||
common.logging.info(message2);
|
||||
return commands.deleteTable(table, connection);
|
||||
});
|
||||
};
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const Promise = require('bluebird'),
|
||||
logging = require('../../../../lib/common/logging'),
|
||||
common = require('../../../../lib/common'),
|
||||
commands = require('../../../schema').commands,
|
||||
table = 'posts',
|
||||
columns = ['custom_excerpt'],
|
||||
|
@ -25,11 +25,11 @@ _private.handle = function handle(options) {
|
|||
return connection.schema.hasColumn(table, column)
|
||||
.then(function (exists) {
|
||||
if (exists && isAdding || !exists && !isAdding) {
|
||||
logging.warn(`${type} column ${table}.${column}`);
|
||||
common.logging.warn(`${type} column ${table}.${column}`);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
logging.info(`${type} column ${table}.${column}`);
|
||||
common.logging.info(`${type} column ${table}.${column}`);
|
||||
return operation(table, column, connection);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const Promise = require('bluebird'),
|
||||
logging = require('../../../../lib/common/logging'),
|
||||
common = require('../../../../lib/common'),
|
||||
commands = require('../../../schema').commands,
|
||||
table = 'posts',
|
||||
columns = ['codeinjection_head', 'codeinjection_foot'],
|
||||
|
@ -25,11 +25,11 @@ _private.handle = function handle(options) {
|
|||
return connection.schema.hasColumn(table, column)
|
||||
.then(function (exists) {
|
||||
if (exists && isAdding || !exists && !isAdding) {
|
||||
logging.warn(`${type} column ${table}.${column}`);
|
||||
common.logging.warn(`${type} column ${table}.${column}`);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
logging.info(`${type} column ${table}.${column}`);
|
||||
common.logging.info(`${type} column ${table}.${column}`);
|
||||
return operation(table, column, connection);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const Promise = require('bluebird'),
|
||||
logging = require('../../../../lib/common/logging'),
|
||||
common = require('../../../../lib/common'),
|
||||
commands = require('../../../schema').commands,
|
||||
table = 'posts',
|
||||
columns = ['og_image', 'og_title', 'og_description', 'twitter_image', 'twitter_title', 'twitter_description'],
|
||||
|
@ -25,11 +25,11 @@ _private.handle = function handle(options) {
|
|||
return connection.schema.hasColumn(table, column)
|
||||
.then(function (exists) {
|
||||
if (exists && isAdding || !exists && !isAdding) {
|
||||
logging.warn(`${type} column ${table}.${column}`);
|
||||
common.logging.warn(`${type} column ${table}.${column}`);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
logging.info(`${type} column ${table}.${column}`);
|
||||
common.logging.info(`${type} column ${table}.${column}`);
|
||||
return operation(table, column, connection);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const models = require('../../../../models'),
|
||||
logging = require('../../../../lib/common/logging'),
|
||||
common = require('../../../../lib/common'),
|
||||
fixtures = require('../../../schema/fixtures'),
|
||||
_ = require('lodash'),
|
||||
backupClient = fixtures.utils.findModelFixtureEntry('Client', {slug: 'ghost-backup'}),
|
||||
|
@ -22,10 +22,10 @@ module.exports.up = function addGhostBackupClient(options) {
|
|||
.findOne({slug: backupClient.slug}, localOptions)
|
||||
.then(function (client) {
|
||||
if (!client) {
|
||||
logging.info(message);
|
||||
common.logging.info(message);
|
||||
return fixtures.utils.addFixturesForModel({name: 'Client', entries: [backupClient]}, localOptions);
|
||||
} else {
|
||||
logging.warn(message);
|
||||
common.logging.warn(message);
|
||||
return Promise.resolve();
|
||||
}
|
||||
});
|
||||
|
@ -40,10 +40,10 @@ module.exports.down = function removeGhostBackupClient(options) {
|
|||
.findOne({slug: backupClient.slug}, localOptions)
|
||||
.then(function (client) {
|
||||
if (client) {
|
||||
logging.info(message1);
|
||||
common.logging.info(message1);
|
||||
return fixtures.utils.removeFixturesForModel({name: 'Client', entries: [backupClient]}, localOptions);
|
||||
} else {
|
||||
logging.warn(message1);
|
||||
common.logging.warn(message1);
|
||||
return Promise.resolve();
|
||||
}
|
||||
});
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
utils = require('../../../schema/fixtures/utils'),
|
||||
permissions = require('../../../../permissions'),
|
||||
logging = require('../../../../lib/common/logging'),
|
||||
common = require('../../../../lib/common'),
|
||||
resource = 'redirect',
|
||||
_private = {};
|
||||
|
||||
|
@ -15,9 +15,9 @@ _private.getRelations = function getRelations() {
|
|||
|
||||
_private.printResult = function printResult(result, message) {
|
||||
if (result.done === result.expected) {
|
||||
logging.info(message);
|
||||
common.logging.info(message);
|
||||
} else {
|
||||
logging.warn('(' + result.done + '/' + result.expected + ') ' + message);
|
||||
common.logging.warn('(' + result.done + '/' + result.expected + ') ' + message);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
db = require('../db'),
|
||||
schema = require('./schema'),
|
||||
clients = require('./clients');
|
||||
|
@ -100,7 +100,7 @@ function getTables(transaction) {
|
|||
return clients[client].getTables(transaction);
|
||||
}
|
||||
|
||||
return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
||||
return Promise.reject(common.i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
||||
}
|
||||
|
||||
function getIndexes(table, transaction) {
|
||||
|
@ -110,7 +110,7 @@ function getIndexes(table, transaction) {
|
|||
return clients[client].getIndexes(table, transaction);
|
||||
}
|
||||
|
||||
return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
||||
return Promise.reject(common.i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
||||
}
|
||||
|
||||
function getColumns(table, transaction) {
|
||||
|
@ -120,7 +120,7 @@ function getColumns(table, transaction) {
|
|||
return clients[client].getColumns(table);
|
||||
}
|
||||
|
||||
return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
||||
return Promise.reject(common.i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
||||
}
|
||||
|
||||
function checkTables(transaction) {
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
var schema = require('../schema').tables,
|
||||
_ = require('lodash'),
|
||||
var schema = require('../schema').tables,
|
||||
_ = require('lodash'),
|
||||
validator = require('validator'),
|
||||
moment = require('moment-timezone'),
|
||||
assert = require('assert'),
|
||||
Promise = require('bluebird'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
moment = require('moment-timezone'),
|
||||
assert = require('assert'),
|
||||
Promise = require('bluebird'),
|
||||
common = require('../../lib/common'),
|
||||
settingsCache = require('../../settings/cache'),
|
||||
urlService = require('../../services/url'),
|
||||
|
||||
|
@ -19,11 +18,11 @@ function assertString(input) {
|
|||
}
|
||||
|
||||
/**
|
||||
* Counts repeated characters in a string. When 50% or more characters are the same,
|
||||
* we return false and therefore invalidate the string.
|
||||
* @param {String} stringToTest The password string to check.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
* Counts repeated characters in a string. When 50% or more characters are the same,
|
||||
* we return false and therefore invalidate the string.
|
||||
* @param {String} stringToTest The password string to check.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
function characterOccurance(stringToTest) {
|
||||
var chars = {},
|
||||
allowedOccurancy,
|
||||
|
@ -83,15 +82,15 @@ validator.extend('isSlug', function isSlug(str) {
|
|||
});
|
||||
|
||||
/**
|
||||
* Validation against simple password rules
|
||||
* Returns false when validation fails and true for a valid password
|
||||
* @param {String} password The password string to check.
|
||||
* @param {String} email The users email address to validate agains password.
|
||||
* @param {String} blogTitle Optional blogTitle value, when blog title is not set yet, e. g. in setup process.
|
||||
* @return {Object} example for returned validation Object:
|
||||
* invalid password: `validationResult: {isValid: false, message: 'Sorry, you cannot use an insecure password.'}`
|
||||
* valid password: `validationResult: {isValid: true}`
|
||||
*/
|
||||
* Validation against simple password rules
|
||||
* Returns false when validation fails and true for a valid password
|
||||
* @param {String} password The password string to check.
|
||||
* @param {String} email The users email address to validate agains password.
|
||||
* @param {String} blogTitle Optional blogTitle value, when blog title is not set yet, e. g. in setup process.
|
||||
* @return {Object} example for returned validation Object:
|
||||
* invalid password: `validationResult: {isValid: false, message: 'Sorry, you cannot use an insecure password.'}`
|
||||
* valid password: `validationResult: {isValid: true}`
|
||||
*/
|
||||
validatePassword = function validatePassword(password, email, blogTitle) {
|
||||
var validationResult = {isValid: true},
|
||||
disallowedPasswords = ['password', 'ghost', 'passw0rd'],
|
||||
|
@ -113,7 +112,7 @@ validatePassword = function validatePassword(password, email, blogTitle) {
|
|||
// password must be longer than 10 characters
|
||||
if (!validator.isLength(password, 10)) {
|
||||
validationResult.isValid = false;
|
||||
validationResult.message = i18n.t('errors.models.user.passwordDoesNotComplyLength', {minLength: 10});
|
||||
validationResult.message = common.i18n.t('errors.models.user.passwordDoesNotComplyLength', {minLength: 10});
|
||||
|
||||
return validationResult;
|
||||
}
|
||||
|
@ -154,7 +153,7 @@ validatePassword = function validatePassword(password, email, blogTitle) {
|
|||
|
||||
// Generic error message for the rules where no dedicated error massage is set
|
||||
if (!validationResult.isValid && !validationResult.message) {
|
||||
validationResult.message = i18n.t('errors.models.user.passwordDoesNotComplySecurity');
|
||||
validationResult.message = common.i18n.t('errors.models.user.passwordDoesNotComplySecurity');
|
||||
}
|
||||
|
||||
return validationResult;
|
||||
|
@ -172,19 +171,31 @@ validateSchema = function validateSchema(tableName, model) {
|
|||
|
||||
// check nullable
|
||||
if (model.hasOwnProperty(columnKey) && schema[tableName][columnKey].hasOwnProperty('nullable')
|
||||
&& schema[tableName][columnKey].nullable !== true) {
|
||||
&& schema[tableName][columnKey].nullable !== true) {
|
||||
if (validator.empty(strVal)) {
|
||||
message = i18n.t('notices.data.validation.index.valueCannotBeBlank', {tableName: tableName, columnKey: columnKey});
|
||||
validationErrors.push(new errors.ValidationError({message: message, context: tableName + '.' + columnKey}));
|
||||
message = common.i18n.t('notices.data.validation.index.valueCannotBeBlank', {
|
||||
tableName: tableName,
|
||||
columnKey: columnKey
|
||||
});
|
||||
validationErrors.push(new common.errors.ValidationError({
|
||||
message: message,
|
||||
context: tableName + '.' + columnKey
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// validate boolean columns
|
||||
if (model.hasOwnProperty(columnKey) && schema[tableName][columnKey].hasOwnProperty('type')
|
||||
&& schema[tableName][columnKey].type === 'bool') {
|
||||
&& schema[tableName][columnKey].type === 'bool') {
|
||||
if (!(validator.isBoolean(strVal) || validator.empty(strVal))) {
|
||||
message = i18n.t('notices.data.validation.index.valueMustBeBoolean', {tableName: tableName, columnKey: columnKey});
|
||||
validationErrors.push(new errors.ValidationError({message: message, context: tableName + '.' + columnKey}));
|
||||
message = common.i18n.t('notices.data.validation.index.valueMustBeBoolean', {
|
||||
tableName: tableName,
|
||||
columnKey: columnKey
|
||||
});
|
||||
validationErrors.push(new common.errors.ValidationError({
|
||||
message: message,
|
||||
context: tableName + '.' + columnKey
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -193,13 +204,13 @@ validateSchema = function validateSchema(tableName, model) {
|
|||
// check length
|
||||
if (schema[tableName][columnKey].hasOwnProperty('maxlength')) {
|
||||
if (!validator.isLength(strVal, 0, schema[tableName][columnKey].maxlength)) {
|
||||
message = i18n.t('notices.data.validation.index.valueExceedsMaxLength',
|
||||
message = common.i18n.t('notices.data.validation.index.valueExceedsMaxLength',
|
||||
{
|
||||
tableName: tableName,
|
||||
columnKey: columnKey,
|
||||
maxlength: schema[tableName][columnKey].maxlength
|
||||
});
|
||||
validationErrors.push(new errors.ValidationError({
|
||||
validationErrors.push(new common.errors.ValidationError({
|
||||
message: message,
|
||||
context: tableName + '.' + columnKey
|
||||
}));
|
||||
|
@ -214,11 +225,11 @@ validateSchema = function validateSchema(tableName, model) {
|
|||
// check type
|
||||
if (schema[tableName][columnKey].hasOwnProperty('type')) {
|
||||
if (schema[tableName][columnKey].type === 'integer' && !validator.isInt(strVal)) {
|
||||
message = i18n.t('notices.data.validation.index.valueIsNotInteger', {
|
||||
message = common.i18n.t('notices.data.validation.index.valueIsNotInteger', {
|
||||
tableName: tableName,
|
||||
columnKey: columnKey
|
||||
});
|
||||
validationErrors.push(new errors.ValidationError({
|
||||
validationErrors.push(new common.errors.ValidationError({
|
||||
message: message,
|
||||
context: tableName + '.' + columnKey
|
||||
}));
|
||||
|
@ -293,17 +304,20 @@ validate = function validate(value, key, validations, tableName) {
|
|||
// equivalent of validator.isSomething(option1, option2)
|
||||
if (validator[validationName].apply(validator, validationOptions) !== goodResult) {
|
||||
// CASE: You can define specific translations for validators e.g. isLength
|
||||
if (i18n.doesTranslationKeyExist('notices.data.validation.index.validationFailedTypes.' + validationName)) {
|
||||
translation = i18n.t('notices.data.validation.index.validationFailedTypes.' + validationName, _.merge({
|
||||
if (common.i18n.doesTranslationKeyExist('notices.data.validation.index.validationFailedTypes.' + validationName)) {
|
||||
translation = common.i18n.t('notices.data.validation.index.validationFailedTypes.' + validationName, _.merge({
|
||||
validationName: validationName,
|
||||
key: key,
|
||||
tableName: tableName
|
||||
}, validationOptions[1]));
|
||||
} else {
|
||||
translation = i18n.t('notices.data.validation.index.validationFailed', {validationName: validationName, key: key});
|
||||
translation = common.i18n.t('notices.data.validation.index.validationFailed', {
|
||||
validationName: validationName,
|
||||
key: key
|
||||
});
|
||||
}
|
||||
|
||||
validationErrors.push(new errors.ValidationError({
|
||||
validationErrors.push(new common.errors.ValidationError({
|
||||
message: translation
|
||||
}));
|
||||
}
|
||||
|
|
|
@ -4,7 +4,7 @@ var _ = require('lodash'),
|
|||
Promise = require('bluebird'),
|
||||
path = require('path'),
|
||||
urlService = require('../../../services/url'),
|
||||
events = require('../../../lib/common/events'),
|
||||
common = require('../../../lib/common'),
|
||||
localUtils = require('./utils'),
|
||||
CHANGE_FREQ = 'weekly',
|
||||
XMLNS_DECLS;
|
||||
|
@ -22,7 +22,7 @@ function BaseSiteMapGenerator() {
|
|||
this.nodeLookup = {};
|
||||
this.nodeTimeLookup = {};
|
||||
this.siteMapContent = '';
|
||||
this.dataEvents = events;
|
||||
this.dataEvents = common.events;
|
||||
}
|
||||
|
||||
_.extend(BaseSiteMapGenerator.prototype, {
|
||||
|
|
|
@ -5,12 +5,9 @@ var debug = require('ghost-ignition').debug('server'),
|
|||
fs = require('fs'),
|
||||
path = require('path'),
|
||||
_ = require('lodash'),
|
||||
errors = require('./lib/common/errors'),
|
||||
events = require('./lib/common/events'),
|
||||
logging = require('./lib/common/logging'),
|
||||
config = require('./config'),
|
||||
urlService = require('./services/url'),
|
||||
i18n = require('./lib/common/i18n'),
|
||||
common = require('./lib/common'),
|
||||
moment = require('moment');
|
||||
|
||||
/**
|
||||
|
@ -79,16 +76,16 @@ GhostServer.prototype.start = function (externalApp) {
|
|||
var ghostError;
|
||||
|
||||
if (error.errno === 'EADDRINUSE') {
|
||||
ghostError = new errors.GhostError({
|
||||
message: i18n.t('errors.httpServer.addressInUse.error'),
|
||||
context: i18n.t('errors.httpServer.addressInUse.context', {port: config.get('server').port}),
|
||||
help: i18n.t('errors.httpServer.addressInUse.help')
|
||||
ghostError = new common.errors.GhostError({
|
||||
message: common.i18n.t('errors.httpServer.addressInUse.error'),
|
||||
context: common.i18n.t('errors.httpServer.addressInUse.context', {port: config.get('server').port}),
|
||||
help: common.i18n.t('errors.httpServer.addressInUse.help')
|
||||
});
|
||||
} else {
|
||||
ghostError = new errors.GhostError({
|
||||
message: i18n.t('errors.httpServer.otherError.error', {errorNumber: error.errno}),
|
||||
context: i18n.t('errors.httpServer.otherError.context'),
|
||||
help: i18n.t('errors.httpServer.otherError.help')
|
||||
ghostError = new common.errors.GhostError({
|
||||
message: common.i18n.t('errors.httpServer.otherError.error', {errorNumber: error.errno}),
|
||||
context: common.i18n.t('errors.httpServer.otherError.context'),
|
||||
help: common.i18n.t('errors.httpServer.otherError.help')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -97,7 +94,7 @@ GhostServer.prototype.start = function (externalApp) {
|
|||
self.httpServer.on('connection', self.connection.bind(self));
|
||||
self.httpServer.on('listening', function () {
|
||||
debug('...Started');
|
||||
events.emit('server:start');
|
||||
common.events.emit('server:start');
|
||||
self.logStartMessages();
|
||||
resolve(self);
|
||||
});
|
||||
|
@ -118,7 +115,7 @@ GhostServer.prototype.stop = function () {
|
|||
resolve(self);
|
||||
} else {
|
||||
self.httpServer.close(function () {
|
||||
events.emit('server:stop');
|
||||
common.events.emit('server:stop');
|
||||
self.httpServer = null;
|
||||
self.logShutdownMessages();
|
||||
resolve(self);
|
||||
|
@ -145,7 +142,7 @@ GhostServer.prototype.restart = function () {
|
|||
* To be called after `stop`
|
||||
*/
|
||||
GhostServer.prototype.hammertime = function () {
|
||||
logging.info(i18n.t('notices.httpServer.cantTouchThis'));
|
||||
common.logging.info(common.i18n.t('notices.httpServer.cantTouchThis'));
|
||||
|
||||
return Promise.resolve(this);
|
||||
};
|
||||
|
@ -192,27 +189,27 @@ GhostServer.prototype.closeConnections = function () {
|
|||
GhostServer.prototype.logStartMessages = function () {
|
||||
// Startup & Shutdown messages
|
||||
if (config.get('env') === 'production') {
|
||||
logging.info(i18n.t('notices.httpServer.ghostIsRunningIn', {env: config.get('env')}));
|
||||
logging.info(i18n.t('notices.httpServer.yourBlogIsAvailableOn', {url: urlService.utils.urlFor('home', true)}));
|
||||
logging.info(i18n.t('notices.httpServer.ctrlCToShutDown'));
|
||||
common.logging.info(common.i18n.t('notices.httpServer.ghostIsRunningIn', {env: config.get('env')}));
|
||||
common.logging.info(common.i18n.t('notices.httpServer.yourBlogIsAvailableOn', {url: urlService.utils.urlFor('home', true)}));
|
||||
common.logging.info(common.i18n.t('notices.httpServer.ctrlCToShutDown'));
|
||||
} else {
|
||||
logging.info(i18n.t('notices.httpServer.ghostIsRunningIn', {env: config.get('env')}));
|
||||
logging.info(i18n.t('notices.httpServer.listeningOn', {
|
||||
common.logging.info(common.i18n.t('notices.httpServer.ghostIsRunningIn', {env: config.get('env')}));
|
||||
common.logging.info(common.i18n.t('notices.httpServer.listeningOn', {
|
||||
host: config.get('server').socket || config.get('server').host,
|
||||
port: config.get('server').port
|
||||
}));
|
||||
logging.info(i18n.t('notices.httpServer.urlConfiguredAs', {url: urlService.utils.urlFor('home', true)}));
|
||||
logging.info(i18n.t('notices.httpServer.ctrlCToShutDown'));
|
||||
common.logging.info(common.i18n.t('notices.httpServer.urlConfiguredAs', {url: urlService.utils.urlFor('home', true)}));
|
||||
common.logging.info(common.i18n.t('notices.httpServer.ctrlCToShutDown'));
|
||||
}
|
||||
|
||||
function shutdown() {
|
||||
logging.warn(i18n.t('notices.httpServer.ghostHasShutdown'));
|
||||
common.logging.warn(common.i18n.t('notices.httpServer.ghostHasShutdown'));
|
||||
|
||||
if (config.get('env') === 'production') {
|
||||
logging.warn(i18n.t('notices.httpServer.yourBlogIsNowOffline'));
|
||||
common.logging.warn(common.i18n.t('notices.httpServer.yourBlogIsNowOffline'));
|
||||
} else {
|
||||
logging.warn(
|
||||
i18n.t('notices.httpServer.ghostWasRunningFor'),
|
||||
common.logging.warn(
|
||||
common.i18n.t('notices.httpServer.ghostWasRunningFor'),
|
||||
moment.duration(process.uptime(), 'seconds').humanize()
|
||||
);
|
||||
}
|
||||
|
@ -228,7 +225,7 @@ GhostServer.prototype.logStartMessages = function () {
|
|||
* ### Log Shutdown Messages
|
||||
*/
|
||||
GhostServer.prototype.logShutdownMessages = function () {
|
||||
logging.warn(i18n.t('notices.httpServer.ghostIsClosingConnections'));
|
||||
common.logging.warn(common.i18n.t('notices.httpServer.ghostIsClosingConnections'));
|
||||
};
|
||||
|
||||
module.exports = GhostServer;
|
||||
|
|
|
@ -173,7 +173,7 @@ module.exports = function ghost_head(options) { // eslint-disable-line camelcase
|
|||
escapeExpression(safeVersion) + '" />');
|
||||
|
||||
head.push('<link rel="alternate" type="application/rss+xml" title="' +
|
||||
escapeExpression(metaData.blog.title) + '" href="' +
|
||||
escapeExpression(metaData.blog.title) + '" href="' +
|
||||
escapeExpression(metaData.rssUrl) + '" />');
|
||||
|
||||
// no code injection for amp context!!!
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
|
||||
// Usage:
|
||||
// `{{img_url feature_image}}`
|
||||
// `{{img_url profile_image absolute="true"}}`
|
||||
|
@ -9,14 +8,12 @@
|
|||
// `absolute` flag outputs absolute URL, else URL is relative.
|
||||
|
||||
var proxy = require('./proxy'),
|
||||
logging = require('../lib/common/logging'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
url = proxy.url;
|
||||
|
||||
module.exports = function imgUrl(attr, options) {
|
||||
// CASE: if no attribute is passed, e.g. `{{img_url}}` we show a warning
|
||||
if (arguments.length < 2) {
|
||||
logging.warn(i18n.t('warnings.helpers.img_url.attrIsRequired'));
|
||||
proxy.logging.warn(proxy.i18n.t('warnings.helpers.img_url.attrIsRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -25,7 +22,7 @@ module.exports = function imgUrl(attr, options) {
|
|||
// CASE: if attribute is passed, but it is undefined, then the attribute was
|
||||
// an unknown value, e.g. {{img_url feature_img}} and we also show a warning
|
||||
if (attr === undefined) {
|
||||
logging.warn(i18n.t('warnings.helpers.img_url.attrIsRequired'));
|
||||
proxy.logging.warn(proxy.i18n.t('warnings.helpers.img_url.attrIsRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
var hbs = require('../themes/engine'),
|
||||
Promise = require('bluebird'),
|
||||
config = require('../config'),
|
||||
errors = require('../lib/common/errors'),
|
||||
logging = require('../lib/common/logging');
|
||||
proxy = require('./proxy');
|
||||
|
||||
// Register an async handlebars helper for a given handlebars instance
|
||||
function asyncHelperWrapper(hbs, name, fn) {
|
||||
|
@ -17,7 +16,7 @@ function asyncHelperWrapper(hbs, name, fn) {
|
|||
Promise.resolve(fn.call(this, context, options)).then(function asyncHelperSuccess(result) {
|
||||
cb(result);
|
||||
}).catch(function asyncHelperError(err) {
|
||||
var wrappedErr = err instanceof errors.GhostError ? err : new errors.IncorrectUsageError({
|
||||
var wrappedErr = err instanceof proxy.errors.GhostError ? err : new proxy.errors.IncorrectUsageError({
|
||||
err: err,
|
||||
context: 'registerAsyncThemeHelper: ' + name,
|
||||
errorDetails: {
|
||||
|
@ -26,7 +25,7 @@ function asyncHelperWrapper(hbs, name, fn) {
|
|||
}),
|
||||
result = config.get('env') === 'development' ? wrappedErr : '';
|
||||
|
||||
logging.error(wrappedErr);
|
||||
proxy.logging.error(wrappedErr);
|
||||
|
||||
cb(new hbs.SafeString(result));
|
||||
});
|
||||
|
|
|
@ -1,9 +1,7 @@
|
|||
var templates = {},
|
||||
|
||||
_ = require('lodash'),
|
||||
hbs = require('../themes/engine'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n');
|
||||
proxy = require('./proxy'),
|
||||
hbs = require('../themes/engine');
|
||||
|
||||
// ## Template utils
|
||||
|
||||
|
@ -13,8 +11,8 @@ templates.execute = function execute(name, context, options) {
|
|||
var partial = hbs.handlebars.partials[name];
|
||||
|
||||
if (partial === undefined) {
|
||||
throw new errors.IncorrectUsageError({
|
||||
message: i18n.t('warnings.helpers.template.templateNotFound', {name: name})
|
||||
throw new proxy.errors.IncorrectUsageError({
|
||||
message: proxy.i18n.t('warnings.helpers.template.templateNotFound', {name: name})
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -16,7 +16,7 @@ require('./overrides');
|
|||
var debug = require('ghost-ignition').debug('boot:init'),
|
||||
config = require('./config'),
|
||||
Promise = require('bluebird'),
|
||||
i18n = require('./lib/common/i18n'),
|
||||
common = require('./lib/common'),
|
||||
models = require('./models'),
|
||||
permissions = require('./permissions'),
|
||||
auth = require('./auth'),
|
||||
|
@ -40,7 +40,7 @@ function init() {
|
|||
var ghostServer, parentApp;
|
||||
|
||||
// Initialize Internationalization
|
||||
i18n.init();
|
||||
common.i18n.init();
|
||||
debug('I18n done');
|
||||
models.init();
|
||||
debug('models done');
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
var events = require('events'),
|
||||
util = require('util'),
|
||||
var events = require('events'),
|
||||
util = require('util'),
|
||||
EventRegistry,
|
||||
EventRegistryInstance;
|
||||
|
||||
|
|
|
@ -4,9 +4,8 @@ var _ = require('lodash'),
|
|||
Promise = require('bluebird'),
|
||||
validator = require('validator'),
|
||||
config = require('../config'),
|
||||
errors = require('../lib/common/errors'),
|
||||
common = require('../lib/common'),
|
||||
settingsCache = require('../settings/cache'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
urlService = require('../services/url');
|
||||
|
||||
function GhostMailer() {
|
||||
|
@ -31,7 +30,7 @@ GhostMailer.prototype.from = function () {
|
|||
|
||||
// If we do have a from address, and it's just an email
|
||||
if (validator.isEmail(from)) {
|
||||
defaultBlogTitle = settingsCache.get('title') ? settingsCache.get('title').replace(/"/g, '\\"') : i18n.t('common.mail.title', {domain: this.getDomain()});
|
||||
defaultBlogTitle = settingsCache.get('title') ? settingsCache.get('title').replace(/"/g, '\\"') : common.i18n.t('common.mail.title', {domain: this.getDomain()});
|
||||
from = '"' + defaultBlogTitle + '" <' + from + '>';
|
||||
}
|
||||
|
||||
|
@ -49,16 +48,16 @@ GhostMailer.prototype.getDomain = function () {
|
|||
GhostMailer.prototype.send = function (message) {
|
||||
var self = this,
|
||||
to,
|
||||
help = i18n.t('errors.api.authentication.checkEmailConfigInstructions', {url: 'http://docs.ghost.org/v1/docs/mail-config'}),
|
||||
errorMessage = i18n.t('errors.mail.failedSendingEmail.error');
|
||||
help = common.i18n.t('errors.api.authentication.checkEmailConfigInstructions', {url: 'http://docs.ghost.org/v1/docs/mail-config'}),
|
||||
errorMessage = common.i18n.t('errors.mail.failedSendingEmail.error');
|
||||
|
||||
// important to clone message as we modify it
|
||||
message = _.clone(message) || {};
|
||||
to = message.to || false;
|
||||
|
||||
if (!(message && message.subject && message.html && message.to)) {
|
||||
return Promise.reject(new errors.EmailError({
|
||||
message: i18n.t('errors.mail.incompleteMessageData.error'),
|
||||
return Promise.reject(new common.errors.EmailError({
|
||||
message: common.i18n.t('errors.mail.incompleteMessageData.error'),
|
||||
help: help
|
||||
}));
|
||||
}
|
||||
|
@ -73,9 +72,9 @@ GhostMailer.prototype.send = function (message) {
|
|||
return new Promise(function (resolve, reject) {
|
||||
self.transport.sendMail(message, function (err, response) {
|
||||
if (err) {
|
||||
errorMessage += i18n.t('errors.mail.reason', {reason: err.message || err});
|
||||
errorMessage += common.i18n.t('errors.mail.reason', {reason: err.message || err});
|
||||
|
||||
return reject(new errors.EmailError({
|
||||
return reject(new common.errors.EmailError({
|
||||
message: errorMessage,
|
||||
err: err,
|
||||
help: help
|
||||
|
@ -88,10 +87,10 @@ GhostMailer.prototype.send = function (message) {
|
|||
|
||||
response.statusHandler.once('failed', function (data) {
|
||||
if (data.error && data.error.errno === 'ENOTFOUND') {
|
||||
errorMessage += i18n.t('errors.mail.noMailServerAtAddress.error', {domain: data.domain});
|
||||
errorMessage += common.i18n.t('errors.mail.noMailServerAtAddress.error', {domain: data.domain});
|
||||
}
|
||||
|
||||
return reject(new errors.EmailError({
|
||||
return reject(new common.errors.EmailError({
|
||||
message: errorMessage,
|
||||
help: help
|
||||
}));
|
||||
|
@ -99,17 +98,17 @@ GhostMailer.prototype.send = function (message) {
|
|||
|
||||
response.statusHandler.once('requeue', function (data) {
|
||||
if (data.error && data.error.message) {
|
||||
errorMessage += i18n.t('errors.mail.reason', {reason: data.error.message});
|
||||
errorMessage += common.i18n.t('errors.mail.reason', {reason: data.error.message});
|
||||
}
|
||||
|
||||
return reject(new errors.EmailError({
|
||||
return reject(new common.errors.EmailError({
|
||||
message: errorMessage,
|
||||
help: help
|
||||
}));
|
||||
});
|
||||
|
||||
response.statusHandler.once('sent', function () {
|
||||
return resolve(i18n.t('notices.mail.messageSent'));
|
||||
return resolve(common.i18n.t('notices.mail.messageSent'));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
var ghostBookshelf = require('./base'),
|
||||
Basetoken = require('./base/token'),
|
||||
events = require('../lib/common/events'),
|
||||
var ghostBookshelf = require('./base'),
|
||||
Basetoken = require('./base/token'),
|
||||
common = require('../lib/common'),
|
||||
|
||||
Accesstoken,
|
||||
Accesstokens;
|
||||
|
@ -10,7 +10,7 @@ Accesstoken = Basetoken.extend({
|
|||
|
||||
emitChange: function emitChange(event) {
|
||||
// Event named 'token' as access and refresh token will be merged in future, see #6626
|
||||
events.emit('token' + '.' + event, this);
|
||||
common.events.emit('token' + '.' + event, this);
|
||||
},
|
||||
|
||||
onCreated: function onCreated(model) {
|
||||
|
|
|
@ -12,14 +12,13 @@ var _ = require('lodash'),
|
|||
ObjectId = require('bson-objectid'),
|
||||
config = require('../../config'),
|
||||
db = require('../../data/db'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
common = require('../../lib/common'),
|
||||
filters = require('../../filters'),
|
||||
schema = require('../../data/schema'),
|
||||
urlService = require('../../services/url'),
|
||||
globalUtils = require('../../utils'),
|
||||
validation = require('../../data/validation'),
|
||||
plugins = require('../plugins'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
|
||||
ghostBookshelf,
|
||||
proto;
|
||||
|
@ -309,8 +308,8 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
|
|||
} else if (options.context.external) {
|
||||
return ghostBookshelf.Model.externalUser;
|
||||
} else {
|
||||
throw new errors.NotFoundError({
|
||||
message: i18n.t('errors.models.base.index.missingContext'),
|
||||
throw new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.models.base.index.missingContext'),
|
||||
level: 'critical'
|
||||
});
|
||||
}
|
||||
|
@ -462,8 +461,8 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
|
|||
|
||||
// CASE: client sends `0000-00-00 00:00:00`
|
||||
if (!dateMoment.isValid()) {
|
||||
throw new errors.ValidationError({
|
||||
message: i18n.t('errors.models.base.invalidDate', {key: key})
|
||||
throw new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.models.base.invalidDate', {key: key})
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -1,18 +1,16 @@
|
|||
var moment = require('moment-timezone'),
|
||||
_ = require('lodash'),
|
||||
models = require('../../models'),
|
||||
events = require('../../lib/common/events'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
common = require('../../lib/common'),
|
||||
sequence = require('../../utils/sequence');
|
||||
|
||||
/**
|
||||
* WHEN access token is created we will update last_seen for user.
|
||||
*/
|
||||
events.on('token.added', function (tokenModel) {
|
||||
common.events.on('token.added', function (tokenModel) {
|
||||
models.User.edit({last_seen: moment().toDate()}, {id: tokenModel.get('user_id')})
|
||||
.catch(function (err) {
|
||||
logging.error(new errors.GhostError({err: err, level: 'critical'}));
|
||||
common.logging.error(new common.errors.GhostError({err: err, level: 'critical'}));
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -25,7 +23,7 @@ events.on('token.added', function (tokenModel) {
|
|||
* - if an active user get's deleted, we have to access the previous attributes, because this is how bookshelf works
|
||||
* if you delete a user.
|
||||
*/
|
||||
events.on('user.deactivated', function (userModel, options) {
|
||||
common.events.on('user.deactivated', function (userModel, options) {
|
||||
options = options || {};
|
||||
options = _.merge({}, options, {id: userModel.id || userModel.previousAttributes().id});
|
||||
|
||||
|
@ -38,7 +36,7 @@ events.on('user.deactivated', function (userModel, options) {
|
|||
return models.Refreshtoken.destroyByUser(options);
|
||||
})
|
||||
.catch(function (err) {
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
level: 'critical'
|
||||
}));
|
||||
|
@ -50,7 +48,7 @@ events.on('user.deactivated', function (userModel, options) {
|
|||
* - reschedule all scheduled posts
|
||||
* - draft scheduled posts, when the published_at would be in the past
|
||||
*/
|
||||
events.on('settings.active_timezone.edited', function (settingModel, options) {
|
||||
common.events.on('settings.active_timezone.edited', function (settingModel, options) {
|
||||
options = options || {};
|
||||
options = _.merge({}, options, {context: {internal: true}});
|
||||
|
||||
|
@ -108,14 +106,14 @@ events.on('settings.active_timezone.edited', function (settingModel, options) {
|
|||
};
|
||||
})).each(function (result) {
|
||||
if (!result.isFulfilled()) {
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: result.reason()
|
||||
}));
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch(function (err) {
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
level: 'critical'
|
||||
}));
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
var Promise = require('bluebird'),
|
||||
ghostBookshelf = require('./index'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
|
||||
var Promise = require('bluebird'),
|
||||
ghostBookshelf = require('./index'),
|
||||
common = require('../../lib/common'),
|
||||
Basetoken;
|
||||
|
||||
Basetoken = ghostBookshelf.Model.extend({
|
||||
|
@ -51,7 +49,7 @@ Basetoken = ghostBookshelf.Model.extend({
|
|||
});
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.models.base.token.noUserFound')}));
|
||||
return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.models.base.token.noUserFound')}));
|
||||
},
|
||||
|
||||
/**
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
ObjectId = require('bson-objectid'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
common = require('../../lib/common'),
|
||||
attach, detach;
|
||||
|
||||
/**
|
||||
|
@ -32,7 +32,7 @@ attach = function attach(Model, effectedModelId, relation, modelsToAttach, optio
|
|||
fetchedModel = _fetchedModel;
|
||||
|
||||
if (!fetchedModel) {
|
||||
throw new errors.NotFoundError({level: 'critical', help: effectedModelId});
|
||||
throw new common.errors.NotFoundError({level: 'critical', help: effectedModelId});
|
||||
}
|
||||
|
||||
fetchedModel.related(relation).on('creating', function (collection, data) {
|
||||
|
@ -74,7 +74,7 @@ detach = function detach(Model, effectedModelId, relation, modelsToAttach, optio
|
|||
fetchedModel = _fetchedModel;
|
||||
|
||||
if (!fetchedModel) {
|
||||
throw new errors.NotFoundError({level: 'critical', help: effectedModelId});
|
||||
throw new common.errors.NotFoundError({level: 'critical', help: effectedModelId});
|
||||
}
|
||||
|
||||
return Promise.resolve(modelsToAttach)
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var moment = require('moment-timezone'),
|
||||
Promise = require('bluebird'),
|
||||
_ = require('lodash'),
|
||||
errors = require('../../lib/common/errors');
|
||||
common = require('../../lib/common');
|
||||
|
||||
module.exports = function (Bookshelf) {
|
||||
var ParentModel = Bookshelf.Model,
|
||||
|
@ -56,7 +56,7 @@ module.exports = function (Bookshelf) {
|
|||
if (Object.keys(changed).length) {
|
||||
if (clientUpdatedAt.diff(serverUpdatedAt) !== 0) {
|
||||
// @TODO: Remove later. We want to figure out how many people experience the error in which context.
|
||||
return Promise.reject(new errors.UpdateCollisionError({
|
||||
return Promise.reject(new common.errors.UpdateCollisionError({
|
||||
message: 'Saving failed! Someone else is editing this post.',
|
||||
code: 'UPDATE_COLLISION',
|
||||
level: 'critical',
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
var _ = require('lodash'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
gql = require('ghost-gql'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
filter,
|
||||
filterUtils;
|
||||
|
||||
|
@ -25,11 +24,11 @@ filterUtils = {
|
|||
return _.isString(arg) ? gql.parse(arg) : arg;
|
||||
});
|
||||
} catch (err) {
|
||||
throw new errors.ValidationError({
|
||||
throw new common.errors.ValidationError({
|
||||
err: err,
|
||||
property: 'filter',
|
||||
context: i18n.t('errors.models.plugins.filter.errorParsing'),
|
||||
help: i18n.t('errors.models.plugins.filter.forInformationRead', {url: 'http://api.ghost.org/docs/filter'})
|
||||
context: common.i18n.t('errors.models.plugins.filter.errorParsing'),
|
||||
help: common.i18n.t('errors.models.plugins.filter.forInformationRead', {url: 'http://api.ghost.org/docs/filter'})
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -80,17 +79,21 @@ filter = function filter(Bookshelf) {
|
|||
// Cached copy of the filters setup for this model instance
|
||||
_filters: null,
|
||||
// Override these on the various models
|
||||
enforcedFilters: function enforcedFilters() {},
|
||||
defaultFilters: function defaultFilters() {},
|
||||
enforcedFilters: function enforcedFilters() {
|
||||
},
|
||||
defaultFilters: function defaultFilters() {
|
||||
},
|
||||
|
||||
preProcessFilters: function preProcessFilters() {
|
||||
this._filters.statements = gql.json.replaceStatements(this._filters.statements, {prop: /primary_tag/}, function (statement) {
|
||||
statement.prop = 'tags.slug';
|
||||
return {group: [
|
||||
statement,
|
||||
{prop: 'posts_tags.sort_order', op: '=', value: 0},
|
||||
{prop: 'tags.visibility', op: '=', value: 'public'}
|
||||
]};
|
||||
return {
|
||||
group: [
|
||||
statement,
|
||||
{prop: 'posts_tags.sort_order', op: '=', value: 0},
|
||||
{prop: 'tags.visibility', op: '=', value: 'public'}
|
||||
]
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
|
|
|
@ -2,8 +2,7 @@
|
|||
//
|
||||
// Extends Bookshelf.Model with a `fetchPage` method. Handles everything to do with paginated requests.
|
||||
var _ = require('lodash'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
defaults,
|
||||
paginationUtils,
|
||||
pagination;
|
||||
|
@ -195,7 +194,7 @@ pagination = function pagination(bookshelf) {
|
|||
.catch(function (err) {
|
||||
// e.g. offset/limit reached max allowed integer value
|
||||
if (err.errno === 20 || err.errno === 1064) {
|
||||
throw new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')});
|
||||
throw new common.errors.NotFoundError({message: common.i18n.t('errors.errors.pageNotFound')});
|
||||
}
|
||||
|
||||
throw err;
|
||||
|
|
|
@ -7,14 +7,12 @@ var _ = require('lodash'),
|
|||
Promise = require('bluebird'),
|
||||
ObjectId = require('bson-objectid'),
|
||||
sequence = require('../utils/sequence'),
|
||||
errors = require('../lib/common/errors'),
|
||||
common = require('../lib/common'),
|
||||
htmlToText = require('html-to-text'),
|
||||
ghostBookshelf = require('./base'),
|
||||
events = require('../lib/common/events'),
|
||||
config = require('../config'),
|
||||
globalUtils = require('../utils'),
|
||||
urlService = require('../services/url'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
Post,
|
||||
Posts;
|
||||
|
||||
|
@ -48,7 +46,7 @@ Post = ghostBookshelf.Model.extend({
|
|||
resourceType = this.updated('page') ? 'page' : 'post';
|
||||
}
|
||||
|
||||
events.emit(resourceType + '.' + event, this, options);
|
||||
common.events.emit(resourceType + '.' + event, this, options);
|
||||
},
|
||||
|
||||
defaults: function defaults() {
|
||||
|
@ -168,29 +166,29 @@ Post = ghostBookshelf.Model.extend({
|
|||
// CASE: disallow published -> scheduled
|
||||
// @TODO: remove when we have versioning based on updated_at
|
||||
if (newStatus !== olderStatus && newStatus === 'scheduled' && olderStatus === 'published') {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('errors.models.post.isAlreadyPublished', {key: 'status'})
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.models.post.isAlreadyPublished', {key: 'status'})
|
||||
}));
|
||||
}
|
||||
|
||||
// CASE: both page and post can get scheduled
|
||||
if (newStatus === 'scheduled') {
|
||||
if (!publishedAt) {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('errors.models.post.valueCannotBeBlank', {key: 'published_at'})
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.models.post.valueCannotBeBlank', {key: 'published_at'})
|
||||
}));
|
||||
} else if (!moment(publishedAt).isValid()) {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('errors.models.post.valueCannotBeBlank', {key: 'published_at'})
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.models.post.valueCannotBeBlank', {key: 'published_at'})
|
||||
}));
|
||||
// CASE: to schedule/reschedule a post, a minimum diff of x minutes is needed (default configured is 2minutes)
|
||||
// CASE: to schedule/reschedule a post, a minimum diff of x minutes is needed (default configured is 2minutes)
|
||||
} else if (
|
||||
publishedAtHasChanged &&
|
||||
moment(publishedAt).isBefore(moment().add(config.get('times').cannotScheduleAPostBeforeInMinutes, 'minutes')) &&
|
||||
!options.importing
|
||||
) {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('errors.models.post.expectedPublishedAtInFuture', {
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.models.post.expectedPublishedAtInFuture', {
|
||||
cannotScheduleAPostBeforeInMinutes: config.get('times').cannotScheduleAPostBeforeInMinutes
|
||||
})
|
||||
}));
|
||||
|
@ -234,7 +232,7 @@ Post = ghostBookshelf.Model.extend({
|
|||
|
||||
// disabling sanitization until we can implement a better version
|
||||
if (!options.importing) {
|
||||
title = this.get('title') || i18n.t('errors.models.post.untitled');
|
||||
title = this.get('title') || common.i18n.t('errors.models.post.untitled');
|
||||
this.set('title', _.toString(title).trim());
|
||||
}
|
||||
|
||||
|
@ -475,10 +473,10 @@ Post = 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.
|
||||
*/
|
||||
* 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 permittedOptions(methodName) {
|
||||
var options = ghostBookshelf.Model.permittedOptions(),
|
||||
|
||||
|
@ -629,8 +627,8 @@ Post = ghostBookshelf.Model.extend({
|
|||
opts = this.filterOptions(opts, 'destroyByAuthor');
|
||||
|
||||
if (!authorId) {
|
||||
throw new errors.NotFoundError({
|
||||
message: i18n.t('errors.models.post.noUserFound')
|
||||
throw new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.models.post.noUserFound')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -640,7 +638,7 @@ Post = ghostBookshelf.Model.extend({
|
|||
.fetch(opts)
|
||||
.call('invokeThen', 'destroy', opts)
|
||||
.catch((err) => {
|
||||
throw new errors.GhostError({err: err});
|
||||
throw new common.errors.GhostError({err: err});
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -698,7 +696,7 @@ Post = ghostBookshelf.Model.extend({
|
|||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.models.post.notEnoughPermission')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.models.post.notEnoughPermission')}));
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
errors = require('../lib/common/errors'),
|
||||
var _ = require('lodash'),
|
||||
ghostBookshelf = require('./base'),
|
||||
Promise = require('bluebird'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
Promise = require('bluebird'),
|
||||
common = require('../lib/common'),
|
||||
|
||||
Role,
|
||||
Roles;
|
||||
|
@ -20,10 +19,10 @@ Role = 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.
|
||||
*/
|
||||
* 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 permittedOptions(methodName) {
|
||||
var options = ghostBookshelf.Model.permittedOptions(),
|
||||
|
||||
|
@ -78,7 +77,7 @@ Role = ghostBookshelf.Model.extend({
|
|||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.models.role.notEnoughPermission')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.models.role.notEnoughPermission')}));
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
@ -1,13 +1,11 @@
|
|||
var Settings,
|
||||
Promise = require('bluebird'),
|
||||
_ = require('lodash'),
|
||||
uuid = require('uuid'),
|
||||
crypto = require('crypto'),
|
||||
Promise = require('bluebird'),
|
||||
_ = require('lodash'),
|
||||
uuid = require('uuid'),
|
||||
crypto = require('crypto'),
|
||||
ghostBookshelf = require('./base'),
|
||||
errors = require('../lib/common/errors'),
|
||||
events = require('../lib/common/events'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
validation = require('../data/validation'),
|
||||
common = require('../lib/common'),
|
||||
validation = require('../data/validation'),
|
||||
|
||||
internalContext = {context: {internal: true}},
|
||||
|
||||
|
@ -60,7 +58,7 @@ Settings = ghostBookshelf.Model.extend({
|
|||
},
|
||||
|
||||
emitChange: function emitChange(event, options) {
|
||||
events.emit('settings' + '.' + event, this, options);
|
||||
common.events.emit('settings' + '.' + event, this, options);
|
||||
},
|
||||
|
||||
onDestroyed: function onDestroyed(model, response, options) {
|
||||
|
@ -110,9 +108,11 @@ Settings = ghostBookshelf.Model.extend({
|
|||
|
||||
return Promise.map(data, function (item) {
|
||||
// Accept an array of models as input
|
||||
if (item.toJSON) { item = item.toJSON(); }
|
||||
if (item.toJSON) {
|
||||
item = item.toJSON();
|
||||
}
|
||||
if (!(_.isString(item.key) && item.key.length > 0)) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.models.settings.valueCannotBeBlank')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.models.settings.valueCannotBeBlank')}));
|
||||
}
|
||||
|
||||
item = self.filterData(item);
|
||||
|
@ -141,7 +141,7 @@ Settings = ghostBookshelf.Model.extend({
|
|||
}
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.models.settings.unableToFindSetting', {key: item.key})}));
|
||||
return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.models.settings.unableToFindSetting', {key: item.key})}));
|
||||
});
|
||||
});
|
||||
},
|
||||
|
@ -154,7 +154,9 @@ Settings = ghostBookshelf.Model.extend({
|
|||
return this
|
||||
.findAll(options)
|
||||
.then(function checkAllSettings(allSettings) {
|
||||
var usedKeys = allSettings.models.map(function mapper(setting) { return setting.get('key'); }),
|
||||
var usedKeys = allSettings.models.map(function mapper(setting) {
|
||||
return setting.get('key');
|
||||
}),
|
||||
insertOperations = [];
|
||||
|
||||
_.each(getDefaultSettings(), function forEachDefault(defaultSetting, defaultSettingKey) {
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
var ghostBookshelf = require('./base'),
|
||||
errors = require('../lib/common/errors'),
|
||||
events = require('../lib/common/events'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
Promise = require('bluebird'),
|
||||
var Promise = require('bluebird'),
|
||||
ghostBookshelf = require('./base'),
|
||||
common = require('../lib/common'),
|
||||
Subscriber,
|
||||
Subscribers;
|
||||
|
||||
|
@ -12,7 +10,7 @@ Subscriber = ghostBookshelf.Model.extend({
|
|||
emitChange: function emitChange(event, options) {
|
||||
options = options || {};
|
||||
|
||||
events.emit('subscriber' + '.' + event, this, options);
|
||||
common.events.emit('subscriber' + '.' + event, this, options);
|
||||
},
|
||||
|
||||
defaults: function defaults() {
|
||||
|
@ -73,7 +71,7 @@ Subscriber = ghostBookshelf.Model.extend({
|
|||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.models.subscriber.notEnoughPermission')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.models.subscriber.notEnoughPermission')}));
|
||||
},
|
||||
|
||||
// TODO: This is a copy paste of models/user.js!
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
var _ = require('lodash'),
|
||||
var _ = require('lodash'),
|
||||
ghostBookshelf = require('./base'),
|
||||
events = require('../lib/common/events'),
|
||||
common = require('../lib/common'),
|
||||
Tag,
|
||||
Tags;
|
||||
|
||||
|
@ -15,7 +15,7 @@ Tag = ghostBookshelf.Model.extend({
|
|||
},
|
||||
|
||||
emitChange: function emitChange(event) {
|
||||
events.emit('tag' + '.' + event, this);
|
||||
common.events.emit('tag' + '.' + event, this);
|
||||
},
|
||||
|
||||
onCreated: function onCreated(model) {
|
||||
|
|
|
@ -1,29 +1,26 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
bcrypt = require('bcryptjs'),
|
||||
validator = require('validator'),
|
||||
ObjectId = require('bson-objectid'),
|
||||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
bcrypt = require('bcryptjs'),
|
||||
validator = require('validator'),
|
||||
ObjectId = require('bson-objectid'),
|
||||
ghostBookshelf = require('./base'),
|
||||
baseUtils = require('./base/utils'),
|
||||
errors = require('../lib/common/errors'),
|
||||
logging = require('../lib/common/logging'),
|
||||
utils = require('../utils'),
|
||||
gravatar = require('../utils/gravatar'),
|
||||
validation = require('../data/validation'),
|
||||
events = require('../lib/common/events'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
pipeline = require('../utils/pipeline'),
|
||||
baseUtils = require('./base/utils'),
|
||||
common = require('../lib/common'),
|
||||
utils = require('../utils'),
|
||||
gravatar = require('../utils/gravatar'),
|
||||
validation = require('../data/validation'),
|
||||
pipeline = require('../utils/pipeline'),
|
||||
|
||||
bcryptGenSalt = Promise.promisify(bcrypt.genSalt),
|
||||
bcryptHash = Promise.promisify(bcrypt.hash),
|
||||
bcryptCompare = Promise.promisify(bcrypt.compare),
|
||||
activeStates = ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4'],
|
||||
bcryptGenSalt = Promise.promisify(bcrypt.genSalt),
|
||||
bcryptHash = Promise.promisify(bcrypt.hash),
|
||||
bcryptCompare = Promise.promisify(bcrypt.compare),
|
||||
activeStates = ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4'],
|
||||
/**
|
||||
* inactive: owner user before blog setup, suspended users
|
||||
* locked user: imported users, they get a random passport
|
||||
*/
|
||||
inactiveStates = ['inactive', 'locked'],
|
||||
allStates = activeStates.concat(inactiveStates),
|
||||
inactiveStates = ['inactive', 'locked'],
|
||||
allStates = activeStates.concat(inactiveStates),
|
||||
User,
|
||||
Users;
|
||||
|
||||
|
@ -49,7 +46,7 @@ User = ghostBookshelf.Model.extend({
|
|||
},
|
||||
|
||||
emitChange: function emitChange(event, options) {
|
||||
events.emit('user' + '.' + event, this, options);
|
||||
common.events.emit('user' + '.' + event, this, options);
|
||||
},
|
||||
|
||||
onDestroyed: function onDestroyed(model, response, options) {
|
||||
|
@ -171,7 +168,7 @@ User = ghostBookshelf.Model.extend({
|
|||
passwordValidation = validation.validatePassword(this.get('password'), this.get('email'));
|
||||
|
||||
if (!passwordValidation.isValid) {
|
||||
return Promise.reject(new errors.ValidationError({message: passwordValidation.message}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: passwordValidation.message}));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -322,10 +319,10 @@ User = 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.
|
||||
*/
|
||||
* 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 permittedOptions(methodName, options) {
|
||||
var permittedOptionsToReturn = ghostBookshelf.Model.permittedOptions(),
|
||||
|
||||
|
@ -420,7 +417,7 @@ User = ghostBookshelf.Model.extend({
|
|||
|
||||
if (data.roles && data.roles.length > 1) {
|
||||
return Promise.reject(
|
||||
new errors.ValidationError({message: i18n.t('errors.models.user.onlyOneRolePerUserSupported')})
|
||||
new common.errors.ValidationError({message: common.i18n.t('errors.models.user.onlyOneRolePerUserSupported')})
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -431,7 +428,7 @@ User = ghostBookshelf.Model.extend({
|
|||
ops.push(function checkForDuplicateEmail() {
|
||||
return self.getByEmail(data.email, options).then(function then(user) {
|
||||
if (user && user.id !== options.id) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.models.user.userUpdateError.emailIsAlreadyInUse')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.models.user.userUpdateError.emailIsAlreadyInUse')}));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
@ -456,7 +453,7 @@ User = ghostBookshelf.Model.extend({
|
|||
}).then(function then(roleToAssign) {
|
||||
if (roleToAssign && roleToAssign.get('name') === 'Owner') {
|
||||
return Promise.reject(
|
||||
new errors.ValidationError({message: i18n.t('errors.models.user.methodDoesNotSupportOwnerRole')})
|
||||
new common.errors.ValidationError({message: common.i18n.t('errors.models.user.methodDoesNotSupportOwnerRole')})
|
||||
);
|
||||
} else {
|
||||
// assign all other roles
|
||||
|
@ -496,7 +493,7 @@ User = ghostBookshelf.Model.extend({
|
|||
|
||||
// check for too many roles
|
||||
if (data.roles && data.roles.length > 1) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.models.user.onlyOneRolePerUserSupported')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.models.user.onlyOneRolePerUserSupported')}));
|
||||
}
|
||||
|
||||
function getAuthorRole() {
|
||||
|
@ -569,7 +566,7 @@ User = ghostBookshelf.Model.extend({
|
|||
passwordValidation = validation.validatePassword(userData.password, userData.email, data.blogTitle);
|
||||
|
||||
if (!passwordValidation.isValid) {
|
||||
return Promise.reject(new errors.ValidationError({message: passwordValidation.message}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: passwordValidation.message}));
|
||||
}
|
||||
|
||||
options = this.filterOptions(options, 'setup');
|
||||
|
@ -602,8 +599,8 @@ User = ghostBookshelf.Model.extend({
|
|||
status: 'all'
|
||||
}, options).then(function (owner) {
|
||||
if (!owner) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.models.user.ownerNotFound')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.models.user.ownerNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -626,10 +623,13 @@ User = ghostBookshelf.Model.extend({
|
|||
origArgs = _.toArray(arguments).slice(1);
|
||||
|
||||
// Get the actual user model
|
||||
return this.findOne({id: userModelOrId, status: 'all'}, {include: ['roles']}).then(function then(foundUserModel) {
|
||||
return this.findOne({
|
||||
id: userModelOrId,
|
||||
status: 'all'
|
||||
}, {include: ['roles']}).then(function then(foundUserModel) {
|
||||
if (!foundUserModel) {
|
||||
throw new errors.NotFoundError({
|
||||
message: i18n.t('errors.models.user.userNotFound')
|
||||
throw new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.models.user.userNotFound')
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -664,7 +664,7 @@ User = ghostBookshelf.Model.extend({
|
|||
if (action === 'destroy') {
|
||||
// Owner cannot be deleted EVER
|
||||
if (loadedPermissions.user && userModel.hasRole('Owner')) {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.models.user.notEnoughPermission')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.models.user.notEnoughPermission')}));
|
||||
}
|
||||
|
||||
// Users with the role 'Editor' have complex permissions when the action === 'destroy'
|
||||
|
@ -681,7 +681,7 @@ User = ghostBookshelf.Model.extend({
|
|||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.models.user.notEnoughPermission')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.models.user.notEnoughPermission')}));
|
||||
},
|
||||
|
||||
// Finds the user by email, and checks the password
|
||||
|
@ -691,20 +691,20 @@ User = ghostBookshelf.Model.extend({
|
|||
|
||||
return this.getByEmail(object.email).then(function then(user) {
|
||||
if (!user) {
|
||||
return Promise.reject(new errors.NotFoundError({
|
||||
message: i18n.t('errors.models.user.noUserWithEnteredEmailAddr')
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.models.user.noUserWithEnteredEmailAddr')
|
||||
}));
|
||||
}
|
||||
|
||||
if (user.isLocked()) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
message: i18n.t('errors.models.user.accountLocked')
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.models.user.accountLocked')
|
||||
}));
|
||||
}
|
||||
|
||||
if (user.isInactive()) {
|
||||
return Promise.reject(new errors.NoPermissionError({
|
||||
message: i18n.t('errors.models.user.accountSuspended')
|
||||
return Promise.reject(new common.errors.NoPermissionError({
|
||||
message: common.i18n.t('errors.models.user.accountSuspended')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -714,10 +714,10 @@ User = ghostBookshelf.Model.extend({
|
|||
.catch(function handleError(err) {
|
||||
// If we get a validation or other error during this save, catch it and log it, but don't
|
||||
// cause a login error because of it. The user validation is not important here.
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
context: i18n.t('errors.models.user.userUpdateError.context'),
|
||||
help: i18n.t('errors.models.user.userUpdateError.help')
|
||||
context: common.i18n.t('errors.models.user.userUpdateError.context'),
|
||||
help: common.i18n.t('errors.models.user.userUpdateError.help')
|
||||
}));
|
||||
|
||||
return user;
|
||||
|
@ -728,7 +728,7 @@ User = ghostBookshelf.Model.extend({
|
|||
});
|
||||
}, function handleError(error) {
|
||||
if (error.message === 'NotFound' || error.message === 'EmptyResponse') {
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.models.user.noUserWithEnteredEmailAddr')}));
|
||||
return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.models.user.noUserWithEnteredEmailAddr')}));
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
|
@ -740,8 +740,8 @@ User = ghostBookshelf.Model.extend({
|
|||
hashedPassword = object.hashedPassword;
|
||||
|
||||
if (!plainPassword || !hashedPassword) {
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
message: i18n.t('errors.models.user.passwordRequiredForOperation')
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.models.user.passwordRequiredForOperation')
|
||||
}));
|
||||
}
|
||||
|
||||
|
@ -751,10 +751,10 @@ User = ghostBookshelf.Model.extend({
|
|||
return;
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.ValidationError({
|
||||
context: i18n.t('errors.models.user.incorrectPassword'),
|
||||
message: i18n.t('errors.models.user.incorrectPassword'),
|
||||
help: i18n.t('errors.models.user.userUpdateError.help'),
|
||||
return Promise.reject(new common.errors.ValidationError({
|
||||
context: common.i18n.t('errors.models.user.incorrectPassword'),
|
||||
message: common.i18n.t('errors.models.user.incorrectPassword'),
|
||||
help: common.i18n.t('errors.models.user.userUpdateError.help'),
|
||||
code: 'PASSWORD_INCORRECT'
|
||||
}));
|
||||
});
|
||||
|
@ -804,7 +804,7 @@ User = ghostBookshelf.Model.extend({
|
|||
// check if user has the owner role
|
||||
var currentRoles = contextUser.toJSON(options).roles;
|
||||
if (!_.some(currentRoles, {id: ownerRole.id})) {
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.models.user.onlyOwnerCanTransferOwnerRole')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.models.user.onlyOwnerCanTransferOwnerRole')}));
|
||||
}
|
||||
|
||||
return Promise.join(ghostBookshelf.model('Role').findOne({name: 'Administrator'}),
|
||||
|
@ -816,7 +816,7 @@ User = ghostBookshelf.Model.extend({
|
|||
currentRoles = user.toJSON(options).roles;
|
||||
|
||||
if (!_.some(currentRoles, {id: adminRole.id})) {
|
||||
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.models.user.onlyAdmCanBeAssignedOwnerRole')}));
|
||||
return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.models.user.onlyAdmCanBeAssignedOwnerRole')}));
|
||||
}
|
||||
|
||||
// convert owner to admin
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
var ghostBookshelf = require('./base'),
|
||||
events = require('../lib/common/events'),
|
||||
Promise = require('bluebird'),
|
||||
var Promise = require('bluebird'),
|
||||
ghostBookshelf = require('./base'),
|
||||
common = require('../lib/common'),
|
||||
Webhook,
|
||||
Webhooks;
|
||||
|
||||
|
@ -10,7 +10,7 @@ Webhook = ghostBookshelf.Model.extend({
|
|||
emitChange: function emitChange(event, options) {
|
||||
options = options || {};
|
||||
|
||||
events.emit('webhook' + '.' + event, this, options);
|
||||
common.events.emit('webhook' + '.' + event, this, options);
|
||||
},
|
||||
|
||||
onCreated: function onCreated(model, response, options) {
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
providers = require('./providers'),
|
||||
parseContext = require('./parse-context'),
|
||||
actionsMap = require('./actions-map-cache'),
|
||||
|
@ -10,7 +9,8 @@ var _ = require('lodash'),
|
|||
CanThisResult;
|
||||
|
||||
// Base class for canThis call results
|
||||
CanThisResult = function () {};
|
||||
CanThisResult = function () {
|
||||
};
|
||||
|
||||
CanThisResult.prototype.buildObjectTypeHandlers = function (objTypes, actType, context, permissionLoad) {
|
||||
var objectTypeModelMap = {
|
||||
|
@ -99,7 +99,7 @@ CanThisResult.prototype.buildObjectTypeHandlers = function (objTypes, actType, c
|
|||
return;
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.NoPermissionError({message: i18n.t('errors.permissions.noPermissionToAction')}));
|
||||
return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.permissions.noPermissionToAction')}));
|
||||
});
|
||||
};
|
||||
|
||||
|
@ -117,7 +117,7 @@ CanThisResult.prototype.beginCheck = function (context) {
|
|||
context = parseContext(context);
|
||||
|
||||
if (actionsMap.empty()) {
|
||||
throw new Error(i18n.t('errors.permissions.noActionsMapFound.error'));
|
||||
throw new Error(common.i18n.t('errors.permissions.noActionsMapFound.error'));
|
||||
}
|
||||
|
||||
// Kick off loading of user permissions if necessary
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
models = require('../models'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n');
|
||||
common = require('../lib/common');
|
||||
|
||||
module.exports = {
|
||||
user: function (id) {
|
||||
|
@ -10,7 +9,9 @@ module.exports = {
|
|||
.then(function (foundUser) {
|
||||
// CASE: {context: {user: id}} where the id is not in our database
|
||||
if (!foundUser) {
|
||||
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.models.user.userNotFound')}));
|
||||
return Promise.reject(new common.errors.NotFoundError({
|
||||
message: common.i18n.t('errors.models.user.userNotFound')
|
||||
}));
|
||||
}
|
||||
|
||||
var seenPerms = {},
|
||||
|
|
|
@ -1,12 +1,11 @@
|
|||
var _ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
parseContext = require('./parse-context'),
|
||||
_private = {};
|
||||
|
||||
_private.applyStatusRules = function applyStatusRules(docName, method, opts) {
|
||||
var err = new errors.NoPermissionError({message: i18n.t('errors.permissions.applyStatusRules.error', {docName: docName})});
|
||||
var err = new common.errors.NoPermissionError({message: common.i18n.t('errors.permissions.applyStatusRules.error', {docName: docName})});
|
||||
|
||||
// Enforce status 'active' for users
|
||||
if (docName === 'users') {
|
||||
|
|
|
@ -1,10 +1,8 @@
|
|||
var debug = require('ghost-ignition').debug('services:apps'),
|
||||
_ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
logging = require('../../lib/common/logging'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
api = require('../../api'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
config = require('../../config'),
|
||||
settingsCache = require('../../settings/cache'),
|
||||
loader = require('./loader'),
|
||||
|
@ -31,7 +29,12 @@ function saveInstalledApps(installedApps) {
|
|||
}
|
||||
|
||||
debug('saving settings');
|
||||
return api.settings.edit({settings: [{key: 'installed_apps', value: updatedAppsInstalled}]}, {context: {internal: true}});
|
||||
return api.settings.edit({
|
||||
settings: [{
|
||||
key: 'installed_apps',
|
||||
value: updatedAppsInstalled
|
||||
}]
|
||||
}, {context: {internal: true}});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
@ -65,10 +68,10 @@ module.exports = {
|
|||
return saveInstalledApps(_.keys(availableApps));
|
||||
})
|
||||
.catch(function (err) {
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
context: i18n.t('errors.apps.appWillNotBeLoaded.error'),
|
||||
help: i18n.t('errors.apps.appWillNotBeLoaded.help')
|
||||
context: common.i18n.t('errors.apps.appWillNotBeLoaded.error'),
|
||||
help: common.i18n.t('errors.apps.appWillNotBeLoaded.help')
|
||||
}));
|
||||
});
|
||||
},
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
var path = require('path'),
|
||||
_ = require('lodash'),
|
||||
_ = require('lodash'),
|
||||
Promise = require('bluebird'),
|
||||
config = require('../../config'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
|
||||
AppProxy = require('./proxy'),
|
||||
AppSandbox = require('./sandbox'),
|
||||
|
@ -83,7 +83,10 @@ loader = {
|
|||
|
||||
return perms.read().catch(function (err) {
|
||||
// Provide a helpful error about which app
|
||||
return Promise.reject(new Error(i18n.t('errors.apps.permissionsErrorLoadingApp.error', {name: name, message: err.message})));
|
||||
return Promise.reject(new Error(common.i18n.t('errors.apps.permissionsErrorLoadingApp.error', {
|
||||
name: name,
|
||||
message: err.message
|
||||
})));
|
||||
});
|
||||
})
|
||||
.then(function (appPerms) {
|
||||
|
@ -93,7 +96,7 @@ loader = {
|
|||
|
||||
// Check for an install() method on the app.
|
||||
if (!_.isFunction(app.install)) {
|
||||
return Promise.reject(new Error(i18n.t('errors.apps.noInstallMethodLoadingApp.error', {name: name})));
|
||||
return Promise.reject(new Error(common.i18n.t('errors.apps.noInstallMethodLoadingApp.error', {name: name})));
|
||||
}
|
||||
|
||||
// Run the app.install() method
|
||||
|
@ -114,7 +117,7 @@ loader = {
|
|||
|
||||
// Check for an activate() method on the app.
|
||||
if (!_.isFunction(app.activate)) {
|
||||
return Promise.reject(new Error(i18n.t('errors.apps.noActivateMethodLoadingApp.error', {name: name})));
|
||||
return Promise.reject(new Error(common.i18n.t('errors.apps.noActivateMethodLoadingApp.error', {name: name})));
|
||||
}
|
||||
|
||||
// Wrapping the activate() with a when because it's possible
|
||||
|
|
|
@ -2,7 +2,7 @@ var _ = require('lodash'),
|
|||
api = require('../../api'),
|
||||
helpers = require('../../helpers/register'),
|
||||
filters = require('../../filters'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
router = require('../route').appRouter,
|
||||
generateProxyFunctions;
|
||||
|
||||
|
@ -30,7 +30,11 @@ generateProxyFunctions = function (name, permissions, isInternal) {
|
|||
var permValue = getPermissionToMethod(perm, method);
|
||||
|
||||
if (!permValue) {
|
||||
throw new Error(i18n.t('errors.apps.accessResourceWithoutPermission.error', {name: name, perm: perm, method: method}));
|
||||
throw new Error(common.i18n.t('errors.apps.accessResourceWithoutPermission.error', {
|
||||
name: name,
|
||||
perm: perm,
|
||||
method: method
|
||||
}));
|
||||
}
|
||||
|
||||
return wrappedFunc.apply(context, args);
|
||||
|
@ -97,11 +101,11 @@ generateProxyFunctions = function (name, permissions, isInternal) {
|
|||
|
||||
function AppProxy(options) {
|
||||
if (!options.name) {
|
||||
throw new Error(i18n.t('errors.apps.mustProvideAppName.error'));
|
||||
throw new Error(common.i18n.t('errors.apps.mustProvideAppName.error'));
|
||||
}
|
||||
|
||||
if (!options.permissions) {
|
||||
throw new Error(i18n.t('errors.apps.mustProvideAppPermissions.error'));
|
||||
throw new Error(common.i18n.t('errors.apps.mustProvideAppPermissions.error'));
|
||||
}
|
||||
|
||||
_.extend(this, generateProxyFunctions(options.name, options.permissions, options.internal));
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
var path = require('path'),
|
||||
Module = require('module'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
_ = require('lodash');
|
||||
|
||||
function AppSandbox(opts) {
|
||||
|
@ -44,7 +44,7 @@ AppSandbox.prototype.loadModule = function loadModuleSandboxed(modulePath) {
|
|||
currentModule.require = function requireProxy(module) {
|
||||
// check whitelist, plugin config, etc.
|
||||
if (_.includes(self.opts.blacklist, module)) {
|
||||
throw new Error(i18n.t('errors.apps.unsafeAppRequire.error', {msg: module}));
|
||||
throw new Error(common.i18n.t('errors.apps.unsafeAppRequire.error', {msg: module}));
|
||||
}
|
||||
|
||||
var firstTwo = module.slice(0, 2),
|
||||
|
@ -61,7 +61,7 @@ AppSandbox.prototype.loadModule = function loadModuleSandboxed(modulePath) {
|
|||
// Check relative path from the appRoot for outside requires
|
||||
relPath = path.relative(appRoot, resolvedPath);
|
||||
if (relPath.slice(0, 2) === '..') {
|
||||
throw new Error(i18n.t('errors.apps.unsafeAppRequire.error', {msg: relPath}));
|
||||
throw new Error(common.i18n.t('errors.apps.unsafeAppRequire.error', {msg: relPath}));
|
||||
}
|
||||
|
||||
// Assign as new module path
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
var express = require('express'),
|
||||
_ = require('lodash'),
|
||||
config = require('../../config'),
|
||||
errors = require('../../lib/common/errors'),
|
||||
i18n = require('../../lib/common/i18n'),
|
||||
common = require('../../lib/common'),
|
||||
urlService = require('../../services/url'),
|
||||
channelController = require('../../controllers/channel'),
|
||||
rssController = require('../../controllers/rss'),
|
||||
|
@ -24,7 +23,7 @@ function handlePageParam(req, res, next, page) {
|
|||
}
|
||||
} else if (page < 1 || isNaN(page)) {
|
||||
// Nothing less than 1 is a valid page number, go straight to a 404
|
||||
return next(new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')}));
|
||||
return next(new common.errors.NotFoundError({message: common.i18n.t('errors.errors.pageNotFound')}));
|
||||
} else {
|
||||
// Set req.params.page to the already parsed number, and continue
|
||||
req.params.page = page;
|
||||
|
|
|
@ -1,12 +1,9 @@
|
|||
var https = require('https'),
|
||||
url = require('url'),
|
||||
errors = require('../lib/common/errors'),
|
||||
logging = require('../lib/common/logging'),
|
||||
common = require('../lib/common'),
|
||||
urlService = require('../services/url'),
|
||||
blogIconUtils = require('../utils/blog-icon'),
|
||||
events = require('../lib/common/events'),
|
||||
settingsCache = require('../settings/cache'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
schema = require('../data/schema').checks,
|
||||
defaultPostSlugs = [
|
||||
'welcome',
|
||||
|
@ -32,10 +29,10 @@ function makeRequest(reqOptions, reqPayload) {
|
|||
|
||||
req.write(reqPayload);
|
||||
req.on('error', function (err) {
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
context: i18n.t('errors.services.ping.requestFailed.error', {service: 'slack'}),
|
||||
help: i18n.t('errors.services.ping.requestFailed.help', {url: 'http://docs.ghost.org'})
|
||||
context: common.i18n.t('errors.services.ping.requestFailed.error', {service: 'slack'}),
|
||||
help: common.i18n.t('errors.services.ping.requestFailed.help', {url: 'http://docs.ghost.org'})
|
||||
}));
|
||||
});
|
||||
|
||||
|
@ -103,8 +100,8 @@ function testPing() {
|
|||
}
|
||||
|
||||
function listen() {
|
||||
events.on('post.published', listener);
|
||||
events.on('slack.test', testPing);
|
||||
common.events.on('post.published', listener);
|
||||
common.events.on('slack.test', testPing);
|
||||
}
|
||||
|
||||
// Public API
|
||||
|
|
|
@ -11,7 +11,7 @@ const _ = require('lodash'),
|
|||
Promise = require('bluebird'),
|
||||
_debug = require('ghost-ignition').debug._base,
|
||||
debug = _debug('ghost:services:url'),
|
||||
events = require('../../lib/common/events'),
|
||||
common = require('../../lib/common'),
|
||||
// TODO: make this dynamic
|
||||
resourceConfig = require('./config.json'),
|
||||
Resource = require('./Resource'),
|
||||
|
@ -44,7 +44,7 @@ class UrlService {
|
|||
UrlService.cacheRoute('/subscribe/', {});
|
||||
|
||||
// Register a listener for server-start to load all the known urls
|
||||
events.on('server:start', (() => {
|
||||
common.events.on('server:start', (() => {
|
||||
debug('URL service, loading all URLS');
|
||||
this.loadResourceUrls();
|
||||
}));
|
||||
|
@ -90,7 +90,7 @@ class UrlService {
|
|||
|
||||
_.each(this.resources, (resource) => {
|
||||
_.each(resource.events, (method, eventName) => {
|
||||
events.on(eventName, (model) => {
|
||||
common.events.on(eventName, (model) => {
|
||||
eventHandlers[method].call(this, model, resource, eventName);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
// Based heavily on the settings cache
|
||||
const _ = require('lodash'),
|
||||
debug = require('ghost-ignition').debug('services:url:cache'),
|
||||
events = require('../../lib/common/events'),
|
||||
common = require('../../lib/common'),
|
||||
urlCache = {};
|
||||
|
||||
module.exports = {
|
||||
|
@ -20,18 +20,18 @@ module.exports = {
|
|||
if (!existing) {
|
||||
debug('adding url', key);
|
||||
urlCache[key] = _.cloneDeep(value);
|
||||
events.emit('url.added', key, value);
|
||||
common.events.emit('url.added', key, value);
|
||||
} else if (!_.isEqual(value, existing)) {
|
||||
debug('overwriting url', key);
|
||||
urlCache[key] = _.cloneDeep(value);
|
||||
events.emit('url.edited', key, value);
|
||||
common.events.emit('url.edited', key, value);
|
||||
}
|
||||
},
|
||||
unset(key) {
|
||||
const value = this.get(key);
|
||||
delete urlCache[key];
|
||||
debug('removing url', key);
|
||||
events.emit('url.removed', key, value);
|
||||
common.events.emit('url.removed', key, value);
|
||||
},
|
||||
get(key) {
|
||||
return _.cloneDeep(urlCache[key]);
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
var _ = require('lodash'),
|
||||
events = require('../lib/common/events'),
|
||||
common = require('../lib/common'),
|
||||
api = require('../api'),
|
||||
modelAttrs;
|
||||
|
||||
|
@ -47,8 +47,8 @@ function listener(event, model, options) {
|
|||
// TODO: use a wildcard with the new event emitter or use the webhooks API to
|
||||
// register listeners only for events that have webhooks
|
||||
function listen() {
|
||||
events.on('subscriber.added', _.partial(listener, 'subscriber.added'));
|
||||
events.on('subscriber.deleted', _.partial(listener, 'subscriber.deleted'));
|
||||
common.events.on('subscriber.added', _.partial(listener, 'subscriber.added'));
|
||||
common.events.on('subscriber.deleted', _.partial(listener, 'subscriber.deleted'));
|
||||
}
|
||||
|
||||
// Public API
|
||||
|
|
|
@ -3,10 +3,7 @@ var _ = require('lodash'),
|
|||
xml = require('xml'),
|
||||
config = require('../config'),
|
||||
urlService = require('../services/url'),
|
||||
errors = require('../lib/common/errors'),
|
||||
logging = require('../lib/common/logging'),
|
||||
events = require('../lib/common/events'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
settingsCache = require('../settings/cache'),
|
||||
|
||||
defaultPostSlugs = [
|
||||
|
@ -78,11 +75,11 @@ function ping(post) {
|
|||
req.write(pingXML);
|
||||
|
||||
req.on('error', function handleError(err) {
|
||||
logging.error(new errors.GhostError({
|
||||
common.logging.error(new common.errors.GhostError({
|
||||
err: err,
|
||||
message: err.message,
|
||||
context: i18n.t('errors.services.ping.requestFailed.error', {service: 'slack'}),
|
||||
help: i18n.t('errors.services.ping.requestFailed.help', {url: 'http://docs.ghost.org'})
|
||||
context: common.i18n.t('errors.services.ping.requestFailed.error', {service: 'slack'}),
|
||||
help: common.i18n.t('errors.services.ping.requestFailed.help', {url: 'http://docs.ghost.org'})
|
||||
}));
|
||||
});
|
||||
|
||||
|
@ -101,7 +98,7 @@ function listener(model, options) {
|
|||
}
|
||||
|
||||
function listen() {
|
||||
events.on('post.published', listener);
|
||||
common.events.on('post.published', listener);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
// circular dependency bugs.
|
||||
var debug = require('ghost-ignition').debug('settings:cache'),
|
||||
_ = require('lodash'),
|
||||
events = require('../lib/common/events'),
|
||||
common = require('../lib/common'),
|
||||
/**
|
||||
* ## Cache
|
||||
* Holds cached settings
|
||||
|
@ -104,9 +104,9 @@ module.exports = {
|
|||
}
|
||||
|
||||
// Bind to events to automatically keep up-to-date
|
||||
events.on('settings.edited', updateSettingFromModel);
|
||||
events.on('settings.added', updateSettingFromModel);
|
||||
events.on('settings.deleted', updateSettingFromModel);
|
||||
common.events.on('settings.edited', updateSettingFromModel);
|
||||
common.events.on('settings.added', updateSettingFromModel);
|
||||
common.events.on('settings.deleted', updateSettingFromModel);
|
||||
|
||||
return settingsCache;
|
||||
}
|
||||
|
|
|
@ -1,8 +1,5 @@
|
|||
var debug = require('ghost-ignition').debug('themes'),
|
||||
events = require('../lib/common/events'),
|
||||
errors = require('../lib/common/errors'),
|
||||
logging = require('../lib/common/logging'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
themeLoader = require('./loader'),
|
||||
active = require('./active'),
|
||||
validate = require('./validate'),
|
||||
|
@ -22,7 +19,7 @@ module.exports = {
|
|||
debug('init themes', activeThemeName);
|
||||
|
||||
// Register a listener for server-start to load all themes
|
||||
events.on('server:start', function readAllThemesOnServerStart() {
|
||||
common.events.on('server:start', function readAllThemesOnServerStart() {
|
||||
themeLoader.loadAllThemes();
|
||||
});
|
||||
|
||||
|
@ -36,9 +33,9 @@ module.exports = {
|
|||
.then(function validationSuccess(checkedTheme) {
|
||||
// CASE: inform that the theme has errors, but not fatal (theme still works)
|
||||
if (checkedTheme.results.error.length) {
|
||||
logging.warn(new errors.ThemeValidationError({
|
||||
common.logging.warn(new common.errors.ThemeValidationError({
|
||||
errorType: 'ThemeWorksButHasErrors',
|
||||
message: i18n.t('errors.middleware.themehandler.themeHasErrors', {theme: activeThemeName}),
|
||||
message: common.i18n.t('errors.middleware.themehandler.themeHasErrors', {theme: activeThemeName}),
|
||||
errorDetails: JSON.stringify(checkedTheme.results.error, null, '\t')
|
||||
}));
|
||||
}
|
||||
|
@ -48,8 +45,8 @@ module.exports = {
|
|||
})
|
||||
.catch(function validationFailure(err) {
|
||||
if (err.errorDetails) {
|
||||
logging.error(new errors.ThemeValidationError({
|
||||
message: i18n.t('errors.middleware.themehandler.invalidTheme', {theme: activeThemeName}),
|
||||
common.logging.error(new common.errors.ThemeValidationError({
|
||||
message: common.i18n.t('errors.middleware.themehandler.invalidTheme', {theme: activeThemeName}),
|
||||
errorDetails: JSON.stringify(err.errorDetails, null, '\t')
|
||||
}));
|
||||
}
|
||||
|
@ -59,15 +56,15 @@ module.exports = {
|
|||
self.activate(theme, err.context, err);
|
||||
});
|
||||
})
|
||||
.catch(errors.NotFoundError, function (err) {
|
||||
.catch(common.errors.NotFoundError, function (err) {
|
||||
// CASE: active theme is missing, we don't want to exit because the admin panel will still work
|
||||
err.message = i18n.t('errors.middleware.themehandler.missingTheme', {theme: activeThemeName});
|
||||
logging.error(err);
|
||||
err.message = common.i18n.t('errors.middleware.themehandler.missingTheme', {theme: activeThemeName});
|
||||
common.logging.error(err);
|
||||
})
|
||||
.catch(function (err) {
|
||||
// CASE: theme threw an odd error, we don't want to exit because the admin panel will still work
|
||||
// This is the absolute catch-all, at this point, we do not know what went wrong!
|
||||
logging.error(err);
|
||||
common.logging.error(err);
|
||||
});
|
||||
},
|
||||
// Load themes, soon to be removed and exposed via specific function.
|
||||
|
@ -88,8 +85,8 @@ module.exports = {
|
|||
try {
|
||||
active.set(loadedTheme, checkedTheme, error);
|
||||
} catch (err) {
|
||||
logging.error(new errors.InternalServerError({
|
||||
message: i18n.t('errors.middleware.themehandler.activateFailed', {theme: loadedTheme.name}),
|
||||
common.logging.error(new common.errors.InternalServerError({
|
||||
message: common.i18n.t('errors.middleware.themehandler.activateFailed', {theme: loadedTheme.name}),
|
||||
err: err
|
||||
}));
|
||||
}
|
||||
|
|
|
@ -1,9 +1,8 @@
|
|||
var _ = require('lodash'),
|
||||
var _ = require('lodash'),
|
||||
hbs = require('./engine'),
|
||||
urlService = require('../services/url'),
|
||||
errors = require('../lib/common/errors'),
|
||||
config = require('../config'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
settingsCache = require('../settings/cache'),
|
||||
activeTheme = require('./active'),
|
||||
themeMiddleware = {};
|
||||
|
@ -16,19 +15,19 @@ themeMiddleware.ensureActiveTheme = function ensureActiveTheme(req, res, next) {
|
|||
// CASE: this means that the theme hasn't been loaded yet i.e. there is no active theme
|
||||
if (!activeTheme.get()) {
|
||||
// This is the one place we ACTUALLY throw an error for a missing theme as it's a request we cannot serve
|
||||
return next(new errors.InternalServerError({
|
||||
return next(new common.errors.InternalServerError({
|
||||
// We use the settingsCache here, because the setting will be set,
|
||||
// even if the theme itself is not usable because it is invalid or missing.
|
||||
message: i18n.t('errors.middleware.themehandler.missingTheme', {theme: settingsCache.get('active_theme')})
|
||||
message: common.i18n.t('errors.middleware.themehandler.missingTheme', {theme: settingsCache.get('active_theme')})
|
||||
}));
|
||||
}
|
||||
|
||||
// CASE: bootstrap theme validation failed, we would like to show the errors on the blog [only production]
|
||||
if (activeTheme.get().error && config.get('env') === 'production') {
|
||||
return next(new errors.InternalServerError({
|
||||
return next(new common.errors.InternalServerError({
|
||||
// We use the settingsCache here, because the setting will be set,
|
||||
// even if the theme itself is not usable because it is invalid or missing.
|
||||
message: i18n.t('errors.middleware.themehandler.invalidTheme', {theme: settingsCache.get('active_theme')}),
|
||||
message: common.i18n.t('errors.middleware.themehandler.invalidTheme', {theme: settingsCache.get('active_theme')}),
|
||||
errorDetails: activeTheme.get().error.errorDetails
|
||||
}));
|
||||
}
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
var Promise = require('bluebird'),
|
||||
config = require('../config'),
|
||||
errors = require('../lib/common/errors'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
common = require('../lib/common'),
|
||||
checkTheme;
|
||||
|
||||
checkTheme = function checkTheme(theme, isZip) {
|
||||
|
@ -29,8 +28,8 @@ checkTheme = function checkTheme(theme, isZip) {
|
|||
return checkedTheme;
|
||||
}
|
||||
|
||||
return Promise.reject(new errors.ThemeValidationError({
|
||||
message: i18n.t('errors.api.themes.invalidTheme'),
|
||||
return Promise.reject(new common.errors.ThemeValidationError({
|
||||
message: common.i18n.t('errors.api.themes.invalidTheme'),
|
||||
errorDetails: checkedTheme.results.error,
|
||||
context: checkedTheme
|
||||
}));
|
||||
|
|
|
@ -32,24 +32,22 @@ var crypto = require('crypto'),
|
|||
api = require('./api'),
|
||||
config = require('./config'),
|
||||
urlService = require('./services/url'),
|
||||
logging = require('./lib/common/logging'),
|
||||
errors = require('./lib/common/errors'),
|
||||
i18n = require('./lib/common/i18n'),
|
||||
common = require('./lib/common'),
|
||||
currentVersion = require('./utils/ghost-version').full,
|
||||
internal = {context: {internal: true}},
|
||||
checkEndpoint = config.get('updateCheckUrl') || 'https://updates.ghost.org';
|
||||
|
||||
function updateCheckError(err) {
|
||||
err = errors.utils.deserialize(err);
|
||||
err = common.errors.utils.deserialize(err);
|
||||
|
||||
api.settings.edit(
|
||||
{settings: [{key: 'next_update_check', value: Math.round(Date.now() / 1000 + 24 * 3600)}]},
|
||||
internal
|
||||
);
|
||||
|
||||
err.context = i18n.t('errors.update-check.checkingForUpdatesFailed.error');
|
||||
err.help = i18n.t('errors.update-check.checkingForUpdatesFailed.help', {url: 'https://docs.ghost.org/v1'});
|
||||
logging.error(err);
|
||||
err.context = common.i18n.t('errors.update-check.checkingForUpdatesFailed.error');
|
||||
err.help = common.i18n.t('errors.update-check.checkingForUpdatesFailed.help', {url: 'https://docs.ghost.org/v1'});
|
||||
common.logging.error(err);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -176,7 +174,7 @@ function updateCheckRequest() {
|
|||
|
||||
resolve(resData);
|
||||
} catch (e) {
|
||||
reject(i18n.t('errors.update-check.unableToDecodeUpdateResponse.error'));
|
||||
reject(common.i18n.t('errors.update-check.unableToDecodeUpdateResponse.error'));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
@ -2,8 +2,7 @@ var sizeOf = require('image-size'),
|
|||
Promise = require('bluebird'),
|
||||
_ = require('lodash'),
|
||||
path = require('path'),
|
||||
i18n = require('../lib/common/i18n'),
|
||||
errors = require('../lib/common/errors'),
|
||||
common = require('../lib/common'),
|
||||
settingsCache = require('../settings/cache'),
|
||||
config = require('../config'),
|
||||
urlService = require('../services/url'),
|
||||
|
@ -29,8 +28,12 @@ getIconDimensions = function getIconDimensions(path) {
|
|||
dimensions = sizeOf(path);
|
||||
|
||||
if (dimensions.images) {
|
||||
dimensions.width = _.maxBy(dimensions.images, function (w) {return w.width;}).width;
|
||||
dimensions.height = _.maxBy(dimensions.images, function (h) {return h.height;}).height;
|
||||
dimensions.width = _.maxBy(dimensions.images, function (w) {
|
||||
return w.width;
|
||||
}).width;
|
||||
dimensions.height = _.maxBy(dimensions.images, function (h) {
|
||||
return h.height;
|
||||
}).height;
|
||||
}
|
||||
|
||||
return resolve({
|
||||
|
@ -38,7 +41,12 @@ getIconDimensions = function getIconDimensions(path) {
|
|||
height: dimensions.height
|
||||
});
|
||||
} catch (err) {
|
||||
return reject(new errors.ValidationError({message: i18n.t('errors.utils.blogIcon.error', {file: path, error: err.message})}));
|
||||
return reject(new common.errors.ValidationError({
|
||||
message: common.i18n.t('errors.utils.blogIcon.error', {
|
||||
file: path,
|
||||
error: err.message
|
||||
})
|
||||
}));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue