2
1
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2023-12-13 21:00:40 +01:00

ES6 migration: server/web/middleware (#9737)

refs #9589
This commit is contained in:
Lars Nolden 2018-09-10 08:07:57 -04:00 committed by Katharina Irrgang
parent b17e242fc6
commit 5e963935f9
16 changed files with 77 additions and 83 deletions

View file

@ -1,15 +1,14 @@
var express = require('express'),
urlService = require('../../services/url'),
adminRedirect;
const express = require('express'),
urlService = require('../../services/url');
adminRedirect = function adminRedirect(path) {
const adminRedirect = function adminRedirect(path) {
return function doRedirect(req, res) {
return urlService.utils.redirectToAdmin(301, res, path);
};
};
module.exports = function adminRedirects() {
var router = express.Router();
const router = express.Router();
// Admin redirects - register redirect as route
// TODO: this should be middleware!
router.get(/^\/(logout|signout)\/$/, adminRedirect('#/signout/'));

View file

@ -1,4 +1,4 @@
var url = require('url'),
const url = require('url'),
spamPrevention = require('./api/spam-prevention');
/**

View file

@ -6,16 +6,16 @@
//
// Allows each app to declare its own default caching rules
var _ = require('lodash'),
config = require('../../config'),
cacheControl;
const _ = require('lodash'),
config = require('../../config');
cacheControl = function cacheControl(options) {
var profiles = {
public: 'public, max-age=' + config.get('caching:frontend:maxAge'),
private: 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
},
output;
const cacheControl = function cacheControl(options) {
const profiles = {
public: 'public, max-age=' + config.get('caching:frontend:maxAge'),
private: 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
};
let output;
if (_.isString(options) && profiles.hasOwnProperty(options)) {
output = profiles[options];

View file

@ -1,5 +1,4 @@
var fs = require('fs-extra'),
_ = require('lodash'),
const fs = require('fs-extra'),
express = require('express'),
url = require('url'),
path = require('path'),
@ -7,20 +6,21 @@ var fs = require('fs-extra'),
config = require('../../config'),
common = require('../../lib/common'),
validation = require('../../data/validation'),
customRedirectsRouter,
_private = {};
let customRedirectsRouter;
_private.registerRoutes = function registerRoutes() {
debug('redirects loading');
customRedirectsRouter = express.Router();
try {
var redirects = fs.readFileSync(path.join(config.getContentPath('data'), 'redirects.json'), 'utf-8');
let redirects = fs.readFileSync(path.join(config.getContentPath('data'), 'redirects.json'), 'utf-8');
redirects = JSON.parse(redirects);
validation.validateRedirects(redirects);
_.each(redirects, function (redirect) {
redirects.forEach(function (redirect) {
/**
* always delete trailing slashes, doesn't matter if regex or not
* Example:
@ -37,7 +37,7 @@ _private.registerRoutes = function registerRoutes() {
debug('register', redirect.from);
customRedirectsRouter.get(new RegExp(redirect.from), function (req, res) {
var maxAge = redirect.permanent ? config.get('caching:customRedirects:maxAge') : 0,
const maxAge = redirect.permanent ? config.get('caching:customRedirects:maxAge') : 0,
parsedUrl = url.parse(req.originalUrl);
res.set({

View file

@ -1,5 +1,4 @@
var _ = require('lodash'),
hbs = require('express-hbs'),
const hbs = require('express-hbs'),
debug = require('ghost-ignition').debug('error-handler'),
config = require('../../config'),
common = require('../../lib/common'),
@ -13,7 +12,7 @@ var _ = require('lodash'),
* It uses the {{asset}} helper, and nothing more
*/
_private.createHbsEngine = function createHbsEngine() {
var engine = hbs.create();
const engine = hbs.create();
engine.registerHelper('asset', require('../../helpers/asset'));
return engine.express4();
@ -27,7 +26,7 @@ _private.createHbsEngine = function createHbsEngine() {
_private.prepareError = function prepareError(err, req, res, next) {
debug(err);
if (_.isArray(err)) {
if (Array.isArray(err)) {
err = err[0];
}
@ -74,11 +73,11 @@ _private.JSONErrorRenderer = function JSONErrorRenderer(err, req, res, next) { /
};
_private.ErrorFallbackMessage = function ErrorFallbackMessage(err) {
return '<h1>' + common.i18n.t('errors.errors.oopsErrorTemplateHasError') + '</h1>' +
'<p>' + common.i18n.t('errors.errors.encounteredError') + '</p>' +
'<pre>' + escapeExpression(err.message || err) + '</pre>' +
'<br ><p>' + common.i18n.t('errors.errors.whilstTryingToRender') + '</p>' +
err.statusCode + ' ' + '<pre>' + escapeExpression(err.message || err) + '</pre>';
return `<h1>${common.i18n.t('errors.errors.oopsErrorTemplateHasError')}</h1>
<p>${common.i18n.t('errors.errors.encounteredError')}</p>
<pre>${escapeExpression(err.message || err)}</pre>
<br ><p>${common.i18n.t('errors.errors.whilstTryingToRender')}</p>
${err.statusCode} <pre>${escapeExpression(err.message || err)}</pre>`;
};
_private.ThemeErrorRenderer = function ThemeErrorRenderer(err, req, res, next) {
@ -92,7 +91,7 @@ _private.ThemeErrorRenderer = function ThemeErrorRenderer(err, req, res, next) {
// Renderer begin
// Format Data
var data = {
const data = {
message: err.message,
// @deprecated Remove in Ghost 3.0
code: err.statusCode,
@ -107,7 +106,7 @@ _private.ThemeErrorRenderer = function ThemeErrorRenderer(err, req, res, next) {
// It can be that something went wrong with the theme or otherwise loading handlebars
// This ensures that no matter what res.render will work here
// @TODO: split the error handler for assets, admin & theme to refactor this away
if (_.isEmpty(req.app.engines)) {
if (!req.app.engines || Object.keys(req.app.engines).length === 0) {
res._template = 'error';
req.app.engine('hbs', _private.createHbsEngine());
req.app.set('view engine', 'hbs');
@ -131,7 +130,7 @@ _private.ThemeErrorRenderer = function ThemeErrorRenderer(err, req, res, next) {
};
_private.HTMLErrorRenderer = function HTMLErrorRender(err, req, res, next) { // eslint-disable-line no-unused-vars
var data = {
const data = {
message: err.message,
statusCode: err.statusCode,
errorDetails: err.errorDetails || []
@ -140,7 +139,7 @@ _private.HTMLErrorRenderer = function HTMLErrorRender(err, req, res, next) { //
// e.g. if you serve the admin /ghost and Ghost returns a 503 because it generates the urls at the moment.
// This ensures that no matter what res.render will work here
// @TODO: put to prepare error function?
if (_.isEmpty(req.app.engines)) {
if (!req.app.engines || req.app.engines.length === 0) {
res._template = 'error';
req.app.engine('hbs', _private.createHbsEngine());
req.app.set('view engine', 'hbs');

View file

@ -1,4 +1,4 @@
var api = require('../../api'),
const api = require('../../api'),
labs = require('../../services/labs'),
common = require('../../lib/common');

View file

@ -1,4 +1,4 @@
var ghostVersion = require('../../lib/ghost-version');
const ghostVersion = require('../../lib/ghost-version');
// ### GhostLocals Middleware
// Expose the standard locals that every request will need to have available

View file

@ -1,8 +1,7 @@
var labsUtil = require('../../services/labs'),
common = require('../../lib/common'),
labs;
const labsUtil = require('../../services/labs'),
common = require('../../lib/common');
labs = {
const labs = {
subscribers: function subscribers(req, res, next) {
if (labsUtil.isSet('subscribers') === true) {
return next();

View file

@ -1,4 +1,4 @@
var uuid = require('uuid'),
const uuid = require('uuid'),
common = require('../../lib/common');
/**
@ -6,7 +6,7 @@ var uuid = require('uuid'),
* - move middleware to ignition?
*/
module.exports = function logRequest(req, res, next) {
var startTime = Date.now(),
const startTime = Date.now(),
requestId = req.get('X-Request-ID') || uuid.v1();
function logResponse() {

View file

@ -1,4 +1,4 @@
var config = require('../../config'),
const config = require('../../config'),
common = require('../../lib/common'),
urlService = require('../../services/url');

View file

@ -6,7 +6,7 @@
// Uncapitalise changes case to lowercase
// @TODO optimise this to reduce the number of redirects required to get to a pretty URL
// @TODO move this to being used by routers?
var slashes = require('connect-slashes'),
const slashes = require('connect-slashes'),
config = require('../../config');
module.exports = [

View file

@ -1,15 +1,15 @@
var fs = require('fs-extra'),
const fs = require('fs-extra'),
path = require('path'),
crypto = require('crypto'),
config = require('../../config'),
imageLib = require('../../lib/image'),
storage = require('../../adapters/storage'),
urlService = require('../../services/url'),
settingsCache = require('../../services/settings/cache'),
buildContentResponse,
content;
settingsCache = require('../../services/settings/cache');
buildContentResponse = function buildContentResponse(ext, buf) {
let content;
const buildContentResponse = function buildContentResponse(ext, buf) {
content = {
headers: {
'Content-Type': 'image/' + ext,
@ -26,7 +26,7 @@ buildContentResponse = function buildContentResponse(ext, buf) {
// ### serveFavicon Middleware
// Handles requests to favicon.png and favicon.ico
function serveFavicon() {
var iconType,
let iconType,
filePath;
return function serveFavicon(req, res, next) {
@ -39,8 +39,8 @@ function serveFavicon() {
// in this case we don't use path rewrite, that's why we have to make it manually
filePath = imageLib.blogIcon.getIconPath();
var originalExtension = path.extname(filePath).toLowerCase(),
requestedExtension = path.extname(req.path).toLowerCase();
let originalExtension = path.extname(filePath).toLowerCase();
const requestedExtension = path.extname(req.path).toLowerCase();
// CASE: custom favicon exists, load it from local file storage
if (settingsCache.get('icon')) {

View file

@ -1,4 +1,4 @@
var crypto = require('crypto'),
const crypto = require('crypto'),
fs = require('fs-extra'),
path = require('path'),
config = require('../../config'),
@ -7,14 +7,12 @@ var crypto = require('crypto'),
// ### servePublicFile Middleware
// Handles requests to robots.txt and favicon.ico (and caches them)
function servePublicFile(file, type, maxAge) {
var content,
publicFilePath = config.get('paths').publicFilePath,
filePath,
let content;
const publicFilePath = config.get('paths').publicFilePath,
filePath = file.match(/^public/) ? path.join(publicFilePath, file.replace(/^public/, '')) : path.join(publicFilePath, file),
blogRegex = /(\{\{blog-url\}\})/g,
apiRegex = /(\{\{api-url\}\})/g;
filePath = file.match(/^public/) ? path.join(publicFilePath, file.replace(/^public/, '')) : path.join(publicFilePath, file);
return function servePublicFile(req, res, next) {
if (req.path === '/' + file) {
if (content) {

View file

@ -1,20 +1,19 @@
var _ = require('lodash'),
express = require('express'),
const express = require('express'),
path = require('path'),
config = require('../../config'),
constants = require('../../lib/constants'),
themeUtils = require('../../services/themes');
function isBlackListedFileType(file) {
var blackListedFileTypes = ['.hbs', '.md', '.json'],
const blackListedFileTypes = ['.hbs', '.md', '.json'],
ext = path.extname(file);
return _.includes(blackListedFileTypes, ext);
return blackListedFileTypes.includes(ext);
}
function isWhiteListedFile(file) {
var whiteListedFiles = ['manifest.json'],
const whiteListedFiles = ['manifest.json'],
base = path.basename(file);
return _.includes(whiteListedFiles, base);
return whiteListedFiles.includes(base);
}
function forwardToExpressStatic(req, res, next) {
@ -22,7 +21,7 @@ function forwardToExpressStatic(req, res, next) {
return next();
}
var configMaxAge = config.get('caching:theme:maxAge');
const configMaxAge = config.get('caching:theme:maxAge');
express.static(themeUtils.getActive().path,
{maxAge: (configMaxAge || configMaxAge === 0) ? configMaxAge : constants.ONE_YEAR_MS}

View file

@ -12,16 +12,17 @@
// req.baseUrl = /blog
// req.path = /ghost/signin/
var urlService = require('../../services/url'),
const urlService = require('../../services/url'),
common = require('../../lib/common'),
localUtils = require('../utils'),
uncapitalise;
localUtils = require('../utils');
uncapitalise = function uncapitalise(req, res, next) {
var pathToTest = (req.baseUrl ? req.baseUrl : '') + req.path,
isSignupOrReset = pathToTest.match(/^(.*\/ghost\/(signup|reset)\/)/i),
isAPI = pathToTest.match(/^(.*\/ghost\/api\/v[\d\.]+\/.*?\/)/i),
redirectPath, decodedURI;
const uncapitalise = function uncapitalise(req, res, next) {
let pathToTest = (req.baseUrl ? req.baseUrl : '') + req.path,
redirectPath,
decodedURI;
const isSignupOrReset = pathToTest.match(/^(.*\/ghost\/(signup|reset)\/)/i),
isAPI = pathToTest.match(/^(.*\/ghost\/api\/v[\d\.]+\/.*?\/)/i);
if (isSignupOrReset) {
pathToTest = isSignupOrReset[1];

View file

@ -1,15 +1,14 @@
var url = require('url'),
const url = require('url'),
path = require('path'),
debug = require('ghost-ignition').debug('url-redirects'),
urlService = require('../../services/url'),
urlRedirects,
_private = {};
_private.redirectUrl = function redirectUrl(options) {
var redirectTo = options.redirectTo,
pathname = options.path,
const redirectTo = options.redirectTo,
query = options.query,
parts = url.parse(redirectTo);
let pathname = options.path;
// CASE: ensure we always add a trailing slash to reduce the number of redirects
// e.g. you are redirected from example.com/ghost to admin.example.com/ghost and Ghost would detect a missing slash and redirect you to /ghost/
@ -22,13 +21,13 @@ _private.redirectUrl = function redirectUrl(options) {
protocol: parts.protocol,
hostname: parts.hostname,
port: parts.port,
pathname: pathname,
query: query
pathname,
query
});
};
_private.getAdminRedirectUrl = function getAdminRedirectUrl(options) {
var blogHostWithProtocol = urlService.utils.urlFor('home', true),
const blogHostWithProtocol = urlService.utils.urlFor('home', true),
adminHostWithProtocol = urlService.utils.urlFor('admin', true),
adminHostWithoutProtocol = adminHostWithProtocol.replace(/(^\w+:|^)\/\//, ''),
blogHostWithoutProtocol = blogHostWithProtocol.replace(/(^\w+:|^)\/\//, ''),
@ -67,7 +66,7 @@ _private.getAdminRedirectUrl = function getAdminRedirectUrl(options) {
};
_private.getBlogRedirectUrl = function getBlogRedirectUrl(options) {
var blogHostWithProtocol = urlService.utils.urlFor('home', true),
const blogHostWithProtocol = urlService.utils.urlFor('home', true),
requestedHost = options.requestedHost,
requestedUrl = options.requestedUrl,
queryParameters = options.queryParameters,
@ -93,8 +92,8 @@ _private.getBlogRedirectUrl = function getBlogRedirectUrl(options) {
* 1. required SSL redirects
* 2. redirect to the correct admin url
*/
urlRedirects = function urlRedirects(req, res, next) {
var redirectFn = res.isAdmin ? _private.getAdminRedirectUrl : _private.getBlogRedirectUrl,
const urlRedirects = function urlRedirects(req, res, next) {
const redirectFn = res.isAdmin ? _private.getAdminRedirectUrl : _private.getBlogRedirectUrl,
redirectUrl = redirectFn({
requestedHost: req.get('host'),
requestedUrl: url.parse(req.originalUrl || req.url).pathname,