Ghost/core/server/apps/private-blogging/lib/middleware.js

143 lines
5.1 KiB
JavaScript
Raw Normal View History

var _ = require('lodash'),
fs = require('fs'),
🎨 configurable logging with bunyan (#7431) - 🛠 add bunyan and prettyjson, remove morgan - ✨ add logging module - GhostLogger class that handles setup of bunyan - PrettyStream for stdout - ✨ config for logging - @TODO: testing level fatal? - ✨ log each request via GhostLogger (express middleware) - @TODO: add errors to output - 🔥 remove errors.updateActiveTheme - we can read the value from config - 🔥 remove 15 helper functions in core/server/errors/index.js - all these functions get replaced by modules: 1. logging 2. error middleware handling for html/json 3. error creation (which will be part of PR #7477) - ✨ add express error handler for html/json - one true error handler for express responses - contains still some TODO's, but they are not high priority for first implementation/integration - this middleware only takes responsibility of either rendering html responses or return json error responses - 🎨 use new express error handler in middleware/index - 404 and 500 handling - 🎨 return error instead of error message in permissions/index.js - the rule for error handling should be: if you call a unit, this unit should return a custom Ghost error - 🎨 wrap serve static module - rule: if you call a module/unit, you should always wrap this error - it's always the same rule - so the caller never has to worry about what comes back - it's always a clear error instance - in this case: we return our notfounderror if serve static does not find the resource - this avoid having checks everywhere - 🎨 replace usages of errors/index.js functions and adapt tests - use logging.error, logging.warn - make tests green - remove some usages of logging and throwing api errors -> because when a request is involved, logging happens automatically - 🐛 return errorDetails to Ghost-Admin - errorDetails is used for Theme error handling - 🎨 use 500er error for theme is missing error in theme-handler - 🎨 extend file rotation to 1w
2016-10-04 18:33:43 +03:00
session = require('cookie-session'),
crypto = require('crypto'),
path = require('path'),
Promise = require('bluebird'),
🎨 configurable logging with bunyan (#7431) - 🛠 add bunyan and prettyjson, remove morgan - ✨ add logging module - GhostLogger class that handles setup of bunyan - PrettyStream for stdout - ✨ config for logging - @TODO: testing level fatal? - ✨ log each request via GhostLogger (express middleware) - @TODO: add errors to output - 🔥 remove errors.updateActiveTheme - we can read the value from config - 🔥 remove 15 helper functions in core/server/errors/index.js - all these functions get replaced by modules: 1. logging 2. error middleware handling for html/json 3. error creation (which will be part of PR #7477) - ✨ add express error handler for html/json - one true error handler for express responses - contains still some TODO's, but they are not high priority for first implementation/integration - this middleware only takes responsibility of either rendering html responses or return json error responses - 🎨 use new express error handler in middleware/index - 404 and 500 handling - 🎨 return error instead of error message in permissions/index.js - the rule for error handling should be: if you call a unit, this unit should return a custom Ghost error - 🎨 wrap serve static module - rule: if you call a module/unit, you should always wrap this error - it's always the same rule - so the caller never has to worry about what comes back - it's always a clear error instance - in this case: we return our notfounderror if serve static does not find the resource - this avoid having checks everywhere - 🎨 replace usages of errors/index.js functions and adapt tests - use logging.error, logging.warn - make tests green - remove some usages of logging and throwing api errors -> because when a request is involved, logging happens automatically - 🐛 return errorDetails to Ghost-Admin - errorDetails is used for Theme error handling - 🎨 use 500er error for theme is missing error in theme-handler - 🎨 extend file rotation to 1w
2016-10-04 18:33:43 +03:00
config = require('../../../config'),
api = require('../../../api'),
errors = require('../../../errors'),
utils = require('../../../utils'),
i18n = require('../../../i18n'),
privateRoute = '/' + config.get('routeKeywords').private + '/',
privateBlogging;
function verifySessionHash(salt, hash) {
if (!salt || !hash) {
return Promise.resolve(false);
}
return api.settings.read({context: {internal: true}, key: 'password'}).then(function then(response) {
var hasher = crypto.createHash('sha256');
hasher.update(response.settings[0].value + salt, 'utf8');
return hasher.digest('hex') === hash;
});
}
privateBlogging = {
checkIsPrivate: function checkIsPrivate(req, res, next) {
return api.settings.read({context: {internal: true}, key: 'is_private'}).then(function then(response) {
var pass = response.settings[0];
if (_.isEmpty(pass.value) || pass.value === 'false') {
res.isPrivateBlog = false;
return next();
}
res.isPrivateBlog = true;
return session({
maxAge: utils.ONE_MONTH_MS,
signed: false
})(req, res, next);
});
},
filterPrivateRoutes: function filterPrivateRoutes(req, res, next) {
if (res.isAdmin || !res.isPrivateBlog || req.url.lastIndexOf(privateRoute, 0) === 0) {
return next();
}
// take care of rss and sitemap 404s
if (req.path.lastIndexOf('/rss/', 0) === 0 ||
req.path.lastIndexOf('/rss/') === req.url.length - 5 ||
(req.path.lastIndexOf('/sitemap', 0) === 0 && req.path.lastIndexOf('.xml') === req.path.length - 4)) {
return next(new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')}));
} else if (req.url.lastIndexOf('/robots.txt', 0) === 0) {
fs.readFile(path.resolve(__dirname, '../', 'robots.txt'), function readFile(err, buf) {
if (err) {
return next(err);
}
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Length': buf.length,
'Cache-Control': 'public, max-age=' + config.get('caching:robotstxt:maxAge')
});
res.end(buf);
});
} else {
return privateBlogging.authenticatePrivateSession(req, res, next);
}
},
authenticatePrivateSession: function authenticatePrivateSession(req, res, next) {
var hash = req.session.token || '',
salt = req.session.salt || '',
url;
return verifySessionHash(salt, hash).then(function then(isVerified) {
if (isVerified) {
return next();
} else {
url = utils.url.urlFor({relativeUrl: privateRoute});
url += req.url === '/' ? '' : '?r=' + encodeURIComponent(req.url);
return res.redirect(url);
}
});
},
// This is here so a call to /private/ after a session is verified will redirect to home;
isPrivateSessionAuth: function isPrivateSessionAuth(req, res, next) {
if (!res.isPrivateBlog) {
return res.redirect(utils.url.urlFor('home', true));
}
var hash = req.session.token || '',
salt = req.session.salt || '';
return verifySessionHash(salt, hash).then(function then(isVerified) {
if (isVerified) {
// redirect to home if user is already authenticated
return res.redirect(utils.url.urlFor('home', true));
} else {
return next();
}
});
},
authenticateProtection: function authenticateProtection(req, res, next) {
// if errors have been generated from the previous call
if (res.error) {
return next();
}
var bodyPass = req.body.password;
return api.settings.read({context: {internal: true}, key: 'password'}).then(function then(response) {
var pass = response.settings[0],
hasher = crypto.createHash('sha256'),
salt = Date.now().toString(),
forward = req.query && req.query.r ? req.query.r : '/';
if (pass.value === bodyPass) {
hasher.update(bodyPass + salt, 'utf8');
req.session.token = hasher.digest('hex');
req.session.salt = salt;
return res.redirect(utils.url.urlFor({relativeUrl: decodeURIComponent(forward)}));
} else {
res.error = {
message: i18n.t('errors.middleware.privateblogging.wrongPassword')
};
return next();
}
});
}
};
module.exports = privateBlogging;