Merge pull request #5366 from ErisDS/anon-middleware

Ensure middleware functions are named
This commit is contained in:
Jason Williams 2015-06-03 16:26:56 -05:00
commit 8c0bc6cea5
14 changed files with 142 additions and 148 deletions

View File

@ -36,7 +36,7 @@ var _ = require('lodash'),
* Initialise the API - populate the settings cache
* @return {Promise(Settings)} Resolves to Settings Collection
*/
init = function () {
init = function init() {
return settings.updateSettingsCache();
};
@ -53,7 +53,7 @@ init = function () {
* @param {Object} result API method result
* @return {String} Resolves to header string
*/
cacheInvalidationHeader = function (req, result) {
cacheInvalidationHeader = function cacheInvalidationHeader(req, result) {
var parsedUrl = req._parsedUrl.pathname.replace(/^\/|\/$/g, '').split('/'),
method = req.method,
endpoint = parsedUrl[0],
@ -100,7 +100,7 @@ cacheInvalidationHeader = function (req, result) {
* @param {Object} result API method result
* @return {String} Resolves to header string
*/
locationHeader = function (req, result) {
locationHeader = function locationHeader(req, result) {
var apiRoot = config.urlFor('api'),
location,
newObject;
@ -138,8 +138,8 @@ locationHeader = function (req, result) {
* @see http://tools.ietf.org/html/rfc598
* @return {string}
*/
contentDispositionHeader = function () {
return dataExport.fileName().then(function (filename) {
contentDispositionHeader = function contentDispositionHeader() {
return dataExport.fileName().then(function then(filename) {
return 'Attachment; filename="' + filename + '"';
});
};
@ -152,7 +152,7 @@ contentDispositionHeader = function () {
* @param {Array} error
* @return {{errors: Array, statusCode: number}}
*/
formatHttpErrors = function (error) {
formatHttpErrors = function formatHttpErrors(error) {
var statusCode = 500,
errors = [];
@ -160,7 +160,7 @@ formatHttpErrors = function (error) {
error = [].concat(error);
}
_.each(error, function (errorItem) {
_.each(error, function each(errorItem) {
var errorContent = {};
// TODO: add logic to set the correct status code
@ -175,7 +175,7 @@ formatHttpErrors = function (error) {
return {errors: errors, statusCode: statusCode};
};
addHeaders = function (apiMethod, req, res, result) {
addHeaders = function addHeaders(apiMethod, req, res, result) {
var cacheInvalidation,
location,
contentDisposition;
@ -220,8 +220,8 @@ addHeaders = function (apiMethod, req, res, result) {
* @param {Function} apiMethod API method to call
* @return {Function} middleware format function to be called by the route when a matching request is made
*/
http = function (apiMethod) {
return function (req, res) {
http = function http(apiMethod) {
return function apiHandler(req, res) {
// We define 2 properties for using as arguments in API calls:
var object = req.body,
options = _.extend({}, req.files, req.query, req.params, {
@ -240,7 +240,7 @@ http = function (apiMethod) {
return apiMethod(object, options).tap(function onSuccess(response) {
// Add X-Cache-Invalidate, Location, and Content-Disposition headers
return addHeaders(apiMethod, req, res, response);
}).then(function (response) {
}).then(function then(response) {
// Send a properly formatting HTTP response containing the data with correct headers
res.json(response || {});
}).catch(function onError(error) {

View File

@ -9,12 +9,12 @@ adminControllers = {
// Route: index
// Path: /ghost/
// Method: GET
index: function (req, res) {
index: function index(req, res) {
/*jslint unparam:true*/
function renderIndex() {
return api.configuration.browse().then(function (data) {
var apiConfig = _.omit(data.configuration, function (value) {
return api.configuration.browse().then(function then(data) {
var apiConfig = _.omit(data.configuration, function omit(value) {
return _.contains(['environment', 'database', 'mail', 'version'], value.key);
});
@ -25,9 +25,9 @@ adminControllers = {
});
}
updateCheck().then(function () {
updateCheck().then(function then() {
return updateCheck.showUpdateNotification();
}).then(function (updateVersion) {
}).then(function then(updateVersion) {
if (!updateVersion) {
return;
}
@ -40,12 +40,12 @@ adminControllers = {
message: 'Ghost ' + updateVersion + ' is available! Hot Damn. <a href="http://support.ghost.org/how-to-upgrade/" target="_blank">Click here</a> to upgrade.'
};
return api.notifications.browse({context: {internal: true}}).then(function (results) {
return api.notifications.browse({context: {internal: true}}).then(function then(results) {
if (!_.some(results.notifications, {message: notification.message})) {
return api.notifications.add({notifications: [notification]}, {context: {internal: true}});
}
});
}).finally(function () {
}).finally(function noMatterWhat() {
renderIndex();
}).catch(errors.logError);
}

View File

@ -19,7 +19,7 @@ var _ = require('lodash'),
staticPostPermalink = routeMatch('/:slug/:edit?');
function getPostPage(options) {
return api.settings.read('postsPerPage').then(function (response) {
return api.settings.read('postsPerPage').then(function then(response) {
var postPP = response.settings[0],
postsPerPage = parseInt(postPP.value, 10);
@ -58,7 +58,12 @@ function formatResponse(post) {
}
function handleError(next) {
return function (err) {
return function handleError(err) {
// If we've thrown an error message of type: 'NotFound' then we found no path match.
if (err.errorType === 'NotFoundError') {
return next();
}
return next(err);
};
}
@ -100,7 +105,7 @@ function setResponseContext(req, res, data) {
// Add Request context parameter to the data object
// to be passed down to the templates
function setReqCtx(req, data) {
(Array.isArray(data) ? data : [data]).forEach(function (d) {
(Array.isArray(data) ? data : [data]).forEach(function forEach(d) {
d.secure = req.secure;
});
}
@ -115,7 +120,7 @@ function getActiveThemePaths() {
context: {
internal: true
}
}).then(function (response) {
}).then(function then(response) {
var activeTheme = response.settings[0],
paths = config.paths.availableThemes[activeTheme.value];
@ -130,8 +135,8 @@ function getActiveThemePaths() {
* Returns a function that takes the post to be rendered.
*/
function renderPost(req, res) {
return function (post) {
return getActiveThemePaths().then(function (paths) {
return function renderPost(post) {
return getActiveThemePaths().then(function then(paths) {
var view = template.getThemeViewForPost(paths, post),
response = formatResponse(post);
@ -176,7 +181,7 @@ function renderChannel(channelOpts) {
return res.redirect(createUrl());
}
return getPostPage(options).then(function (page) {
return getPostPage(options).then(function then(page) {
// If page is greater than number of pages we have, redirect to last page
if (pageParam > page.meta.pagination.pages) {
return res.redirect(createUrl(page.meta.pagination.pages));
@ -189,8 +194,8 @@ function renderChannel(channelOpts) {
setReqCtx(req, filter);
}
filters.doFilter('prePostsRender', page.posts, res.locals).then(function (posts) {
getActiveThemePaths().then(function (paths) {
filters.doFilter('prePostsRender', page.posts, res.locals).then(function then(posts) {
getActiveThemePaths().then(function then(paths) {
var view = 'index',
result,
extra = {};
@ -241,14 +246,14 @@ frontendControllers = {
filter: 'author',
slugTemplate: true
}),
preview: function (req, res, next) {
preview: function preview(req, res, next) {
var params = {
uuid: req.params.uuid,
status: 'all',
include: 'author,tags,fields'
};
api.posts.read(params).then(function (result) {
api.posts.read(params).then(function then(result) {
var post = result.posts[0];
if (!post) {
@ -263,21 +268,15 @@ frontendControllers = {
filters.doFilter('prePostsRender', post, res.locals)
.then(renderPost(req, res));
}).catch(function (err) {
if (err.errorType === 'NotFoundError') {
return next();
}
return handleError(next)(err);
});
}).catch(handleError(next));
},
single: function (req, res, next) {
single: function single(req, res, next) {
var postPath = req.path,
params,
usingStaticPermalink = false;
api.settings.read('permalinks').then(function (response) {
api.settings.read('permalinks').then(function then(response) {
var permalink = response.settings[0].value,
editFormat,
postLookup,
@ -314,7 +313,7 @@ frontendControllers = {
// Query database to find post
return api.posts.read(postLookup);
}).then(function (result) {
}).then(function then(result) {
var post = result.posts[0],
postUrl = (params.edit) ? postPath.replace(params.edit + '/', '') : postPath;
@ -358,21 +357,12 @@ frontendControllers = {
} else {
return next();
}
}).catch(function (err) {
// If we've thrown an error message
// of type: 'NotFound' then we found
// no path match.
if (err.errorType === 'NotFoundError') {
return next();
}
return handleError(next)(err);
});
}).catch(handleError(next));
},
rss: rss,
private: function (req, res) {
private: function private(req, res) {
var defaultPage = path.resolve(config.paths.adminViews, 'private.hbs');
return getActiveThemePaths().then(function (paths) {
return getActiveThemePaths().then(function then(paths) {
var data = {};
if (res.error) {
data.error = res.error;

View File

@ -27,7 +27,7 @@ function isAuthor(req) {
}
function handleError(next) {
return function (err) {
return function handleError(err) {
return next(err);
};
}
@ -82,8 +82,8 @@ function getBaseUrl(req, slugParam) {
function processUrls(html, siteUrl, itemUrl) {
var htmlContent = cheerio.load(html, {decodeEntities: false});
// convert relative resource urls to absolute
['href', 'src'].forEach(function (attributeName) {
htmlContent('[' + attributeName + ']').each(function (ix, el) {
['href', 'src'].forEach(function forEach(attributeName) {
htmlContent('[' + attributeName + ']').each(function each(ix, el) {
var baseUrl,
attributeValue,
parsed;
@ -127,7 +127,7 @@ function processUrls(html, siteUrl, itemUrl) {
return htmlContent;
}
getFeedXml = function (path, data) {
getFeedXml = function getFeedXml(path, data) {
var dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
if (!feedCache[path] || feedCache[path].hash !== dataHash) {
// We need to regenerate
@ -140,7 +140,7 @@ getFeedXml = function (path, data) {
return feedCache[path].xml;
};
generateFeed = function (data) {
generateFeed = function generateFeed(data) {
var feed = new RSS({
title: data.title,
description: data.description,
@ -154,7 +154,7 @@ generateFeed = function (data) {
}
});
data.results.posts.forEach(function (post) {
data.results.posts.forEach(function forEach(post) {
var itemUrl = config.urlFor('post', {post: post, permalinks: data.permalinks, secure: data.secure}, true),
htmlContent = processUrls(post.html, data.siteUrl, itemUrl),
item = {
@ -196,12 +196,12 @@ generateFeed = function (data) {
feed.item(item);
});
return filters.doFilter('rss.feed', feed).then(function (feed) {
return filters.doFilter('rss.feed', feed).then(function then(feed) {
return feed.xml();
});
};
generate = function (req, res, next) {
generate = function generate(req, res, next) {
// Initialize RSS
var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1,
slugParam = req.params.slug,
@ -213,7 +213,7 @@ generate = function (req, res, next) {
return res.redirect(baseUrl);
}
return getData(options).then(function (data) {
return getData(options).then(function then(data) {
var maxPage = data.results.meta.pagination.pages;
// If page is greater than number of pages we have, redirect to last page
@ -226,7 +226,7 @@ generate = function (req, res, next) {
data.feedUrl = config.urlFor({relativeUrl: baseUrl, secure: req.secure}, true);
data.secure = req.secure;
return getFeedXml(req.originalUrl, data).then(function (feedXml) {
return getFeedXml(req.originalUrl, data).then(function then(feedXml) {
res.set('Content-Type', 'text/xml; charset=UTF-8');
res.send(feedXml);
});

View File

@ -3,20 +3,20 @@ var _ = require('lodash'),
sitemap = require('./index');
// Responsible for handling requests for sitemap files
module.exports = function (blogApp) {
module.exports = function handler(blogApp) {
var resourceTypes = ['posts', 'authors', 'tags', 'pages'],
verifyResourceType = function (req, res, next) {
verifyResourceType = function verifyResourceType(req, res, next) {
if (!_.contains(resourceTypes, req.params.resource)) {
return res.sendStatus(404);
}
next();
},
getResourceSiteMapXml = function (type, page) {
getResourceSiteMapXml = function getResourceSiteMapXml(type, page) {
return sitemap.getSiteMapXml(type, page);
};
blogApp.get('/sitemap.xml', function (req, res) {
blogApp.get('/sitemap.xml', function sitemapXML(req, res) {
res.set({
'Cache-Control': 'public, max-age=' + utils.ONE_HOUR_S,
'Content-Type': 'text/xml'
@ -24,7 +24,7 @@ module.exports = function (blogApp) {
res.send(sitemap.getIndexXml());
});
blogApp.get('/sitemap-:resource.xml', verifyResourceType, function (req, res) {
blogApp.get('/sitemap-:resource.xml', verifyResourceType, function sitemapResourceXML(req, res) {
var type = req.params.resource,
page = 1,
siteMapXml = getResourceSiteMapXml(type, page);

View File

@ -14,10 +14,10 @@ var passport = require('passport'),
* Use of the client password strategy is implemented to support ember-simple-auth.
*/
passport.use(new ClientPasswordStrategy(
function (clientId, clientSecret, done) {
function strategy(clientId, clientSecret, done) {
models.Client.forge({slug: clientId})
.fetch()
.then(function (model) {
.then(function then(model) {
if (model) {
var client = model.toJSON();
if (client.secret === clientSecret) {
@ -38,16 +38,16 @@ passport.use(new ClientPasswordStrategy(
* the authorizing user.
*/
passport.use(new BearerStrategy(
function (accessToken, done) {
function strategy(accessToken, done) {
models.Accesstoken.forge({token: accessToken})
.fetch()
.then(function (model) {
.then(function then(model) {
if (model) {
var token = model.toJSON();
if (token.expires > Date.now()) {
models.User.forge({id: token.user_id})
.fetch()
.then(function (model) {
.then(function then(model) {
if (model) {
var user = model.toJSON(),
info = {scope: '*'};

View File

@ -9,7 +9,7 @@
var _ = require('lodash'),
cacheControl;
cacheControl = function (options) {
cacheControl = function cacheControl(options) {
/*jslint unparam:true*/
var profiles = {
public: 'public, max-age=0',

View File

@ -22,7 +22,7 @@ function ghostBusBoy(req, res, next) {
req.files = req.files || {};
req.body = req.body || {};
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
busboy.on('file', function onFile(fieldname, file, filename, encoding, mimetype) {
var filePath,
tmpFileName,
md5 = crypto.createHash('md5');
@ -39,7 +39,7 @@ function ghostBusBoy(req, res, next) {
filePath = path.join(tmpDir, tmpFileName || 'temp.tmp');
file.on('end', function () {
file.on('end', function end() {
req.files[fieldname] = {
type: mimetype,
encoding: encoding,
@ -48,29 +48,29 @@ function ghostBusBoy(req, res, next) {
};
});
file.on('error', function (error) {
file.on('error', function onError(error) {
console.log('Error', 'Something went wrong uploading the file', error);
});
stream = fs.createWriteStream(filePath);
stream.on('error', function (error) {
stream.on('error', function onError(error) {
console.log('Error', 'Something went wrong uploading the file', error);
});
file.pipe(stream);
});
busboy.on('error', function (error) {
busboy.on('error', function onError(error) {
console.log('Error', 'Something went wrong parsing the form', error);
res.status(500).send({code: 500, message: 'Could not parse upload completely.'});
});
busboy.on('field', function (fieldname, val) {
busboy.on('field', function onField(fieldname, val) {
req.body[fieldname] = val;
});
busboy.on('finish', function () {
busboy.on('finish', function onFinish() {
next();
});

View File

@ -55,12 +55,12 @@ function activateTheme(activeTheme) {
// set view engine
hbsOptions = {
partialsDir: [config.paths.helperTemplates],
onCompile: function (exhbs, source) {
onCompile: function onCompile(exhbs, source) {
return exhbs.handlebars.compile(source, {preventIndent: true});
}
};
fs.stat(themePartials, function (err, stats) {
fs.stat(themePartials, function stat(err, stats) {
// Check that the theme has a partials directory before trying to use it
if (!err && stats && stats.isDirectory()) {
hbsOptions.partialsDir.push(themePartials);
@ -111,7 +111,7 @@ function configHbsForContext(req, res, next) {
// activates that theme's views with the hbs templating engine if it
// is not yet activated.
function updateActiveTheme(req, res, next) {
api.settings.read({context: {internal: true}, key: 'activeTheme'}).then(function (response) {
api.settings.read({context: {internal: true}, key: 'activeTheme'}).then(function then(response) {
var activeTheme = response.settings[0];
// Check if the theme changed
@ -136,7 +136,7 @@ function updateActiveTheme(req, res, next) {
}
}
next();
}).catch(function (err) {
}).catch(function handleError(err) {
// Trying to start up without the active theme present, setup a simple hbs instance
// and render an error page straight away.
blogApp.engine('hbs', hbs.express3());
@ -148,12 +148,12 @@ function updateActiveTheme(req, res, next) {
function redirectToSetup(req, res, next) {
/*jslint unparam:true*/
api.authentication.isSetup().then(function (exists) {
api.authentication.isSetup().then(function then(exists) {
if (!exists.setup[0].status && !req.path.match(/\/setup\//)) {
return res.redirect(config.paths.subdir + '/ghost/setup/');
}
next();
}).catch(function (err) {
}).catch(function handleError(err) {
return next(new Error(err));
});
}
@ -194,7 +194,7 @@ function serveSharedFile(file, type, maxAge) {
res.writeHead(200, content.headers);
res.end(content.body);
} else {
fs.readFile(filePath, function (err, buf) {
fs.readFile(filePath, function readFile(err, buf) {
if (err) {
return next(err);
}
@ -220,7 +220,7 @@ function serveSharedFile(file, type, maxAge) {
};
}
setupMiddleware = function (blogAppInstance, adminApp) {
setupMiddleware = function setupMiddleware(blogAppInstance, adminApp) {
var logging = config.logging,
corePath = config.paths.corePath,
oauthServer = oauth2orize.createServer();

View File

@ -54,7 +54,7 @@ function sslForbiddenOrRedirect(opt) {
isForbidden: (forceAdminSSL && forceAdminSSL.redirect !== undefined && !forceAdminSSL.redirect),
// Append the request path to the base configuration path, trimming out a double "//"
redirectPathname: function () {
redirectPathname: function redirectPathname() {
var pathname = baseUrl.path;
if (reqUrl[0] === '/' && pathname[pathname.length - 1] === '/') {
pathname += reqUrl.slice(1);
@ -63,7 +63,7 @@ function sslForbiddenOrRedirect(opt) {
}
return pathname;
},
redirectUrl: function (query) {
redirectUrl: function redirectUrl(query) {
return url.format({
protocol: 'https:',
hostname: baseUrl.hostname,
@ -82,7 +82,7 @@ function verifySessionHash(salt, hash) {
return Promise.resolve(false);
}
return api.settings.read({context: {internal: true}, key: 'password'}).then(function (response) {
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');
@ -97,7 +97,7 @@ 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) {
authenticate: function authenticate(req, res, next) {
var path,
subPath;
@ -105,14 +105,14 @@ middleware = {
// it is stripped of anything after the two levels `/ghost/.*?/` as the reset link has an argument
path = req.path;
/*jslint regexp:true, unparam:true*/
subPath = path.replace(/^(\/.*?\/.*?\/)(.*)?/, function (match, a) {
subPath = path.replace(/^(\/.*?\/.*?\/)(.*)?/, function replace(match, a) {
return a;
});
if (subPath.indexOf('/ghost/api/') === 0
&& path.indexOf('/ghost/api/v0.1/authentication/') !== 0) {
return passport.authenticate('bearer', {session: false, failWithError: true},
function (err, user, info) {
function authenticate(err, user, info) {
if (err) {
return next(err); // will generate a 500 error
}
@ -139,7 +139,7 @@ middleware = {
// ### whenEnabled Middleware
// Selectively use middleware
// From https://github.com/senchalabs/connect/issues/676#issuecomment-9569658
whenEnabled: function (setting, fn) {
whenEnabled: function whenEnabled(setting, fn) {
return function settingEnabled(req, res, next) {
// Set from server/middleware/index.js for now
if (blogApp.enabled(setting)) {
@ -150,7 +150,7 @@ middleware = {
};
},
staticTheme: function () {
staticTheme: function staticTheme() {
return function blackListStatic(req, res, next) {
if (isBlackListedFileType(req.url)) {
return next();
@ -161,8 +161,8 @@ middleware = {
},
// to allow unit testing
forwardToExpressStatic: function (req, res, next) {
api.settings.read({context: {internal: true}, key: 'activeTheme'}).then(function (response) {
forwardToExpressStatic: function forwardToExpressStatic(req, res, next) {
api.settings.read({context: {internal: true}, key: 'activeTheme'}).then(function then(response) {
var activeTheme = response.settings[0];
express['static'](path.join(config.paths.themePath, activeTheme.value), {maxAge: utils.ONE_YEAR_MS})(req, res, next);
@ -171,7 +171,7 @@ middleware = {
// Check to see if we should use SSL
// and redirect if needed
checkSSL: function (req, res, next) {
checkSSL: function checkSSL(req, res, next) {
if (isSSLrequired(res.isAdmin, config.url, config.forceAdminSSL)) {
if (!req.secure) {
var response = sslForbiddenOrRedirect({
@ -191,8 +191,8 @@ middleware = {
next();
},
checkIsPrivate: function (req, res, next) {
return api.settings.read({context: {internal: true}, key: 'isPrivate'}).then(function (response) {
checkIsPrivate: function checkIsPrivate(req, res, next) {
return api.settings.read({context: {internal: true}, key: 'isPrivate'}).then(function then(response) {
var pass = response.settings[0];
if (_.isEmpty(pass.value) || pass.value === 'false') {
@ -209,7 +209,7 @@ middleware = {
});
},
filterPrivateRoutes: function (req, res, next) {
filterPrivateRoutes: function filterPrivateRoutes(req, res, next) {
if (res.isAdmin || !res.isPrivateBlog || req.url.lastIndexOf('/private/', 0) === 0) {
return next();
}
@ -218,7 +218,7 @@ middleware = {
if (req.url.lastIndexOf('/rss', 0) === 0 || req.url.lastIndexOf('/sitemap', 0) === 0) {
return errors.error404(req, res, next);
} else if (req.url.lastIndexOf('/robots.txt', 0) === 0) {
fs.readFile(path.join(config.paths.corePath, 'shared', 'private-robots.txt'), function (err, buf) {
fs.readFile(path.join(config.paths.corePath, 'shared', 'private-robots.txt'), function readFile(err, buf) {
if (err) {
return next(err);
}
@ -234,12 +234,12 @@ middleware = {
}
},
authenticatePrivateSession: function (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 (isVerified) {
return verifySessionHash(salt, hash).then(function then(isVerified) {
if (isVerified) {
return next();
} else {
@ -251,7 +251,7 @@ middleware = {
},
// This is here so a call to /private/ after a session is verified will redirect to home;
isPrivateSessionAuth: function (req, res, next) {
isPrivateSessionAuth: function isPrivateSessionAuth(req, res, next) {
if (!res.isPrivateBlog) {
return res.redirect(config.urlFor('home', true));
}
@ -259,7 +259,7 @@ middleware = {
var hash = req.session.token || '',
salt = req.session.salt || '';
return verifySessionHash(salt, hash).then(function (isVerified) {
return verifySessionHash(salt, hash).then(function then(isVerified) {
if (isVerified) {
// redirect to home if user is already authenticated
return res.redirect(config.urlFor('home', true));
@ -269,7 +269,7 @@ middleware = {
});
},
authenticateProtection: function (req, res, next) {
authenticateProtection: function authenticateProtection(req, res, next) {
// if errors have been generated from the previous call
if (res.error) {
return next();
@ -277,7 +277,7 @@ middleware = {
var bodyPass = req.body.password;
return api.settings.read({context: {internal: true}, key: 'password'}).then(function (response) {
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(),

View File

@ -7,7 +7,7 @@ var oauth2orize = require('oauth2orize'),
oauth = {
init: function (oauthServer, resetSpamCounter) {
init: function init(oauthServer, resetSpamCounter) {
// remove all expired accesstokens on startup
models.Accesstoken.destroyAllExpired();
@ -18,31 +18,35 @@ oauth = {
// `client`, which is exchanging the user's name and password from the
// authorization request for verification. If these values are validated, the
// application issues an access token on behalf of the user who authorized the code.
oauthServer.exchange(oauth2orize.exchange.password(function (client, username, password, scope, done) {
oauthServer.exchange(oauth2orize.exchange.password(function exchange(client, username, password, scope, done) {
// Validate the client
models.Client.forge({slug: client.slug})
.fetch()
.then(function (client) {
.then(function then(client) {
if (!client) {
return done(new errors.NoPermissionError('Invalid client.'), false);
}
// Validate the user
return models.User.check({email: username, password: password}).then(function (user) {
return models.User.check({email: username, password: password}).then(function then(user) {
// Everything validated, return the access- and refreshtoken
var accessToken = utils.uid(256),
refreshToken = utils.uid(256),
accessExpires = Date.now() + utils.ONE_HOUR_MS,
refreshExpires = Date.now() + utils.ONE_WEEK_MS;
return models.Accesstoken.add({token: accessToken, user_id: user.id, client_id: client.id, expires: accessExpires}).then(function () {
return models.Refreshtoken.add({token: refreshToken, user_id: user.id, client_id: client.id, expires: refreshExpires});
}).then(function () {
return models.Accesstoken.add(
{token: accessToken, user_id: user.id, client_id: client.id, expires: accessExpires}
).then(function then() {
return models.Refreshtoken.add(
{token: refreshToken, user_id: user.id, client_id: client.id, expires: refreshExpires}
);
}).then(function then() {
resetSpamCounter(username);
return done(null, accessToken, refreshToken, {expires_in: utils.ONE_HOUR_S});
}).catch(function (error) {
}).catch(function handleError(error) {
return done(error, false);
});
}).catch(function (error) {
}).catch(function handleError(error) {
return done(error);
});
});
@ -52,10 +56,10 @@ oauth = {
// `client`, which is exchanging a `refreshToken` previously issued by the server
// for verification. If these values are validated, the application issues an
// access token on behalf of the user who authorized the code.
oauthServer.exchange(oauth2orize.exchange.refreshToken(function (client, refreshToken, scope, done) {
oauthServer.exchange(oauth2orize.exchange.refreshToken(function exchange(client, refreshToken, scope, done) {
models.Refreshtoken.forge({token: refreshToken})
.fetch()
.then(function (model) {
.then(function then(model) {
if (!model) {
return done(new errors.NoPermissionError('Invalid refresh token.'), false);
} else {
@ -70,11 +74,11 @@ oauth = {
user_id: token.user_id,
client_id: token.client_id,
expires: accessExpires
}).then(function () {
}).then(function then() {
return models.Refreshtoken.edit({expires: refreshExpires}, {id: token.id});
}).then(function () {
}).then(function then() {
return done(null, accessToken, {expires_in: utils.ONE_HOUR_S});
}).catch(function (error) {
}).catch(function handleError(error) {
return done(error, false);
});
} else {

View File

@ -17,7 +17,7 @@ var _ = require('lodash'),
spamPrevention = {
/*jslint unparam:true*/
// limit signin requests to ten failed requests per IP per hour
signin: function (req, res, next) {
signin: function signin(req, res, next) {
var currentTime = process.hrtime()[0],
remoteAddress = req.connection.remoteAddress,
deniedRateLimit = '',
@ -35,7 +35,7 @@ spamPrevention = {
}
// filter entries that are older than rateSigninPeriod
loginSecurity = _.filter(loginSecurity, function (logTime) {
loginSecurity = _.filter(loginSecurity, function filter(logTime) {
return (logTime.time + rateSigninPeriod > currentTime);
});
@ -56,7 +56,7 @@ spamPrevention = {
// limit forgotten password requests to five requests per IP per hour for different email addresses
// limit forgotten password requests to five requests per email address
forgotten: function (req, res, next) {
forgotten: function forgotten(req, res, next) {
var currentTime = process.hrtime()[0],
remoteAddress = req.connection.remoteAddress,
rateForgottenPeriod = config.rateForgottenPeriod || 3600,
@ -66,7 +66,7 @@ spamPrevention = {
deniedRateLimit = '',
deniedEmailRateLimit = '',
message = 'Too many attempts.',
index = _.findIndex(forgottenSecurity, function (logTime) {
index = _.findIndex(forgottenSecurity, function findIndex(logTime) {
return (logTime.ip === remoteAddress && logTime.email === email);
});
@ -81,7 +81,7 @@ spamPrevention = {
}
// filter entries that are older than rateForgottenPeriod
forgottenSecurity = _.filter(forgottenSecurity, function (logTime) {
forgottenSecurity = _.filter(forgottenSecurity, function filter(logTime) {
return (logTime.time + rateForgottenPeriod > currentTime);
});
@ -116,7 +116,7 @@ spamPrevention = {
next();
},
protected: function (req, res, next) {
protected: function protected(req, res, next) {
var currentTime = process.hrtime()[0],
remoteAddress = req.connection.remoteAddress,
rateProtectedPeriod = config.rateProtectedPeriod || 3600,
@ -136,7 +136,7 @@ spamPrevention = {
}
// filter entries that are older than rateProtectedPeriod
protectedSecurity = _.filter(protectedSecurity, function (logTime) {
protectedSecurity = _.filter(protectedSecurity, function filter(logTime) {
return (logTime.time + rateProtectedPeriod > currentTime);
});
@ -156,8 +156,8 @@ spamPrevention = {
return next();
},
resetCounter: function (email) {
loginSecurity = _.filter(loginSecurity, function (logTime) {
resetCounter: function resetCounter(email) {
loginSecurity = _.filter(loginSecurity, function filter(logTime) {
return (logTime.email !== email);
});
}

View File

@ -5,7 +5,7 @@ var frontend = require('../controllers/frontend'),
frontendRoutes;
frontendRoutes = function (middleware) {
frontendRoutes = function frontendRoutes(middleware) {
var router = express.Router(),
subdir = config.paths.subdir,
routeKeywords = config.routeKeywords,
@ -16,19 +16,19 @@ frontendRoutes = function (middleware) {
privateRouter = express.Router();
// ### Admin routes
router.get(/^\/(logout|signout)\/$/, function redirect(req, res) {
router.get(/^\/(logout|signout)\/$/, function redirectToSignout(req, res) {
/*jslint unparam:true*/
res.set({'Cache-Control': 'public, max-age=' + utils.ONE_YEAR_S});
res.redirect(301, subdir + '/ghost/signout/');
});
router.get(/^\/signup\/$/, function redirect(req, res) {
router.get(/^\/signup\/$/, function redirectToSignup(req, res) {
/*jslint unparam:true*/
res.set({'Cache-Control': 'public, max-age=' + utils.ONE_YEAR_S});
res.redirect(301, subdir + '/ghost/signup/');
});
// redirect to /ghost and let that do the authentication to prevent redirects to /ghost//admin etc.
router.get(/^\/((ghost-admin|admin|wp-admin|dashboard|signin|login)\/?)$/, function (req, res) {
router.get(/^\/((ghost-admin|admin|wp-admin|dashboard|signin|login)\/?)$/, function redirectToAdmin(req, res) {
/*jslint unparam:true*/
res.redirect(subdir + '/ghost/');
});

View File

@ -102,7 +102,7 @@ function updateCheckData() {
}
function updateCheckRequest() {
return updateCheckData().then(function (reqData) {
return updateCheckData().then(function then(reqData) {
var resData = '',
headers,
req;
@ -113,15 +113,15 @@ function updateCheckRequest() {
'Content-Length': reqData.length
};
return new Promise(function (resolve, reject) {
return new Promise(function p(resolve, reject) {
req = https.request({
hostname: checkEndpoint,
method: 'POST',
headers: headers
}, function (res) {
res.on('error', function (error) { reject(error); });
res.on('data', function (chunk) { resData += chunk; });
res.on('end', function () {
}, function handler(res) {
res.on('error', function onError(error) { reject(error); });
res.on('data', function onData(chunk) { resData += chunk; });
res.on('end', function onEnd() {
try {
resData = JSON.parse(resData);
resolve(resData);
@ -131,15 +131,15 @@ function updateCheckRequest() {
});
});
req.on('socket', function (socket) {
req.on('socket', function onSocket(socket) {
// Wait a maximum of 10seconds
socket.setTimeout(10000);
socket.on('timeout', function () {
socket.on('timeout', function onTimeout() {
req.abort();
});
});
req.on('error', function (error) {
req.on('error', function onError(error) {
reject(error);
});
@ -168,8 +168,8 @@ function updateCheckResponse(response) {
).catch(errors.rejectError)
);
return Promise.settle(ops).then(function (descriptors) {
descriptors.forEach(function (d) {
return Promise.settle(ops).then(function then(descriptors) {
descriptors.forEach(function forEach(d) {
if (d.isRejected()) {
errors.rejectError(d.reason());
}
@ -187,7 +187,7 @@ function updateCheck() {
// No update check
return Promise.resolve();
} else {
return api.settings.read(_.extend(internal, {key: 'nextUpdateCheck'})).then(function (result) {
return api.settings.read(_.extend(internal, {key: 'nextUpdateCheck'})).then(function then(result) {
var nextUpdateCheck = result.settings[0];
if (nextUpdateCheck && nextUpdateCheck.value && nextUpdateCheck.value > moment().unix()) {
@ -204,7 +204,7 @@ function updateCheck() {
}
function showUpdateNotification() {
return api.settings.read(_.extend(internal, {key: 'displayUpdateNotification'})).then(function (response) {
return api.settings.read(_.extend(internal, {key: 'displayUpdateNotification'})).then(function then(response) {
var display = response.settings[0];
// Version 0.4 used boolean to indicate the need for an update. This special case is