From 42374462777ba02d2b10d7d78df71ba4ca865aa8 Mon Sep 17 00:00:00 2001 From: Hannah Wolfe Date: Tue, 12 Sep 2017 16:31:14 +0100 Subject: [PATCH] Misc cleanup & consistency amends (#9002) no issue - Consistent naming for postLookup - makes it easier to search and inspect the various usages - Cleanup unneeded code - Make res.render calls more consistent - add some consistency to the calls to res.render - Remove ancient reference to dataProvider - Let's call it models everywhere now... - Use consistent formatting across the API - we're no longer using alignment in vars - Misc other consistency changes in API - always refer to local utils as apiUtils - logical grouping of requires - dependencies, utils, "lib common" etc - use xAPI to refer to API endpoints, e.g. mailAPI, settingsAPI for clarity --- core/server/api/authentication.js | 50 +++++------ core/server/api/clients.js | 21 +++-- core/server/api/configuration.js | 17 ++-- core/server/api/db.js | 32 +++---- core/server/api/index.js | 46 +++++----- core/server/api/invites.js | 60 +++++++------- core/server/api/mail.js | 24 +++--- core/server/api/notifications.js | 29 ++++--- core/server/api/posts.js | 59 +++++++------ core/server/api/roles.js | 18 ++-- core/server/api/schedules.js | 28 +++---- core/server/api/settings.js | 26 +++--- core/server/api/slack.js | 4 +- core/server/api/slugs.js | 29 ++++--- core/server/api/subscribers.js | 61 +++++++------- core/server/api/tags.js | 57 +++++++------ core/server/api/themes.js | 4 +- core/server/api/upload.js | 2 +- core/server/api/users.js | 80 +++++++++--------- core/server/api/utils.js | 11 ++- core/server/apps/amp/lib/router.js | 11 ++- .../apps/private-blogging/lib/router.js | 3 +- core/server/apps/subscribers/lib/router.js | 7 +- .../controllers/frontend/render-channel.js | 1 + core/server/data/meta/image-dimensions.js | 83 +++++++++---------- 25 files changed, 375 insertions(+), 388 deletions(-) diff --git a/core/server/api/authentication.js b/core/server/api/authentication.js index 27c2eb56d4..502a41abfb 100644 --- a/core/server/api/authentication.js +++ b/core/server/api/authentication.js @@ -1,19 +1,19 @@ -var _ = require('lodash'), - validator = require('validator'), - Promise = require('bluebird'), - pipeline = require('../utils/pipeline'), - settings = require('./settings'), - mail = require('./../mail'), - apiMail = require('./mail'), - globalUtils = require('../utils'), - utils = require('./utils'), - errors = require('../errors'), - models = require('../models'), - logging = require('../logging'), - events = require('../events'), - config = require('../config'), - i18n = require('../i18n'), - spamPrevention = require('../middleware/api/spam-prevention'), +var Promise = require('bluebird'), + _ = require('lodash'), + validator = require('validator'), + pipeline = require('../utils/pipeline'), + mail = require('./../mail'), + globalUtils = require('../utils'), + apiUtils = require('./utils'), + models = require('../models'), + config = require('../config'), + errors = require('../errors'), + events = require('../events'), + i18n = require('../i18n'), + logging = require('../logging'), + spamPrevention = require('../middleware/api/spam-prevention'), + mailAPI = require('./mail'), + settingsAPI = require('./settings'), authentication, tokenSecurity = {}; @@ -61,7 +61,7 @@ function setupTasks(setupData) { var tasks; function validateData(setupData) { - return utils.checkObject(setupData, 'setup').then(function then(checked) { + return apiUtils.checkObject(setupData, 'setup').then(function then(checked) { var data = checked.setup[0]; return { @@ -109,7 +109,7 @@ function setupTasks(setupData) { {key: 'description', value: i18n.t('common.api.authentication.sampleBlogDescription')} ]; - return settings.edit({settings: userSettings}, context).return(user); + return settingsAPI.edit({settings: userSettings}, context).return(user); } function formatResponse(user) { @@ -141,7 +141,7 @@ authentication = { var tasks; function validateRequest(object) { - return utils.checkObject(object, 'passwordreset').then(function then(data) { + return apiUtils.checkObject(object, 'passwordreset').then(function then(data) { var email = data.passwordreset[0].email; if (typeof email !== 'string' || !validator.isEmail(email)) { @@ -158,7 +158,7 @@ authentication = { var options = {context: {internal: true}}, dbHash, token; - return settings.read(_.merge({key: 'db_hash'}, options)) + return settingsAPI.read(_.merge({key: 'db_hash'}, options)) .then(function fetchedSettings(response) { dbHash = response.settings[0].value; @@ -205,7 +205,7 @@ authentication = { }] }; - return apiMail.send(payload, {context: {internal: true}}); + return mailAPI.send(payload, {context: {internal: true}}); }); } @@ -238,7 +238,7 @@ authentication = { var tasks, tokenIsCorrect, dbHash, options = {context: {internal: true}}, tokenParts; function validateRequest() { - return utils.validate('passwordreset')(object, options) + return apiUtils.validate('passwordreset')(object, options) .then(function (options) { var data = options.data.passwordreset[0]; @@ -286,7 +286,7 @@ authentication = { oldPassword = data.oldPassword, newPassword = data.newPassword; - return settings.read(_.merge({key: 'db_hash'}, options)) + return settingsAPI.read(_.merge({key: 'db_hash'}, options)) .then(function fetchedSettings(response) { dbHash = response.settings[0].value; @@ -355,7 +355,7 @@ authentication = { var tasks, invite, options = {context: {internal: true}}; function validateInvitation(invitation) { - return utils.checkObject(invitation, 'invitation') + 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')})); @@ -532,7 +532,7 @@ authentication = { }] }; - apiMail.send(payload, {context: {internal: true}}).catch(function (error) { + mailAPI.send(payload, {context: {internal: true}}).catch(function (error) { logging.error(new errors.EmailError({ err: error, context: i18n.t('errors.api.authentication.unableToSendWelcomeEmail'), diff --git a/core/server/api/clients.js b/core/server/api/clients.js index 5bba9a24fb..d1f4afe1ba 100644 --- a/core/server/api/clients.js +++ b/core/server/api/clients.js @@ -1,14 +1,13 @@ // # Client API // RESTful API for the Client resource -var Promise = require('bluebird'), - _ = require('lodash'), - dataProvider = require('../models'), - errors = require('../errors'), - utils = require('./utils'), - pipeline = require('../utils/pipeline'), - i18n = require('../i18n'), - - docName = 'clients', +var Promise = require('bluebird'), + _ = require('lodash'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + models = require('../models'), + errors = require('../errors'), + i18n = require('../i18n'), + docName = 'clients', clients; /** @@ -36,12 +35,12 @@ clients = { function doQuery(options) { // only User Agent (type = `ua`) clients are available at the moment. options.data = _.extend(options.data, {type: 'ua'}); - return dataProvider.Client.findOne(options.data, _.omit(options, ['data'])); + return models.Client.findOne(options.data, _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {attrs: attrs}), + apiUtils.validate(docName, {attrs: attrs}), // TODO: add permissions // utils.handlePublicPermissions(docName, 'read'), doQuery diff --git a/core/server/api/configuration.js b/core/server/api/configuration.js index 2b7c10a5cd..becf07f733 100644 --- a/core/server/api/configuration.js +++ b/core/server/api/configuration.js @@ -1,13 +1,12 @@ // # Configuration API // RESTful API for browsing the configuration -var _ = require('lodash'), - config = require('../config'), - settingsCache = require('../settings/cache'), - ghostVersion = require('../utils/ghost-version'), - models = require('../models'), - Promise = require('bluebird'), - utils = require('../utils'), - +var Promise = require('bluebird'), + _ = require('lodash'), + apiUtils = require('../utils'), + models = require('../models'), + config = require('../config'), + settingsCache = require('../settings/cache'), + ghostVersion = require('../utils/ghost-version'), configuration; function fetchAvailableTimezones() { @@ -36,7 +35,7 @@ function getBaseConfig() { return { useGravatar: !config.isPrivacyDisabled('useGravatar'), publicAPI: config.get('publicAPI') === true, - blogUrl: utils.url.urlFor('home', true), + blogUrl: apiUtils.url.urlFor('home', true), blogTitle: settingsCache.get('title'), routeKeywords: config.get('routeKeywords'), clientExtensions: config.get('clientExtensions') diff --git a/core/server/api/db.js b/core/server/api/db.js index eb91fe6226..ccae26efb9 100644 --- a/core/server/api/db.js +++ b/core/server/api/db.js @@ -1,18 +1,18 @@ // # DB API // API for DB operations -var Promise = require('bluebird'), - exporter = require('../data/export'), - importer = require('../data/importer'), - backupDatabase = require('../data/db/backup'), - models = require('../models'), - errors = require('../errors'), - utils = require('./utils'), - path = require('path'), - fs = require('fs'), - utilsUrl = require('../utils/url'), - config = require('../config'), - pipeline = require('../utils/pipeline'), - docName = 'db', +var Promise = require('bluebird'), + path = require('path'), + fs = require('fs'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + exporter = require('../data/export'), + importer = require('../data/importer'), + backupDatabase = require('../data/db/backup'), + models = require('../models'), + config = require('../config'), + errors = require('../errors'), + utilsUrl = require('../utils/url'), + docName = 'db', db; /** @@ -67,7 +67,7 @@ db = { } tasks = [ - utils.handlePermissions(docName, 'exportContent'), + apiUtils.handlePermissions(docName, 'exportContent'), exportContent ]; @@ -94,7 +94,7 @@ db = { } tasks = [ - utils.handlePermissions(docName, 'importContent'), + apiUtils.handlePermissions(docName, 'importContent'), importContent ]; @@ -129,7 +129,7 @@ db = { } tasks = [ - utils.handlePermissions(docName, 'deleteAllContent'), + apiUtils.handlePermissions(docName, 'deleteAllContent'), backupDatabase, deleteContent ]; diff --git a/core/server/api/index.js b/core/server/api/index.js index 387c090411..cc829753dc 100644 --- a/core/server/api/index.js +++ b/core/server/api/index.js @@ -4,30 +4,30 @@ // Ghost's JSON API is integral to the workings of Ghost, regardless of whether you want to access data internally, // from a theme, an app, or from an external app, you'll use the Ghost JSON API to do so. -var _ = require('lodash'), - Promise = require('bluebird'), - config = require('../config'), - models = require('../models'), - utils = require('../utils'), - configuration = require('./configuration'), - db = require('./db'), - mail = require('./mail'), - notifications = require('./notifications'), - posts = require('./posts'), - schedules = require('./schedules'), - roles = require('./roles'), - settings = require('./settings'), - tags = require('./tags'), - invites = require('./invites'), - clients = require('./clients'), - users = require('./users'), - slugs = require('./slugs'), - themes = require('./themes'), - subscribers = require('./subscribers'), +var _ = require('lodash'), + Promise = require('bluebird'), + config = require('../config'), + models = require('../models'), + utils = require('../utils'), + configuration = require('./configuration'), + db = require('./db'), + mail = require('./mail'), + notifications = require('./notifications'), + posts = require('./posts'), + schedules = require('./schedules'), + roles = require('./roles'), + settings = require('./settings'), + tags = require('./tags'), + invites = require('./invites'), + clients = require('./clients'), + users = require('./users'), + slugs = require('./slugs'), + themes = require('./themes'), + subscribers = require('./subscribers'), authentication = require('./authentication'), - uploads = require('./upload'), - exporter = require('../data/export'), - slack = require('./slack'), + uploads = require('./upload'), + exporter = require('../data/export'), + slack = require('./slack'), http, addHeaders, diff --git a/core/server/api/invites.js b/core/server/api/invites.js index e3551b24bb..15f2da3713 100644 --- a/core/server/api/invites.js +++ b/core/server/api/invites.js @@ -1,15 +1,15 @@ -var _ = require('lodash'), - Promise = require('bluebird'), +var Promise = require('bluebird'), + _ = require('lodash'), pipeline = require('../utils/pipeline'), - dataProvider = require('../models'), - settings = require('./settings'), mail = require('./../mail'), - apiMail = require('./mail'), globalUtils = require('../utils'), - utils = require('./utils'), + apiUtils = require('./utils'), + models = require('../models'), errors = require('../errors'), - logging = require('../logging'), i18n = require('../i18n'), + logging = require('../logging'), + mailAPI = require('./mail'), + settingsAPI = require('./settings'), docName = 'invites', allowedIncludes = ['created_by', 'updated_by'], invites; @@ -19,13 +19,13 @@ invites = { var tasks; function modelQuery(options) { - return dataProvider.Invite.findPage(options); + return models.Invite.findPage(options); } tasks = [ - utils.validate(docName, {opts: utils.browseDefaultOptions}), - utils.handlePublicPermissions(docName, 'browse'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: apiUtils.browseDefaultOptions}), + apiUtils.handlePublicPermissions(docName, 'browse'), + apiUtils.convertOptions(allowedIncludes), modelQuery ]; @@ -37,13 +37,13 @@ invites = { tasks; function modelQuery(options) { - return dataProvider.Invite.findOne(options.data, _.omit(options, ['data'])); + return models.Invite.findOne(options.data, _.omit(options, ['data'])); } tasks = [ - utils.validate(docName, {attrs: attrs}), - utils.handlePublicPermissions(docName, 'read'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {attrs: attrs}), + apiUtils.handlePublicPermissions(docName, 'read'), + apiUtils.convertOptions(allowedIncludes), modelQuery ]; @@ -61,7 +61,7 @@ invites = { var tasks; function modelQuery(options) { - return dataProvider.Invite.findOne({id: options.id}, _.omit(options, ['data'])) + 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')}); @@ -72,9 +72,9 @@ invites = { } tasks = [ - utils.validate(docName, {opts: utils.idDefaultOptions}), - utils.handlePermissions(docName, 'destroy'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}), + apiUtils.handlePermissions(docName, 'destroy'), + apiUtils.convertOptions(allowedIncludes), modelQuery ]; @@ -90,11 +90,11 @@ invites = { function addInvite(options) { var data = options.data; - return dataProvider.Invite.add(data.invites[0], _.omit(options, 'data')) + return models.Invite.add(data.invites[0], _.omit(options, 'data')) .then(function (_invite) { invite = _invite; - return settings.read({key: 'title'}); + return settingsAPI.read({key: 'title'}); }) .then(function (response) { var adminUrl = globalUtils.url.urlFor('admin', true); @@ -124,10 +124,10 @@ invites = { }] }; - return apiMail.send(payload, {context: {internal: true}}); + return mailAPI.send(payload, {context: {internal: true}}); }).then(function () { options.id = invite.id; - return dataProvider.Invite.edit({status: 'sent'}, options); + return models.Invite.edit({status: 'sent'}, options); }).then(function () { invite.set('status', 'sent'); var inviteAsJSON = invite.toJSON(); @@ -146,7 +146,7 @@ invites = { function destroyOldInvite(options) { var data = options.data; - return dataProvider.Invite.findOne({email: data.invites[0].email}, _.omit(options, 'data')) + return models.Invite.findOne({email: data.invites[0].email}, _.omit(options, 'data')) .then(function (invite) { if (!invite) { return Promise.resolve(options); @@ -173,7 +173,7 @@ invites = { // We cannot use permissible because we don't have access to the role_id!!! // Adding a permissible function to the invite model, doesn't give us much context of the invite we would like to add // As we are looking forward to replace the permission system completely, we do not add a hack here - return dataProvider.Role.findOne({id: options.data.invites[0].role_id}).then(function (roleToInvite) { + 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')})); } @@ -202,7 +202,7 @@ invites = { } function checkIfUserExists(options) { - return dataProvider.User.findOne({email: options.data.invites[0].email}, options) + return models.User.findOne({email: options.data.invites[0].email}, options) .then(function (user) { if (user) { return Promise.reject(new errors.ValidationError({ @@ -215,7 +215,7 @@ invites = { } function fetchLoggedInUser(options) { - return dataProvider.User.findOne({id: loggedInUser}, _.merge({}, options, {include: ['roles']})) + 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')})); @@ -227,9 +227,9 @@ invites = { } tasks = [ - utils.validate(docName, {opts: ['email']}), - utils.handlePermissions(docName, 'add'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: ['email']}), + apiUtils.handlePermissions(docName, 'add'), + apiUtils.convertOptions(allowedIncludes), fetchLoggedInUser, validation, checkIfUserExists, diff --git a/core/server/api/mail.js b/core/server/api/mail.js index 573068dc6e..625a0ef01c 100644 --- a/core/server/api/mail.js +++ b/core/server/api/mail.js @@ -1,15 +1,15 @@ // # Mail API // API for sending Mail -var Promise = require('bluebird'), - pipeline = require('../utils/pipeline'), - errors = require('../errors'), - mail = require('../mail'), - Models = require('../models'), - utils = require('./utils'), - notifications = require('./notifications'), - i18n = require('../i18n'), - docName = 'mail', +var Promise = require('bluebird'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + models = require('../models'), + errors = require('../errors'), + i18n = require('../i18n'), + mail = require('../mail'), + notificationsAPI = require('./notifications'), + docName = 'mail', mailer, apiMail; @@ -23,7 +23,7 @@ function sendMail(object) { return mailer.send(object.mail[0].message).catch(function (err) { if (mailer.state.usingDirect) { - notifications.add( + notificationsAPI.add( {notifications: [{ type: 'warn', message: [ @@ -84,7 +84,7 @@ apiMail = { } tasks = [ - utils.handlePermissions(docName, 'send'), + apiUtils.handlePermissions(docName, 'send'), send, formatResponse ]; @@ -108,7 +108,7 @@ apiMail = { */ function modelQuery() { - return Models.User.findOne({id: options.context.user}); + return models.User.findOne({id: options.context.user}); } /** diff --git a/core/server/api/notifications.js b/core/server/api/notifications.js index f642fa5735..6a6c3093a0 100644 --- a/core/server/api/notifications.js +++ b/core/server/api/notifications.js @@ -1,16 +1,15 @@ // # Notifications API // RESTful API for creating notifications -var Promise = require('bluebird'), - _ = require('lodash'), - ObjectId = require('bson-objectid'), - permissions = require('../permissions'), - errors = require('../errors'), - settings = require('./settings'), - utils = require('./utils'), - pipeline = require('../utils/pipeline'), - canThis = permissions.canThis, - i18n = require('../i18n'), - +var Promise = require('bluebird'), + _ = require('lodash'), + ObjectId = require('bson-objectid'), + pipeline = require('../utils/pipeline'), + permissions = require('../permissions'), + canThis = permissions.canThis, + apiUtils = require('./utils'), + errors = require('../errors'), + i18n = require('../i18n'), + settingsAPI = require('./settings'), // Holds the persistent notifications notificationsStore = [], notifications; @@ -108,7 +107,7 @@ notifications = { } tasks = [ - utils.validate('notifications'), + apiUtils.validate('notifications'), handlePermissions, saveNotifications ]; @@ -135,10 +134,10 @@ notifications = { */ function markAsSeen(notification) { var context = {internal: true}; - return settings.read({key: 'seen_notifications', context: context}).then(function then(response) { + 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 settings.edit({settings: [{key: 'seen_notifications', value: seenNotifications}]}, {context: context}); + return settingsAPI.edit({settings: [{key: 'seen_notifications', value: seenNotifications}]}, {context: context}); }); } @@ -181,7 +180,7 @@ notifications = { } tasks = [ - utils.validate('notifications', {opts: utils.idDefaultOptions}), + apiUtils.validate('notifications', {opts: apiUtils.idDefaultOptions}), handlePermissions, destroyNotification ]; diff --git a/core/server/api/posts.js b/core/server/api/posts.js index 0ddbee82cf..e103b48ed1 100644 --- a/core/server/api/posts.js +++ b/core/server/api/posts.js @@ -1,14 +1,13 @@ // # Posts API // RESTful API for the Post resource -var Promise = require('bluebird'), - _ = require('lodash'), - dataProvider = require('../models'), - errors = require('../errors'), - utils = require('./utils'), - pipeline = require('../utils/pipeline'), - i18n = require('../i18n'), - - docName = 'posts', +var Promise = require('bluebird'), + _ = require('lodash'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + models = require('../models'), + errors = require('../errors'), + i18n = require('../i18n'), + docName = 'posts', allowedIncludes = [ 'created_by', 'updated_by', 'published_by', 'author', 'tags', 'fields', 'next', 'previous', 'next.author', 'next.tags', 'previous.author', 'previous.tags' @@ -46,7 +45,7 @@ posts = { if (options && options.context && (options.context.user || options.context.internal)) { extraOptions.push('staticPages'); } - permittedOptions = utils.browseDefaultOptions.concat(extraOptions); + permittedOptions = apiUtils.browseDefaultOptions.concat(extraOptions); /** * ### Model Query @@ -55,14 +54,14 @@ posts = { * @returns {Object} options */ function modelQuery(options) { - return dataProvider.Post.findPage(options); + return models.Post.findPage(options); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: permittedOptions}), - utils.handlePublicPermissions(docName, 'browse'), - utils.convertOptions(allowedIncludes, dataProvider.Post.allowedFormats), + apiUtils.validate(docName, {opts: permittedOptions}), + apiUtils.handlePublicPermissions(docName, 'browse'), + apiUtils.convertOptions(allowedIncludes, models.Post.allowedFormats), modelQuery ]; @@ -89,14 +88,14 @@ posts = { * @returns {Object} options */ function modelQuery(options) { - return dataProvider.Post.findOne(options.data, _.omit(options, ['data'])); + return models.Post.findOne(options.data, _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {attrs: attrs, opts: options.opts || []}), - utils.handlePublicPermissions(docName, 'read'), - utils.convertOptions(allowedIncludes, dataProvider.Post.allowedFormats), + apiUtils.validate(docName, {attrs: attrs, opts: options.opts || []}), + apiUtils.handlePublicPermissions(docName, 'read'), + apiUtils.convertOptions(allowedIncludes, models.Post.allowedFormats), modelQuery ]; @@ -130,14 +129,14 @@ posts = { * @returns {Object} options */ function modelQuery(options) { - return dataProvider.Post.edit(options.data.posts[0], _.omit(options, ['data'])); + return models.Post.edit(options.data.posts[0], _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.idDefaultOptions.concat(options.opts || [])}), - utils.handlePermissions(docName, 'edit'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions.concat(options.opts || [])}), + apiUtils.handlePermissions(docName, 'edit'), + apiUtils.convertOptions(allowedIncludes), modelQuery ]; @@ -177,14 +176,14 @@ posts = { * @returns {Object} options */ function modelQuery(options) { - return dataProvider.Post.add(options.data.posts[0], _.omit(options, ['data'])); + return models.Post.add(options.data.posts[0], _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName), - utils.handlePermissions(docName, 'add'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName), + apiUtils.handlePermissions(docName, 'add'), + apiUtils.convertOptions(allowedIncludes), modelQuery ]; @@ -216,7 +215,7 @@ posts = { * @param {Object} options */ function deletePost(options) { - var Post = dataProvider.Post, + var Post = models.Post, data = _.defaults({status: 'all'}, options), fetchOpts = _.defaults({require: true, columns: 'id'}, options); @@ -229,9 +228,9 @@ posts = { // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.idDefaultOptions}), - utils.handlePermissions(docName, 'destroy'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}), + apiUtils.handlePermissions(docName, 'destroy'), + apiUtils.convertOptions(allowedIncludes), deletePost ]; diff --git a/core/server/api/roles.js b/core/server/api/roles.js index e9886e88c4..68c17430e7 100644 --- a/core/server/api/roles.js +++ b/core/server/api/roles.js @@ -1,11 +1,11 @@ // # Roles API // RESTful API for the Role resource -var Promise = require('bluebird'), - canThis = require('../permissions').canThis, - dataProvider = require('../models'), - pipeline = require('../utils/pipeline'), - utils = require('./utils'), - docName = 'roles', +var Promise = require('bluebird'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + canThis = require('../permissions').canThis, + models = require('../models'), + docName = 'roles', roles; @@ -39,13 +39,13 @@ roles = { * @returns {Object} options */ function modelQuery(options) { - return dataProvider.Role.findAll(options); + return models.Role.findAll(options); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: permittedOptions}), - utils.handlePermissions(docName, 'browse'), + apiUtils.validate(docName, {opts: permittedOptions}), + apiUtils.handlePermissions(docName, 'browse'), modelQuery ]; diff --git a/core/server/api/schedules.js b/core/server/api/schedules.js index 912ed1ab1f..0a64024559 100644 --- a/core/server/api/schedules.js +++ b/core/server/api/schedules.js @@ -1,13 +1,13 @@ -var _ = require('lodash'), - Promise = require('bluebird'), +var Promise = require('bluebird'), + _ = require('lodash'), moment = require('moment'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + models = require('../models'), config = require('../config'), - pipeline = require(config.get('paths').corePath + '/server/utils/pipeline'), - dataProvider = require(config.get('paths').corePath + '/server/models'), - i18n = require(config.get('paths').corePath + '/server/i18n'), - errors = require(config.get('paths').corePath + '/server/errors'), - apiPosts = require(config.get('paths').corePath + '/server/api/posts'), - utils = require('./utils'); + errors = require('../errors'), + i18n = require('../i18n'), + postsAPI = require('../api/posts'); /** * Publish a scheduled post @@ -35,18 +35,18 @@ exports.publishPost = function publishPost(object, options) { options.context = {internal: true}; return pipeline([ - utils.validate('posts', {opts: utils.idDefaultOptions}), + apiUtils.validate('posts', {opts: apiUtils.idDefaultOptions}), function (cleanOptions) { cleanOptions.status = 'scheduled'; - return dataProvider.Base.transaction(function (transacting) { + return models.Base.transaction(function (transacting) { cleanOptions.transacting = transacting; cleanOptions.forUpdate = true; // CASE: extend allowed options, see api/utils.js cleanOptions.opts = ['forUpdate', 'transacting']; - return apiPosts.read(cleanOptions) + return postsAPI.read(cleanOptions) .then(function (result) { post = result.posts[0]; publishedAtMoment = moment(post.published_at); @@ -59,7 +59,7 @@ exports.publishPost = function publishPost(object, options) { return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.job.publishInThePast')})); } - return apiPosts.edit({ + return postsAPI.edit({ posts: [{status: 'published'}]}, _.pick(cleanOptions, ['context', 'id', 'transacting', 'forUpdate', 'opts']) ); @@ -78,7 +78,7 @@ exports.getScheduledPosts = function readPosts(options) { options.context = {internal: true}; return pipeline([ - utils.validate('posts', {opts: ['from', 'to']}), + apiUtils.validate('posts', {opts: ['from', 'to']}), function (cleanOptions) { cleanOptions.filter = 'status:scheduled'; cleanOptions.columns = ['id', 'published_at', 'created_at']; @@ -91,7 +91,7 @@ exports.getScheduledPosts = function readPosts(options) { cleanOptions.filter += '+created_at:<=\'' + moment(cleanOptions.to).format('YYYY-MM-DD HH:mm:ss') + '\''; } - return dataProvider.Post.findAll(cleanOptions) + return models.Post.findAll(cleanOptions) .then(function (result) { return Promise.resolve({posts: result.models}); }); diff --git a/core/server/api/settings.js b/core/server/api/settings.js index 72de574f2e..c9303df409 100644 --- a/core/server/api/settings.js +++ b/core/server/api/settings.js @@ -1,19 +1,15 @@ // # Settings API // RESTful API for the Setting resource -var _ = require('lodash'), - dataProvider = require('../models'), - Promise = require('bluebird'), - canThis = require('../permissions').canThis, - errors = require('../errors'), - utils = require('./utils'), - i18n = require('../i18n'), - - docName = 'settings', - settings, - +var Promise = require('bluebird'), + _ = require('lodash'), + models = require('../models'), + canThis = require('../permissions').canThis, + apiUtils = require('./utils'), + errors = require('../errors'), + i18n = require('../i18n'), settingsCache = require('../settings/cache'), - - settingsFilter, + docName = 'settings', + settings, settingsResult, canEditAllSettings, @@ -223,9 +219,9 @@ settings = { }); return canEditAllSettings(object.settings, options).then(function () { - return utils.checkObject(object, docName).then(function (checkedData) { + return apiUtils.checkObject(object, docName).then(function (checkedData) { options.user = self.user; - return dataProvider.Settings.edit(checkedData.settings, options); + return models.Settings.edit(checkedData.settings, options); }).then(function (settingsModelsArray) { // Instead of a standard bookshelf collection, Settings.edit returns an array of Settings Models. // We convert this to JSON, by calling toJSON on each Model (using invokeMap for ease) diff --git a/core/server/api/slack.js b/core/server/api/slack.js index 8ef40b82b9..b916d03735 100644 --- a/core/server/api/slack.js +++ b/core/server/api/slack.js @@ -1,7 +1,7 @@ // # Slack API // API for sending Test Notifications to Slack -var events = require('../events'), - Promise = require('bluebird'), +var Promise = require('bluebird'), + events = require('../events'), slack; /** diff --git a/core/server/api/slugs.js b/core/server/api/slugs.js index 8105d34b07..f14989c79f 100644 --- a/core/server/api/slugs.js +++ b/core/server/api/slugs.js @@ -1,13 +1,12 @@ // # Slug API // RESTful API for the Slug resource -var dataProvider = require('../models'), - errors = require('../errors'), - Promise = require('bluebird'), - pipeline = require('../utils/pipeline'), - utils = require('./utils'), - i18n = require('../i18n'), - docName = 'slugs', - +var Promise = require('bluebird'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + models = require('../models'), + errors = require('../errors'), + i18n = require('../i18n'), + docName = 'slugs', slugs, allowedTypes; @@ -32,10 +31,10 @@ slugs = { // `allowedTypes` is used to define allowed slug types and map them against its model class counterpart allowedTypes = { - post: dataProvider.Post, - tag: dataProvider.Tag, - user: dataProvider.User, - app: dataProvider.App + post: models.Post, + tag: models.Tag, + user: models.User, + app: models.App }; /** @@ -58,13 +57,13 @@ slugs = { * @returns {Object} options */ function modelQuery(options) { - return dataProvider.Base.Model.generateSlug(allowedTypes[options.type], options.data.name, {status: 'all'}); + return models.Base.Model.generateSlug(allowedTypes[options.type], options.data.name, {status: 'all'}); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: opts, attrs: attrs}), - utils.handlePermissions(docName, 'generate'), + apiUtils.validate(docName, {opts: opts, attrs: attrs}), + apiUtils.handlePermissions(docName, 'generate'), checkAllowedTypes, modelQuery ]; diff --git a/core/server/api/subscribers.js b/core/server/api/subscribers.js index 7cc10f901f..a35756ba34 100644 --- a/core/server/api/subscribers.js +++ b/core/server/api/subscribers.js @@ -1,16 +1,15 @@ // # Tag API // RESTful API for the Tag resource -var Promise = require('bluebird'), - _ = require('lodash'), - fs = require('fs'), - dataProvider = require('../models'), - errors = require('../errors'), - utils = require('./utils'), - serverUtils = require('../utils'), - pipeline = require('../utils/pipeline'), - i18n = require('../i18n'), - - docName = 'subscribers', +var Promise = require('bluebird'), + _ = require('lodash'), + fs = require('fs'), + pipeline = require('../utils/pipeline'), + globalUtils = require('../utils'), + apiUtils = require('./utils'), + models = require('../models'), + errors = require('../errors'), + i18n = require('../i18n'), + docName = 'subscribers', subscribers; /** @@ -34,13 +33,13 @@ subscribers = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.Subscriber.findPage(options); + return models.Subscriber.findPage(options); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.browseDefaultOptions}), - utils.handlePermissions(docName, 'browse'), + apiUtils.validate(docName, {opts: apiUtils.browseDefaultOptions}), + apiUtils.handlePermissions(docName, 'browse'), doQuery ]; @@ -64,13 +63,13 @@ subscribers = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.Subscriber.findOne(options.data, _.omit(options, ['data'])); + return models.Subscriber.findOne(options.data, _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {attrs: attrs}), - utils.handlePermissions(docName, 'read'), + apiUtils.validate(docName, {attrs: attrs}), + apiUtils.handlePermissions(docName, 'read'), doQuery ]; @@ -99,7 +98,7 @@ subscribers = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.Subscriber.getByEmail(options.data.subscribers[0].email) + return models.Subscriber.getByEmail(options.data.subscribers[0].email) .then(function (subscriber) { if (subscriber && options.context.external) { // we don't expose this information @@ -108,7 +107,7 @@ subscribers = { return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.subscribers.subscriberAlreadyExists')})); } - return dataProvider.Subscriber.add(options.data.subscribers[0], _.omit(options, ['data'])).catch(function (error) { + 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')})); } @@ -120,8 +119,8 @@ subscribers = { // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName), - utils.handlePermissions(docName, 'add'), + apiUtils.validate(docName), + apiUtils.handlePermissions(docName, 'add'), doQuery ]; @@ -149,13 +148,13 @@ subscribers = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.Subscriber.edit(options.data.subscribers[0], _.omit(options, ['data'])); + return models.Subscriber.edit(options.data.subscribers[0], _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.idDefaultOptions}), - utils.handlePermissions(docName, 'edit'), + apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}), + apiUtils.handlePermissions(docName, 'edit'), doQuery ]; @@ -187,13 +186,13 @@ subscribers = { * @param {Object} options */ function doQuery(options) { - return dataProvider.Subscriber.destroy(options).return(null); + return models.Subscriber.destroy(options).return(null); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.idDefaultOptions}), - utils.handlePermissions(docName, 'destroy'), + apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}), + apiUtils.handlePermissions(docName, 'destroy'), doQuery ]; @@ -239,7 +238,7 @@ subscribers = { // Export data, otherwise send error 500 function exportSubscribers() { - return dataProvider.Subscriber.findAll(options).then(function (data) { + return models.Subscriber.findAll(options).then(function (data) { return formatCSV(data.toJSON(options)); }).catch(function (err) { return Promise.reject(new errors.GhostError({err: err})); @@ -247,7 +246,7 @@ subscribers = { } tasks = [ - utils.handlePermissions(docName, 'browse'), + apiUtils.handlePermissions(docName, 'browse'), exportSubscribers ]; @@ -272,7 +271,7 @@ subscribers = { invalid = 0, duplicates = 0; - return serverUtils.readCSV({ + return globalUtils.readCSV({ path: filePath, columnsToExtract: [{name: 'email', lookup: /email/i}] }).then(function (result) { @@ -309,7 +308,7 @@ subscribers = { } tasks = [ - utils.handlePermissions(docName, 'add'), + apiUtils.handlePermissions(docName, 'add'), importCSV ]; diff --git a/core/server/api/tags.js b/core/server/api/tags.js index d569186c0e..b1e652d5be 100644 --- a/core/server/api/tags.js +++ b/core/server/api/tags.js @@ -1,14 +1,13 @@ // # Tag API // RESTful API for the Tag resource -var Promise = require('bluebird'), - _ = require('lodash'), - dataProvider = require('../models'), - errors = require('../errors'), - utils = require('./utils'), - pipeline = require('../utils/pipeline'), - i18n = require('../i18n'), - - docName = 'tags', +var Promise = require('bluebird'), + _ = require('lodash'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + models = require('../models'), + errors = require('../errors'), + i18n = require('../i18n'), + docName = 'tags', allowedIncludes = ['count.posts'], tags; @@ -33,14 +32,14 @@ tags = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.Tag.findPage(options); + return models.Tag.findPage(options); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.browseDefaultOptions}), - utils.handlePublicPermissions(docName, 'browse'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: apiUtils.browseDefaultOptions}), + apiUtils.handlePublicPermissions(docName, 'browse'), + apiUtils.convertOptions(allowedIncludes), doQuery ]; @@ -64,14 +63,14 @@ tags = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.Tag.findOne(options.data, _.omit(options, ['data'])); + return models.Tag.findOne(options.data, _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {attrs: attrs}), - utils.handlePublicPermissions(docName, 'read'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {attrs: attrs}), + apiUtils.handlePublicPermissions(docName, 'read'), + apiUtils.convertOptions(allowedIncludes), doQuery ]; @@ -100,14 +99,14 @@ tags = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.Tag.add(options.data.tags[0], _.omit(options, ['data'])); + return models.Tag.add(options.data.tags[0], _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName), - utils.handlePermissions(docName, 'add'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName), + apiUtils.handlePermissions(docName, 'add'), + apiUtils.convertOptions(allowedIncludes), doQuery ]; @@ -136,14 +135,14 @@ tags = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.Tag.edit(options.data.tags[0], _.omit(options, ['data'])); + return models.Tag.edit(options.data.tags[0], _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.idDefaultOptions}), - utils.handlePermissions(docName, 'edit'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}), + apiUtils.handlePermissions(docName, 'edit'), + apiUtils.convertOptions(allowedIncludes), doQuery ]; @@ -175,14 +174,14 @@ tags = { * @param {Object} options */ function deleteTag(options) { - return dataProvider.Tag.destroy(options).return(null); + return models.Tag.destroy(options).return(null); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.idDefaultOptions}), - utils.handlePermissions(docName, 'destroy'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}), + apiUtils.handlePermissions(docName, 'destroy'), + apiUtils.convertOptions(allowedIncludes), deleteTag ]; diff --git a/core/server/api/themes.js b/core/server/api/themes.js index 3b8b60f754..3c67b5ec71 100644 --- a/core/server/api/themes.js +++ b/core/server/api/themes.js @@ -3,11 +3,11 @@ var debug = require('ghost-ignition').debug('api:themes'), Promise = require('bluebird'), fs = require('fs-extra'), + apiUtils = require('./utils'), errors = require('../errors'), events = require('../events'), - logging = require('../logging'), - apiUtils = require('./utils'), i18n = require('../i18n'), + logging = require('../logging'), settingsModel = require('../models/settings').Settings, settingsCache = require('../settings/cache'), themeUtils = require('../themes'), diff --git a/core/server/api/upload.js b/core/server/api/upload.js index e97ca89424..8e200da385 100644 --- a/core/server/api/upload.js +++ b/core/server/api/upload.js @@ -1,5 +1,5 @@ var Promise = require('bluebird'), - fs = require('fs-extra'), + fs = require('fs-extra'), pUnlink = Promise.promisify(fs.unlink), storage = require('../adapters/storage'), upload; diff --git a/core/server/api/users.js b/core/server/api/users.js index 9cdef17d42..b5ab6ce024 100644 --- a/core/server/api/users.js +++ b/core/server/api/users.js @@ -1,15 +1,15 @@ // # Users API // RESTful API for the User resource -var Promise = require('bluebird'), - _ = require('lodash'), - dataProvider = require('../models'), - canThis = require('../permissions').canThis, - errors = require('../errors'), - events = require('../events'), - utils = require('./utils'), - pipeline = require('../utils/pipeline'), - i18n = require('../i18n'), - docName = 'users', +var Promise = require('bluebird'), + _ = require('lodash'), + pipeline = require('../utils/pipeline'), + apiUtils = require('./utils'), + canThis = require('../permissions').canThis, + models = require('../models'), + errors = require('../errors'), + events = require('../events'), + i18n = require('../i18n'), + docName = 'users', // TODO: implement created_by, updated_by allowedIncludes = ['count.posts', 'permissions', 'roles', 'roles.permissions'], users; @@ -28,7 +28,7 @@ users = { */ browse: function browse(options) { var extraOptions = ['status'], - permittedOptions = utils.browseDefaultOptions.concat(extraOptions), + permittedOptions = apiUtils.browseDefaultOptions.concat(extraOptions), tasks; /** @@ -38,14 +38,14 @@ users = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.User.findPage(options); + return models.User.findPage(options); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: permittedOptions}), - utils.handlePublicPermissions(docName, 'browse'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {opts: permittedOptions}), + apiUtils.handlePublicPermissions(docName, 'browse'), + apiUtils.convertOptions(allowedIncludes), doQuery ]; @@ -75,14 +75,14 @@ users = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.User.findOne(options.data, _.omit(options, ['data'])); + return models.User.findOne(options.data, _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {attrs: attrs}), - utils.handlePublicPermissions(docName, 'read'), - utils.convertOptions(allowedIncludes), + apiUtils.validate(docName, {attrs: attrs}), + apiUtils.handlePublicPermissions(docName, 'read'), + apiUtils.convertOptions(allowedIncludes), doQuery ]; @@ -108,7 +108,7 @@ users = { */ edit: function edit(object, options) { var extraOptions = ['editRoles'], - permittedOptions = extraOptions.concat(utils.idDefaultOptions), + permittedOptions = extraOptions.concat(apiUtils.idDefaultOptions), tasks; if (object.users && object.users[0] && object.users[0].roles && object.users[0].roles[0]) { @@ -137,7 +137,7 @@ users = { return canThis(options.context).edit.user(options.id).then(function () { // CASE: can't edit my own status to inactive or locked if (options.id === options.context.user) { - if (dataProvider.User.inactiveStates.indexOf(options.data.users[0].status) !== -1) { + if (models.User.inactiveStates.indexOf(options.data.users[0].status) !== -1) { return Promise.reject(new errors.NoPermissionError({ message: i18n.t('errors.api.users.cannotChangeStatus') })); @@ -154,7 +154,7 @@ users = { roleId = role.id || role, editedUserId = options.id; - return dataProvider.User.findOne( + return models.User.findOne( {id: options.context.user, status: 'all'}, {include: ['roles']} ).then(function (contextUser) { var contextRoleId = contextUser.related('roles').toJSON(options)[0].id; @@ -165,7 +165,7 @@ users = { })); } - return dataProvider.User.findOne({role: 'Owner'}).then(function (owner) { + return models.User.findOne({role: 'Owner'}).then(function (owner) { if (contextUser.id !== owner.id) { if (editedUserId === owner.id) { if (owner.related('roles').at(0).id !== roleId) { @@ -198,14 +198,14 @@ users = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.User.edit(options.data.users[0], _.omit(options, ['data'])); + return models.User.edit(options.data.users[0], _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: permittedOptions}), + apiUtils.validate(docName, {opts: permittedOptions}), handlePermissions, - utils.convertOptions(allowedIncludes), + apiUtils.convertOptions(allowedIncludes), doQuery ]; @@ -250,15 +250,15 @@ users = { * @param {Object} options */ function deleteUser(options) { - return dataProvider.Base.transaction(function (t) { + return models.Base.transaction(function (t) { options.transacting = t; return Promise.all([ - dataProvider.Accesstoken.destroyByUser(options), - dataProvider.Refreshtoken.destroyByUser(options), - dataProvider.Post.destroyByAuthor(options) + models.Accesstoken.destroyByUser(options), + models.Refreshtoken.destroyByUser(options), + models.Post.destroyByAuthor(options) ]).then(function () { - return dataProvider.User.destroy(options); + return models.User.destroy(options); }).return(null); }).catch(function (err) { return Promise.reject(new errors.NoPermissionError({ @@ -269,9 +269,9 @@ users = { // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate(docName, {opts: utils.idDefaultOptions}), + apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}), handlePermissions, - utils.convertOptions(allowedIncludes), + apiUtils.convertOptions(allowedIncludes), deleteUser ]; @@ -289,7 +289,7 @@ users = { var tasks; function validateRequest() { - return utils.validate('password')(object, options) + return apiUtils.validate('password')(object, options) .then(function (options) { var data = options.data.password[0]; @@ -327,7 +327,7 @@ users = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.User.changePassword( + return models.User.changePassword( options.data.password[0], _.omit(options, ['data']) ); @@ -337,7 +337,7 @@ users = { tasks = [ validateRequest, handlePermissions, - utils.convertOptions(allowedIncludes), + apiUtils.convertOptions(allowedIncludes), doQuery ]; @@ -363,7 +363,7 @@ users = { * @returns {Object} options */ function handlePermissions(options) { - return dataProvider.Role.findOne({name: 'Owner'}).then(function (ownerRole) { + return models.Role.findOne({name: 'Owner'}).then(function (ownerRole) { return canThis(options.context).assign.role(ownerRole); }).then(function () { return options; @@ -377,14 +377,14 @@ users = { * @returns {Object} options */ function doQuery(options) { - return dataProvider.User.transferOwnership(options.data.owner[0], _.omit(options, ['data'])); + return models.User.transferOwnership(options.data.owner[0], _.omit(options, ['data'])); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ - utils.validate('owner'), + apiUtils.validate('owner'), handlePermissions, - utils.convertOptions(allowedIncludes), + apiUtils.convertOptions(allowedIncludes), doQuery ]; diff --git a/core/server/api/utils.js b/core/server/api/utils.js index b3a33674e3..08a56652bc 100644 --- a/core/server/api/utils.js +++ b/core/server/api/utils.js @@ -1,13 +1,12 @@ // # API Utils // Shared helpers for working with the API var Promise = require('bluebird'), - _ = require('lodash'), - path = require('path'), - errors = require('../errors'), + _ = require('lodash'), + path = require('path'), permissions = require('../permissions'), - validation = require('../data/validation'), - i18n = require('../i18n'), - + validation = require('../data/validation'), + errors = require('../errors'), + i18n = require('../i18n'), utils; utils = { diff --git a/core/server/apps/amp/lib/router.js b/core/server/apps/amp/lib/router.js index 0e725f28c5..d9e4184c44 100644 --- a/core/server/apps/amp/lib/router.js +++ b/core/server/apps/amp/lib/router.js @@ -14,6 +14,7 @@ var path = require('path'), function controller(req, res, next) { var templateName = 'amp', defaultTemplate = path.resolve(__dirname, 'views', templateName + '.hbs'), + view = templates.pickTemplate(templateName, defaultTemplate), data = req.body || {}; if (res.error) { @@ -22,12 +23,14 @@ function controller(req, res, next) { setResponseContext(req, res, data); - // we have to check the context. Our context must be ['post', 'amp'], otherwise we won't render the template - if (_.includes(res.locals.context, 'post') && _.includes(res.locals.context, 'amp')) { - return res.render(templates.pickTemplate(templateName, defaultTemplate), data); + // Context check: + // Our context must be ['post', 'amp'], otherwise we won't render the template + // This prevents AMP from being rendered for pages + if (_.intersection(res.locals.context, ['post', 'amp']).length < 2) { + return next(); } - return next(); + return res.render(view, data); } function getPostData(req, res, next) { diff --git a/core/server/apps/private-blogging/lib/router.js b/core/server/apps/private-blogging/lib/router.js index ef4e35a3ee..9cc1d07934 100644 --- a/core/server/apps/private-blogging/lib/router.js +++ b/core/server/apps/private-blogging/lib/router.js @@ -11,6 +11,7 @@ var path = require('path'), function controller(req, res) { var templateName = 'private', defaultTemplate = path.resolve(__dirname, 'views', templateName + '.hbs'), + view = templates.pickTemplate(templateName, defaultTemplate), data = {}; if (res.error) { @@ -19,7 +20,7 @@ function controller(req, res) { setResponseContext(req, res); - return res.render(templates.pickTemplate(templateName, defaultTemplate), data); + return res.render(view, data); } // password-protected frontend route diff --git a/core/server/apps/subscribers/lib/router.js b/core/server/apps/subscribers/lib/router.js index b719ae2fb9..5927f1df3c 100644 --- a/core/server/apps/subscribers/lib/router.js +++ b/core/server/apps/subscribers/lib/router.js @@ -9,17 +9,18 @@ var path = require('path'), errors = require('../../../errors'), validator = require('../../../data/validation').validator, templates = require('../../../controllers/frontend/templates'), - postlookup = require('../../../controllers/frontend/post-lookup'), + postLookup = require('../../../controllers/frontend/post-lookup'), setResponseContext = require('../../../controllers/frontend/context'); function controller(req, res) { var templateName = 'subscribe', defaultTemplate = path.resolve(__dirname, 'views', templateName + '.hbs'), + view = templates.pickTemplate(templateName, defaultTemplate), data = req.body; setResponseContext(req, res); - return res.render(templates.pickTemplate(templateName, defaultTemplate), data); + return res.render(view, data); } /** @@ -60,7 +61,7 @@ function handleSource(req, res, next) { delete req.body.location; delete req.body.referrer; - postlookup(req.body.subscribed_url) + postLookup(req.body.subscribed_url) .then(function (result) { if (result && result.post) { req.body.post_id = result.post.id; diff --git a/core/server/controllers/frontend/render-channel.js b/core/server/controllers/frontend/render-channel.js index daf9a68ae5..808175a852 100644 --- a/core/server/controllers/frontend/render-channel.js +++ b/core/server/controllers/frontend/render-channel.js @@ -45,6 +45,7 @@ function renderChannel(req, res, next) { // Do final data formatting and then render result.posts = posts; result = formatResponse.channel(result); + setResponseContext(req, res); debug('Rendering view: ' + view); res.render(view, result); diff --git a/core/server/data/meta/image-dimensions.js b/core/server/data/meta/image-dimensions.js index 8862f11e9f..ff777149c1 100644 --- a/core/server/data/meta/image-dimensions.js +++ b/core/server/data/meta/image-dimensions.js @@ -1,6 +1,6 @@ var getCachedImageSizeFromUrl = require('../../utils/cached-image-size-from-url'), - Promise = require('bluebird'), - _ = require('lodash'); + Promise = require('bluebird'), + _ = require('lodash'); /** * Get Image dimensions @@ -11,58 +11,51 @@ var getCachedImageSizeFromUrl = require('../../utils/cached-image-size-from-url' */ function getImageDimensions(metaData) { var fetch = { - coverImage: getCachedImageSizeFromUrl(metaData.coverImage.url), - authorImage: getCachedImageSizeFromUrl(metaData.authorImage.url), - ogImage: getCachedImageSizeFromUrl(metaData.ogImage.url), - logo: getCachedImageSizeFromUrl(metaData.blog.logo.url) - }; + coverImage: getCachedImageSizeFromUrl(metaData.coverImage.url), + authorImage: getCachedImageSizeFromUrl(metaData.authorImage.url), + ogImage: getCachedImageSizeFromUrl(metaData.ogImage.url), + logo: getCachedImageSizeFromUrl(metaData.blog.logo.url) + }; - return Promise.props(fetch).then(function (resolve) { - var imageObj = {}; - - imageObj = { - coverImage: resolve.coverImage, - authorImage: resolve.authorImage, - ogImage: resolve.ogImage, - logo: resolve.logo - }; - - _.forEach(imageObj, function (key, value) { - if (_.has(key, 'width') && _.has(key, 'height')) { - // We have some restrictions for publisher.logo: - // The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px). - // Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453), - // we will fake it in some cases or not produce an imageObject at all. - if (value === 'logo') { - if (key.height <= 60 && key.width <= 600) { - _.assign(metaData.blog[value], { + return Promise + .props(fetch) + .then(function (imageObj) { + _.forEach(imageObj, function (key, value) { + if (_.has(key, 'width') && _.has(key, 'height')) { + // We have some restrictions for publisher.logo: + // The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px). + // Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453), + // we will fake it in some cases or not produce an imageObject at all. + if (value === 'logo') { + if (key.height <= 60 && key.width <= 600) { + _.assign(metaData.blog[value], { + dimensions: { + width: key.width, + height: key.height + } + }); + } else if (key.width === key.height) { + // CASE: the logo is too large, but it is a square. We fake it... + _.assign(metaData.blog[value], { + dimensions: { + width: 60, + height: 60 + } + }); + } + } else { + _.assign(metaData[value], { dimensions: { width: key.width, height: key.height } }); - } else if (key.width === key.height) { - // CASE: the logo is too large, but it is a square. We fake it... - _.assign(metaData.blog[value], { - dimensions: { - width: 60, - height: 60 - } - }); } - } else { - _.assign(metaData[value], { - dimensions: { - width: key.width, - height: key.height - } - }); } - } - }); + }); - return metaData; - }); + return metaData; + }); } module.exports = getImageDimensions;