Ghost/core/server/middleware/middleware.js

202 lines
6.7 KiB
JavaScript
Raw Normal View History

// # Custom Middleware
// The following custom middleware functions are all unit testable, and have accompanying unit tests in
// middleware_spec.js
2014-02-05 12:40:30 +04:00
var _ = require('lodash'),
csrf = require('csurf'),
express = require('express'),
busboy = require('./ghost-busboy'),
config = require('../config'),
path = require('path'),
api = require('../api'),
expressServer,
ONE_HOUR_MS = 60 * 60 * 1000,
ONE_YEAR_MS = 365 * 24 * ONE_HOUR_MS;
function isBlackListedFileType(file) {
var blackListedFileTypes = ['.hbs', '.md', '.json'],
ext = path.extname(file);
return _.contains(blackListedFileTypes, ext);
}
function cacheServer(server) {
expressServer = server;
}
var middleware = {
// ### Authenticate Middleware
// authentication has to be done for /ghost/* routes with
// exceptions for signin, signout, signup, forgotten, reset only
// api and frontend use different authentication mechanisms atm
authenticate: function (req, res, next) {
var noAuthNeeded = [
'/ghost/signin/', '/ghost/signout/', '/ghost/signup/',
'/ghost/forgotten/', '/ghost/reset/', '/ghost/ember/',
'/ghost/ember/signin'
],
subPath;
// SubPath is the url path starting after any default subdirectories
// it is stripped of anything after the two levels `/ghost/.*?/` as the reset link has an argument
subPath = req.path.substring(config().paths.subdir.length);
/*jslint regexp:true, unparam:true*/
subPath = subPath.replace(/^(\/.*?\/.*?\/)(.*)?/, function (match, a) {
return a;
});
if (res.isAdmin) {
if (subPath.indexOf('/ghost/api/') === 0) {
return middleware.authAPI(req, res, next);
}
if (noAuthNeeded.indexOf(subPath) < 0) {
return middleware.auth(req, res, next);
}
}
next();
},
// ### Auth Middleware
// Authenticate a request by redirecting to login if not logged in.
// We strip /ghost/ out of the redirect parameter for neatness
auth: function (req, res, next) {
if (!req.session.user) {
var subPath = req.path.substring(config().paths.subdir.length),
reqPath = subPath.replace(/^\/ghost\/?/gi, ''),
redirect = '',
msg;
return api.notifications.browse().then(function (notifications) {
if (reqPath !== '') {
msg = {
type: 'error',
message: 'Please Sign In',
status: 'passive'
};
// let's only add the notification once
if (!_.contains(_.pluck(notifications, 'id'), 'failedauth')) {
api.notifications.add({ notifications: [msg] });
}
redirect = '?r=' + encodeURIComponent(reqPath);
}
if (subPath.indexOf('/ember') > -1) {
return res.redirect(config().paths.subdir + '/ghost/ember/signin');
}
Improve bootstrap flow of a Ghost application addresses #1789, #1364 - Moves ./core/server/loader -> ./core/bootstrap. The bootstrap file is only accessed once during startup, and it’s sole job is to ensure a config.js file exists (creating one if it doesn’t) and then validates the contents of the config file. Since this is directly related to the initializing the application is is appropriate to have it in the ./core folder, named bootstrap as that is what it does. This also improves the dependency graph, as now the bootstrap file require’s the ./core/server/config module and is responsible for passing in the validated config file. Whereas before we had ./core/server/config require’ing ./core/server/loader and running its init code and then passing that value back to itself, the flow is now more straight forward of ./core/bootstrap handling initialization and then instatiation of config module - Merges ./core/server/config/paths into ./core/server/config This flow was always confusing me to that some config options were on the config object, and some were on the paths object. This change now incorporates all of the variables previously defined in config/paths directly into the config module, and in extension, the config.js file. This means that you now have the option of deciding at startup where the content directory for ghost should reside. - broke out loader tests in config_spec to bootstrap_spec - updated all relevant files to now use config().paths - moved urlFor and urlForPost function into ./server/config/url.js
2014-01-05 10:40:53 +04:00
return res.redirect(config().paths.subdir + '/ghost/signin/' + redirect);
});
}
next();
},
// ## AuthApi Middleware
// Authenticate a request to the API by responding with a 401 and json error details
authAPI: function (req, res, next) {
if (!req.session.user) {
res.json(401, { error: 'Please sign in' });
return;
}
next();
},
// Check if we're logged in, and if so, redirect people back to dashboard
// Login and signup forms in particular
redirectToDashboard: function (req, res, next) {
if (req.session && req.session.user) {
Improve bootstrap flow of a Ghost application addresses #1789, #1364 - Moves ./core/server/loader -> ./core/bootstrap. The bootstrap file is only accessed once during startup, and it’s sole job is to ensure a config.js file exists (creating one if it doesn’t) and then validates the contents of the config file. Since this is directly related to the initializing the application is is appropriate to have it in the ./core folder, named bootstrap as that is what it does. This also improves the dependency graph, as now the bootstrap file require’s the ./core/server/config module and is responsible for passing in the validated config file. Whereas before we had ./core/server/config require’ing ./core/server/loader and running its init code and then passing that value back to itself, the flow is now more straight forward of ./core/bootstrap handling initialization and then instatiation of config module - Merges ./core/server/config/paths into ./core/server/config This flow was always confusing me to that some config options were on the config object, and some were on the paths object. This change now incorporates all of the variables previously defined in config/paths directly into the config module, and in extension, the config.js file. This means that you now have the option of deciding at startup where the content directory for ghost should reside. - broke out loader tests in config_spec to bootstrap_spec - updated all relevant files to now use config().paths - moved urlFor and urlForPost function into ./server/config/url.js
2014-01-05 10:40:53 +04:00
return res.redirect(config().paths.subdir + '/ghost/');
}
next();
},
// While we're here, let's clean up on aisle 5
// That being ghost.notifications, and let's remove the passives from there
// plus the local messages, as they have already been added at this point
// otherwise they'd appear one too many times
// ToDo: Remove once ember handles passive notifications.
cleanNotifications: function (req, res, next) {
/*jslint unparam:true*/
api.notifications.browse().then(function (notifications) {
_.each(notifications.notifications, function (notification) {
if (notification.status === 'passive') {
api.notifications.destroy(notification);
}
});
next();
});
},
// ### CacheControl Middleware
// provide sensible cache control headers
cacheControl: function (options) {
/*jslint unparam:true*/
var profiles = {
'public': 'public, max-age=0',
'private': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
},
output;
if (_.isString(options) && profiles.hasOwnProperty(options)) {
output = profiles[options];
}
return function cacheControlHeaders(req, res, next) {
if (output) {
res.set({'Cache-Control': output});
}
next();
};
},
// ### whenEnabled Middleware
// Selectively use middleware
// From https://github.com/senchalabs/connect/issues/676#issuecomment-9569658
whenEnabled: function (setting, fn) {
return function settingEnabled(req, res, next) {
// Set from server/middleware/index.js for now
if (expressServer.enabled(setting)) {
fn(req, res, next);
} else {
next();
}
};
},
staticTheme: function () {
return function blackListStatic(req, res, next) {
if (isBlackListedFileType(req.url)) {
return next();
}
return middleware.forwardToExpressStatic(req, res, next);
};
},
// to allow unit testing
forwardToExpressStatic: function (req, res, next) {
api.settings.read({context: {internal: true}, key: 'activeTheme'}).then(function (response) {
var activeTheme = response.settings[0];
express['static'](path.join(config().paths.themePath, activeTheme.value), {maxAge: ONE_YEAR_MS})(req, res, next);
});
},
conditionalCSRF: function (req, res, next) {
// CSRF is needed for admin only
if (res.isAdmin) {
csrf()(req, res, next);
return;
}
next();
},
busboy: busboy
};
module.exports = middleware;
module.exports.cacheServer = cacheServer;