0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-10 23:36:14 -05:00

Swapped common for @tryghost/errors in core/server/web

- Update all references to common.errors to use @tryghost/errors
- Use dereferencing to only require used bits of common in each file
This commit is contained in:
Hannah Wolfe 2020-04-09 19:40:00 +01:00
parent 1ffdef98c3
commit 4f5fb3d820
18 changed files with 102 additions and 91 deletions

View file

@ -2,7 +2,7 @@ const debug = require('ghost-ignition').debug('web:admin:controller');
const path = require('path'); const path = require('path');
const config = require('../../config'); const config = require('../../config');
const updateCheck = require('../../update-check'); const updateCheck = require('../../update-check');
const common = require('../../lib/common'); const {logging} = require('../../lib/common');
/** /**
* @description Admin controller to handle /ghost/ requests. * @description Admin controller to handle /ghost/ requests.
@ -18,7 +18,7 @@ module.exports = function adminController(req, res) {
// CASE: trigger update check unit and let it run in background, don't block the admin rendering // CASE: trigger update check unit and let it run in background, don't block the admin rendering
updateCheck() updateCheck()
.catch((err) => { .catch((err) => {
common.logging.error(err); logging.error(err);
}); });
const defaultTemplate = config.get('env') === 'production' ? 'default-prod.html' : 'default.html'; const defaultTemplate = config.get('env') === 'production' ? 'default-prod.html' : 'default.html';

View file

@ -1,4 +1,5 @@
const common = require('../../../../lib/common'); const errors = require('@tryghost/errors');
const {i18n} = require('../../../../lib/common');
const auth = require('../../../../services/auth'); const auth = require('../../../../services/auth');
const shared = require('../../../shared'); const shared = require('../../../shared');
@ -38,9 +39,9 @@ const notImplemented = function (req, res, next) {
} }
} }
next(new common.errors.GhostError({ next(new errors.GhostError({
errorType: 'NotImplementedError', errorType: 'NotImplementedError',
message: common.i18n.t('errors.api.common.notImplemented'), message: i18n.t('errors.api.common.notImplemented'),
statusCode: '501' statusCode: '501'
})); }));
}; };

View file

@ -1,4 +1,5 @@
const common = require('../../../../lib/common'); const errors = require('@tryghost/errors');
const {i18n} = require('../../../../lib/common');
const auth = require('../../../../services/auth'); const auth = require('../../../../services/auth');
const shared = require('../../../shared'); const shared = require('../../../shared');
@ -35,9 +36,9 @@ const notImplemented = function (req, res, next) {
} }
} }
next(new common.errors.GhostError({ next(new errors.GhostError({
errorType: 'NotImplementedError', errorType: 'NotImplementedError',
message: common.i18n.t('errors.api.common.notImplemented'), message: i18n.t('errors.api.common.notImplemented'),
statusCode: '501' statusCode: '501'
})); }));
}; };
@ -78,4 +79,3 @@ module.exports.publicAdminApi = [
shared.middlewares.prettyUrls, shared.middlewares.prettyUrls,
notImplemented notImplemented
]; ];

View file

@ -1,8 +1,9 @@
const moment = require('moment'); const moment = require('moment');
const extend = require('lodash/extend'); const extend = require('lodash/extend');
const pick = require('lodash/pick'); const pick = require('lodash/pick');
const errors = require('@tryghost/errors');
const config = require('../../../../config'); const config = require('../../../../config');
const common = require('../../../../lib/common'); const {logging,i18n} = require('../../../../lib/common');
const spam = config.get('spam') || {}; const spam = config.get('spam') || {};
const spamPrivateBlog = spam.private_blog || {}; const spamPrivateBlog = spam.private_blog || {};
@ -24,7 +25,7 @@ let contentApiKeyInstance;
const spamConfigKeys = ['freeRetries', 'minWait', 'maxWait', 'lifetime']; const spamConfigKeys = ['freeRetries', 'minWait', 'maxWait', 'lifetime'];
const handleStoreError = (err) => { const handleStoreError = (err) => {
const customError = new common.errors.InternalServerError({ const customError = new errors.InternalServerError({
message: 'Unknown error', message: 'Unknown error',
err: err.parent ? err.parent : err err: err.parent ? err.parent : err
}); });
@ -34,7 +35,7 @@ const handleStoreError = (err) => {
// we are using reset as synchronous call, so we have to log the error if it occurs // we are using reset as synchronous call, so we have to log the error if it occurs
// there is no way to try/catch, because the reset operation happens asynchronous // there is no way to try/catch, because the reset operation happens asynchronous
if (!err.next) { if (!err.next) {
common.logging.error(err); logging.error(err);
return; return;
} }
@ -60,11 +61,11 @@ const globalBlock = () => {
extend({ extend({
attachResetToRequest: false, attachResetToRequest: false,
failCallback(req, res, next, nextValidRequestDate) { failCallback(req, res, next, nextValidRequestDate) {
return next(new common.errors.TooManyRequestsError({ return next(new errors.TooManyRequestsError({
message: `Too many attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`, message: `Too many attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`,
context: common.i18n.t('errors.middleware.spamprevention.forgottenPasswordIp.error', context: i18n.t('errors.middleware.spamprevention.forgottenPasswordIp.error',
{rfa: spamGlobalBlock.freeRetries + 1 || 5, rfp: spamGlobalBlock.lifetime || 60 * 60}), {rfa: spamGlobalBlock.freeRetries + 1 || 5, rfp: spamGlobalBlock.lifetime || 60 * 60}),
help: common.i18n.t('errors.middleware.spamprevention.tooManyAttempts') help: i18n.t('errors.middleware.spamprevention.tooManyAttempts')
})); }));
}, },
handleStoreError: handleStoreError handleStoreError: handleStoreError
@ -90,11 +91,11 @@ const globalReset = () => {
attachResetToRequest: false, attachResetToRequest: false,
failCallback(req, res, next, nextValidRequestDate) { failCallback(req, res, next, nextValidRequestDate) {
// TODO use i18n again // TODO use i18n again
return next(new common.errors.TooManyRequestsError({ return next(new errors.TooManyRequestsError({
message: `Too many attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`, message: `Too many attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`,
context: common.i18n.t('errors.middleware.spamprevention.forgottenPasswordIp.error', context: i18n.t('errors.middleware.spamprevention.forgottenPasswordIp.error',
{rfa: spamGlobalReset.freeRetries + 1 || 5, rfp: spamGlobalReset.lifetime || 60 * 60}), {rfa: spamGlobalReset.freeRetries + 1 || 5, rfp: spamGlobalReset.lifetime || 60 * 60}),
help: common.i18n.t('errors.middleware.spamprevention.forgottenPasswordIp.context') help: i18n.t('errors.middleware.spamprevention.forgottenPasswordIp.context')
})); }));
}, },
handleStoreError: handleStoreError handleStoreError: handleStoreError
@ -123,11 +124,11 @@ const userLogin = () => {
extend({ extend({
attachResetToRequest: true, attachResetToRequest: true,
failCallback(req, res, next, nextValidRequestDate) { failCallback(req, res, next, nextValidRequestDate) {
return next(new common.errors.TooManyRequestsError({ return next(new errors.TooManyRequestsError({
message: `Too many sign-in attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`, message: `Too many sign-in attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`,
// TODO add more options to i18n // TODO add more options to i18n
context: common.i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context'), context: i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context'),
help: common.i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context') help: i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context')
})); }));
}, },
handleStoreError: handleStoreError handleStoreError: handleStoreError
@ -155,11 +156,11 @@ const userReset = function userReset() {
extend({ extend({
attachResetToRequest: true, attachResetToRequest: true,
failCallback(req, res, next, nextValidRequestDate) { failCallback(req, res, next, nextValidRequestDate) {
return next(new common.errors.TooManyRequestsError({ return next(new errors.TooManyRequestsError({
message: `Too many password reset attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`, message: `Too many password reset attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`,
context: common.i18n.t('errors.middleware.spamprevention.forgottenPasswordEmail.error', context: i18n.t('errors.middleware.spamprevention.forgottenPasswordEmail.error',
{rfa: spamUserReset.freeRetries + 1 || 5, rfp: spamUserReset.lifetime || 60 * 60}), {rfa: spamUserReset.freeRetries + 1 || 5, rfp: spamUserReset.lifetime || 60 * 60}),
help: common.i18n.t('errors.middleware.spamprevention.forgottenPasswordEmail.context') help: i18n.t('errors.middleware.spamprevention.forgottenPasswordEmail.context')
})); }));
}, },
handleStoreError: handleStoreError handleStoreError: handleStoreError
@ -186,16 +187,16 @@ const privateBlog = () => {
extend({ extend({
attachResetToRequest: false, attachResetToRequest: false,
failCallback(req, res, next, nextValidRequestDate) { failCallback(req, res, next, nextValidRequestDate) {
common.logging.error(new common.errors.TooManyRequestsError({ logging.error(new errors.TooManyRequestsError({
message: common.i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.error', message: i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.error',
{ {
rateSigninAttempts: spamPrivateBlog.freeRetries + 1 || 5, rateSigninAttempts: spamPrivateBlog.freeRetries + 1 || 5,
rateSigninPeriod: spamPrivateBlog.lifetime || 60 * 60 rateSigninPeriod: spamPrivateBlog.lifetime || 60 * 60
}), }),
context: common.i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context') context: i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context')
})); }));
return next(new common.errors.TooManyRequestsError({ return next(new errors.TooManyRequestsError({
message: `Too many private sign-in attempts try again in ${moment(nextValidRequestDate).fromNow(true)}` message: `Too many private sign-in attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`
})); }));
}, },
@ -215,11 +216,11 @@ const contentApiKey = () => {
extend({ extend({
attachResetToRequest: true, attachResetToRequest: true,
failCallback(req, res, next) { failCallback(req, res, next) {
const err = new common.errors.TooManyRequestsError({ const err = new errors.TooManyRequestsError({
message: common.i18n.t('errors.middleware.spamprevention.tooManyAttempts') message: i18n.t('errors.middleware.spamprevention.tooManyAttempts')
}); });
common.logging.error(err); logging.error(err);
return next(err); return next(err);
}, },
handleStoreError: handleStoreError handleStoreError: handleStoreError

View file

@ -1,5 +1,6 @@
const semver = require('semver'); const semver = require('semver');
const common = require('../../../../lib/common'); const errors = require('@tryghost/errors');
const {i18n} = require('../../../../lib/common');
function checkVersionMatch(req, res, next) { function checkVersionMatch(req, res, next) {
const clientVersion = req.get('X-Ghost-Version'); const clientVersion = req.get('X-Ghost-Version');
@ -12,8 +13,8 @@ function checkVersionMatch(req, res, next) {
// always error when the major version is different // always error when the major version is different
if (clientVersion && !semver.satisfies(serverVersion, constraint)) { if (clientVersion && !semver.satisfies(serverVersion, constraint)) {
return next(new common.errors.VersionMismatchError({ return next(new errors.VersionMismatchError({
message: common.i18n.t('errors.middleware.api.versionMismatch', { message: i18n.t('errors.middleware.api.versionMismatch', {
clientVersion: clientVersion, clientVersion: clientVersion,
serverVersion: serverVersion serverVersion: serverVersion
}) })

View file

@ -4,7 +4,8 @@ const url = require('url');
const path = require('path'); const path = require('path');
const debug = require('ghost-ignition').debug('web:shared:mw:custom-redirects'); const debug = require('ghost-ignition').debug('web:shared:mw:custom-redirects');
const config = require('../../../config'); const config = require('../../../config');
const common = require('../../../lib/common'); const errors = require('@tryghost/errors');
const {logging, i18n} = require('../../../lib/common');
const redirectsService = require('../../../../frontend/services/redirects'); const redirectsService = require('../../../../frontend/services/redirects');
const _private = {}; const _private = {};
@ -66,11 +67,11 @@ _private.registerRoutes = () => {
}); });
}); });
} catch (err) { } catch (err) {
if (common.errors.utils.isIgnitionError(err)) { if (errors.utils.isIgnitionError(err)) {
common.logging.error(err); logging.error(err);
} else if (err.code !== 'ENOENT') { } else if (err.code !== 'ENOENT') {
common.logging.error(new common.errors.IncorrectUsageError({ logging.error(new errors.IncorrectUsageError({
message: common.i18n.t('errors.middleware.redirects.register'), message: i18n.t('errors.middleware.redirects.register'),
context: err.message, context: err.message,
help: 'https://ghost.org/docs/api/handlebars-themes/routing/redirects/' help: 'https://ghost.org/docs/api/handlebars-themes/routing/redirects/'
})); }));

View file

@ -1,10 +1,10 @@
const common = require('../../../lib/common'); const {events} = require('../../../lib/common');
const INVALIDATE_ALL = '/*'; const INVALIDATE_ALL = '/*';
module.exports = function emitEvents(req, res, next) { module.exports = function emitEvents(req, res, next) {
res.on('finish', function triggerEvents() { res.on('finish', function triggerEvents() {
if (res.get('X-Cache-Invalidate') === INVALIDATE_ALL) { if (res.get('X-Cache-Invalidate') === INVALIDATE_ALL) {
common.events.emit('site.changed'); events.emit('site.changed');
} }
res.removeListener('finish', triggerEvents); res.removeListener('finish', triggerEvents);

View file

@ -1,8 +1,9 @@
const hbs = require('express-hbs'); const hbs = require('express-hbs');
const _ = require('lodash'); const _ = require('lodash');
const debug = require('ghost-ignition').debug('error-handler'); const debug = require('ghost-ignition').debug('error-handler');
const errors = require('@tryghost/errors');
const config = require('../../../config'); const config = require('../../../config');
const common = require('../../../lib/common'); const {i18n} = require('../../../lib/common');
const helpers = require('../../../../frontend/services/routing/helpers'); const helpers = require('../../../../frontend/services/routing/helpers');
const sentry = require('../../../sentry'); const sentry = require('../../../sentry');
@ -33,23 +34,23 @@ _private.prepareError = (err, req, res, next) => {
err = err[0]; err = err[0];
} }
if (!common.errors.utils.isIgnitionError(err)) { if (!errors.utils.isIgnitionError(err)) {
// We need a special case for 404 errors // We need a special case for 404 errors
// @TODO look at adding this to the GhostError class // @TODO look at adding this to the GhostError class
if (err.statusCode && err.statusCode === 404) { if (err.statusCode && err.statusCode === 404) {
err = new common.errors.NotFoundError({ err = new errors.NotFoundError({
err: err err: err
}); });
} else if (err instanceof TypeError && err.stack.match(/node_modules\/handlebars\//)) { } else if (err instanceof TypeError && err.stack.match(/node_modules\/handlebars\//)) {
// Temporary handling of theme errors from handlebars // Temporary handling of theme errors from handlebars
// @TODO remove this when #10496 is solved properly // @TODO remove this when #10496 is solved properly
err = new common.errors.IncorrectUsageError({ err = new errors.IncorrectUsageError({
err: err, err: err,
message: '{{#if}} or {{#unless}} helper is malformed', message: '{{#if}} or {{#unless}} helper is malformed',
statusCode: err.statusCode statusCode: err.statusCode
}); });
} else { } else {
err = new common.errors.GhostError({ err = new errors.GhostError({
err: err, err: err,
message: err.message, message: err.message,
statusCode: err.statusCode statusCode: err.statusCode
@ -102,8 +103,8 @@ _private.prepareUserMessage = (err, res) => {
destroy: 'delete' destroy: 'delete'
}; };
if (common.i18n.doesTranslationKeyExist(`common.api.actions.${docName}.${method}`)) { if (i18n.doesTranslationKeyExist(`common.api.actions.${docName}.${method}`)) {
action = common.i18n.t(`common.api.actions.${docName}.${method}`); action = i18n.t(`common.api.actions.${docName}.${method}`);
} else if (Object.keys(actionMap).includes(method)) { } else if (Object.keys(actionMap).includes(method)) {
let resource = docName; let resource = docName;
@ -121,7 +122,7 @@ _private.prepareUserMessage = (err, res) => {
userError.context = err.message; userError.context = err.message;
} }
userError.message = common.i18n.t(`errors.api.userMessages.${err.name}`, {action: action}); userError.message = i18n.t(`errors.api.userMessages.${err.name}`, {action: action});
} }
} }
@ -145,10 +146,10 @@ _private.JSONErrorRendererV2 = (err, req, res, next) => { // eslint-disable-line
}); });
}; };
_private.ErrorFallbackMessage = err => `<h1>${common.i18n.t('errors.errors.oopsErrorTemplateHasError')}</h1> _private.ErrorFallbackMessage = err => `<h1>${i18n.t('errors.errors.oopsErrorTemplateHasError')}</h1>
<p>${common.i18n.t('errors.errors.encounteredError')}</p> <p>${i18n.t('errors.errors.encounteredError')}</p>
<pre>${escapeExpression(err.message || err)}</pre> <pre>${escapeExpression(err.message || err)}</pre>
<br ><p>${common.i18n.t('errors.errors.whilstTryingToRender')}</p> <br ><p>${i18n.t('errors.errors.whilstTryingToRender')}</p>
${err.statusCode} <pre>${escapeExpression(err.message || err)}</pre>`; ${err.statusCode} <pre>${escapeExpression(err.message || err)}</pre>`;
_private.ThemeErrorRenderer = (err, req, res, next) => { _private.ThemeErrorRenderer = (err, req, res, next) => {
@ -238,11 +239,11 @@ _private.BasicErrorRenderer = (err, req, res, next) => { // eslint-disable-line
errorHandler.resourceNotFound = (req, res, next) => { errorHandler.resourceNotFound = (req, res, next) => {
// TODO, handle unknown resources & methods differently, so that we can also produce // TODO, handle unknown resources & methods differently, so that we can also produce
// 405 Method Not Allowed // 405 Method Not Allowed
next(new common.errors.NotFoundError({message: common.i18n.t('errors.errors.resourceNotFound')})); next(new errors.NotFoundError({message: i18n.t('errors.errors.resourceNotFound')}));
}; };
errorHandler.pageNotFound = (req, res, next) => { errorHandler.pageNotFound = (req, res, next) => {
next(new common.errors.NotFoundError({message: common.i18n.t('errors.errors.pageNotFound')})); next(new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')}));
}; };
errorHandler.handleJSONResponse = [ errorHandler.handleJSONResponse = [

View file

@ -1,11 +1,11 @@
const errors = require('@tryghost/errors');
const labsUtil = require('../../../services/labs'); const labsUtil = require('../../../services/labs');
const common = require('../../../lib/common');
const labs = flag => (req, res, next) => { const labs = flag => (req, res, next) => {
if (labsUtil.isSet(flag) === true) { if (labsUtil.isSet(flag) === true) {
return next(); return next();
} else { } else {
return next(new common.errors.NotFoundError()); return next(new errors.NotFoundError());
} }
}; };

View file

@ -1,4 +1,4 @@
const common = require('../../../lib/common'); const {logging} = require('../../../lib/common');
/** /**
* @TODO: move this middleware to ignition? * @TODO: move this middleware to ignition?
@ -11,9 +11,9 @@ module.exports = function logRequest(req, res, next) {
req.userId = req.user ? (req.user.id ? req.user.id : req.user) : null; req.userId = req.user ? (req.user.id ? req.user.id : req.user) : null;
if (req.err && req.err.statusCode !== 404) { if (req.err && req.err.statusCode !== 404) {
common.logging.error({req: req, res: res, err: req.err}); logging.error({req: req, res: res, err: req.err});
} else { } else {
common.logging.info({req: req, res: res}); logging.info({req: req, res: res});
} }
res.removeListener('finish', logResponse); res.removeListener('finish', logResponse);

View file

@ -1,17 +1,18 @@
const errors = require('@tryghost/errors');
const config = require('../../../config'); const config = require('../../../config');
const common = require('../../../lib/common'); const {i18n} = require('../../../lib/common');
const urlService = require('../../../../frontend/services/url'); const urlService = require('../../../../frontend/services/url');
module.exports = function maintenance(req, res, next) { module.exports = function maintenance(req, res, next) {
if (config.get('maintenance').enabled) { if (config.get('maintenance').enabled) {
return next(new common.errors.MaintenanceError({ return next(new errors.MaintenanceError({
message: common.i18n.t('errors.general.maintenance') message: i18n.t('errors.general.maintenance')
})); }));
} }
if (!urlService.hasFinished()) { if (!urlService.hasFinished()) {
return next(new common.errors.MaintenanceError({ return next(new errors.MaintenanceError({
message: common.i18n.t('errors.general.maintenanceUrlService') message: i18n.t('errors.general.maintenanceUrlService')
})); }));
} }

View file

@ -1,9 +1,10 @@
const crypto = require('crypto'); const crypto = require('crypto');
const fs = require('fs-extra'); const fs = require('fs-extra');
const path = require('path'); const path = require('path');
const errors = require('@tryghost/errors');
const config = require('../../../config'); const config = require('../../../config');
const urlUtils = require('../../../lib/url-utils'); const urlUtils = require('../../../lib/url-utils');
const common = require('../../../lib/common'); const {i18n} = require('../../../lib/common');
function createPublicFileMiddleware(file, type, maxAge) { function createPublicFileMiddleware(file, type, maxAge) {
let content; let content;
@ -23,8 +24,8 @@ function createPublicFileMiddleware(file, type, maxAge) {
return res.sendFile(filePath, (err) => { return res.sendFile(filePath, (err) => {
if (err && err.status === 404) { if (err && err.status === 404) {
// ensure we're triggering basic asset 404 and not a templated 404 // ensure we're triggering basic asset 404 and not a templated 404
return next(new common.errors.NotFoundError({ return next(new errors.NotFoundError({
message: common.i18n.t('errors.errors.imageNotFound'), message: i18n.t('errors.errors.imageNotFound'),
code: 'STATIC_FILE_NOT_FOUND', code: 'STATIC_FILE_NOT_FOUND',
property: err.path property: err.path
})); }));

View file

@ -12,8 +12,9 @@
// req.baseUrl = /blog // req.baseUrl = /blog
// req.path = /ghost/signin/ // req.path = /ghost/signin/
const errors = require('@tryghost/errors');
const urlUtils = require('../../../lib/url-utils'); const urlUtils = require('../../../lib/url-utils');
const common = require('../../../lib/common'); const {i18n} = require('../../../lib/common');
const localUtils = require('../utils'); const localUtils = require('../utils');
const uncapitalise = (req, res, next) => { const uncapitalise = (req, res, next) => {
@ -36,8 +37,8 @@ const uncapitalise = (req, res, next) => {
try { try {
decodedURI = decodeURIComponent(pathToTest); decodedURI = decodeURIComponent(pathToTest);
} catch (err) { } catch (err) {
return next(new common.errors.NotFoundError({ return next(new errors.NotFoundError({
message: common.i18n.t('errors.errors.pageNotFound'), message: i18n.t('errors.errors.pageNotFound'),
err: err err: err
})); }));
} }

View file

@ -2,14 +2,14 @@ const config = require('../../../config');
const os = require('os'); const os = require('os');
const multer = require('multer'); const multer = require('multer');
const fs = require('fs-extra'); const fs = require('fs-extra');
const common = require('../../../lib/common'); const {logging} = require('../../../lib/common');
const upload = { const upload = {
enabledClear: config.get('uploadClear') || true, enabledClear: config.get('uploadClear') || true,
multer: multer({dest: os.tmpdir()}) multer: multer({dest: os.tmpdir()})
}; };
const deleteSingleFile = file => fs.unlink(file.path).catch(err => common.logging.error(err)); const deleteSingleFile = file => fs.unlink(file.path).catch(err => logging.error(err));
const single = name => (req, res, next) => { const single = name => (req, res, next) => {
const singleUpload = upload.multer.single(name); const singleUpload = upload.multer.single(name);

View file

@ -1,5 +1,6 @@
const errors = require('@tryghost/errors');
const config = require('../../../../config'); const config = require('../../../../config');
const common = require('../../../../lib/common'); const {i18n} = require('../../../../lib/common');
const imageLib = require('../../../../lib/image'); const imageLib = require('../../../../lib/image');
const validIconFileSize = (size) => { const validIconFileSize = (size) => {
@ -13,8 +14,8 @@ module.exports = function blogIcon() {
// CASE: file should not be larger than 100kb // CASE: file should not be larger than 100kb
if (!validIconFileSize(req.file.size)) { if (!validIconFileSize(req.file.size)) {
return next(new common.errors.ValidationError({ return next(new errors.ValidationError({
message: common.i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions}) message: i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions})
})); }));
} }
@ -24,23 +25,23 @@ module.exports = function blogIcon() {
// CASE: file needs to be a square // CASE: file needs to be a square
if (req.file.dimensions.width !== req.file.dimensions.height) { if (req.file.dimensions.width !== req.file.dimensions.height) {
return next(new common.errors.ValidationError({ return next(new errors.ValidationError({
message: common.i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions}) message: i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions})
})); }));
} }
// CASE: icon needs to be bigger than or equal to 60px // CASE: icon needs to be bigger than or equal to 60px
// .ico files can contain multiple sizes, we need at least a minimum of 60px (16px is ok, as long as 60px are present as well) // .ico files can contain multiple sizes, we need at least a minimum of 60px (16px is ok, as long as 60px are present as well)
if (req.file.dimensions.width < 60) { if (req.file.dimensions.width < 60) {
return next(new common.errors.ValidationError({ return next(new errors.ValidationError({
message: common.i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions}) message: i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions})
})); }));
} }
// CASE: icon needs to be smaller than or equal to 1000px // CASE: icon needs to be smaller than or equal to 1000px
if (req.file.dimensions.width > 1000) { if (req.file.dimensions.width > 1000) {
return next(new common.errors.ValidationError({ return next(new errors.ValidationError({
message: common.i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions}) message: i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions})
})); }));
} }

View file

@ -1,4 +1,5 @@
const common = require('../../../../lib/common'); const errors = require('@tryghost/errors');
const {i18n} = require('../../../../lib/common');
const imageLib = require('../../../../lib/image'); const imageLib = require('../../../../lib/image');
module.exports = function profileImage(req, res, next) { module.exports = function profileImage(req, res, next) {
@ -9,8 +10,8 @@ module.exports = function profileImage(req, res, next) {
// CASE: file needs to be a square // CASE: file needs to be a square
if (req.file.dimensions.width !== req.file.dimensions.height) { if (req.file.dimensions.width !== req.file.dimensions.height) {
return next(new common.errors.ValidationError({ return next(new errors.ValidationError({
message: common.i18n.t('errors.api.images.isNotSquare') message: i18n.t('errors.api.images.isNotSquare')
})); }));
} }

View file

@ -1,5 +1,6 @@
const path = require('path'); const path = require('path');
const common = require('../../../../lib/common'); const errors = require('@tryghost/errors');
const {i18n} = require('../../../../lib/common');
const config = require('../../../../config'); const config = require('../../../../config');
const localUtils = require('../../utils'); const localUtils = require('../../utils');
@ -17,8 +18,8 @@ module.exports = function upload(options) {
// Check if a file was provided // Check if a file was provided
if (!localUtils.checkFileExists(req.file)) { if (!localUtils.checkFileExists(req.file)) {
return next(new common.errors.ValidationError({ return next(new errors.ValidationError({
message: common.i18n.t(`errors.api.${type}.missingFile`) message: i18n.t(`errors.api.${type}.missingFile`)
})); }));
} }
@ -26,8 +27,8 @@ module.exports = function upload(options) {
// Check if the file is valid // Check if the file is valid
if (!localUtils.checkFileIsValid(req.file, contentTypes, extensions)) { if (!localUtils.checkFileIsValid(req.file, contentTypes, extensions)) {
return next(new common.errors.UnsupportedMediaTypeError({ return next(new errors.UnsupportedMediaTypeError({
message: common.i18n.t(`errors.api.${type}.invalidFile`, {extensions: extensions}) message: i18n.t(`errors.api.${type}.invalidFile`, {extensions: extensions})
})); }));
} }

View file

@ -3,7 +3,7 @@ const path = require('path');
const express = require('express'); const express = require('express');
const cors = require('cors'); const cors = require('cors');
const {URL} = require('url'); const {URL} = require('url');
const common = require('../../lib/common'); const errors = require('@tryghost/errors');
// App requires // App requires
const config = require('../../config'); const config = require('../../config');
@ -40,7 +40,7 @@ const corsOptionsDelegate = function corsOptionsDelegate(req, callback) {
try { try {
originUrl = new URL(origin); originUrl = new URL(origin);
} catch (err) { } catch (err) {
return callback(new common.errors.BadRequestError({err})); return callback(new errors.BadRequestError({err}));
} }
// originUrl will definitely exist here because according to WHATWG URL spec // originUrl will definitely exist here because according to WHATWG URL spec