diff --git a/.jscsrc b/.jscsrc new file mode 100644 index 0000000000..f661c9e0cf --- /dev/null +++ b/.jscsrc @@ -0,0 +1,72 @@ +{ + "requireCurlyBraces": [ + "if", + "else", + "for", + "while", + "do", + "try", + "catch" + ], + "requireSpaceAfterKeywords": [ + "if", + "else", + "for", + "while", + "do", + "switch", + "case", + "return", + "try", + "catch", + "function", + "typeof" + ], + "requireSpaceBeforeBlockStatements": true, + "requireParenthesesAroundIIFE": true, + "requireSpacesInConditionalExpression": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowSpacesInFunctionDeclaration": { + "beforeOpeningRoundBrace": true + }, + "requireMultipleVarDecl": "onevar", + "requireBlocksOnNewline": 1, + "disallowPaddingNewlinesInBlocks": true, + "disallowEmptyBlocks": true, + "disallowSpacesInsideObjectBrackets": "all", + "disallowSpacesInsideArrayBrackets": true, + "disallowSpacesInsideParentheses": true, + "disallowQuotedKeysInObjects": true, + "disallowSpaceAfterObjectKeys": true, + "requireCommaBeforeLineBreak": true, + "disallowSpaceAfterPrefixUnaryOperators": true, + "disallowSpaceBeforePostfixUnaryOperators": true, + "disallowSpaceBeforeBinaryOperators": [ + "," + ], + "requireSpaceBeforeBinaryOperators": true, + "requireSpaceAfterBinaryOperators": true, + "requireCamelCaseOrUpperCaseIdentifiers": "ignoreProperties", + "disallowKeywords": [ "with" ], + "disallowMultipleLineBreaks": true, + "validateQuoteMarks": "'", + "validateIndentation": 4, + "disallowMixedSpacesAndTabs": true, + "disallowTrailingWhitespace": true, + "disallowTrailingComma": true, + "disallowKeywordsOnNewLine": [ "else" ], + "requireLineFeedAtFileEnd": true, + "requireCapitalizedConstructors": true, + "safeContextKeyword": ["self"], + "requireDotNotation": true, + "disallowYodaConditions": true, + "validateJSDoc": { + "checkParamNames": true, + "checkRedundantParams": true, + "requireParamTypes": true + }, + "requireSpaceAfterLineComment": true, + "disallowNewlineBeforeBlockStatements": true +} diff --git a/Gruntfile.js b/Gruntfile.js index 0aff8c5767..4eef650553 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -32,10 +32,47 @@ var _ = require('lodash'), }); }()), + // ## List of files we want to lint through jshint and jscs to make sure + // they conform to our desired code styles. + lintFiles = { + // Linting files for server side or shared javascript code. + server: { + files: { + src: [ + '*.js', + '!config*.js', // note: i added this, do we want this linted? + 'core/*.js', + 'core/server/**/*.js', + 'core/shared/**/*.js', + '!core/shared/vendor/**/*.js', + '!core/shared/lib/**/*.js' + ] + } + }, + // Linting files for client side javascript code. + client: { + files: { + src: [ + 'core/client/**/*.js', + '!core/client/docs/js/*.js', + '!core/client/assets/vendor/**/*.js', + '!core/client/tpl/**/*.js' + ] + } + }, + // Linting files for test code. + test: { + files: { + src: [ + 'core/test/**/*.js' + ] + } + } + }, + // ## Grunt configuration configureGrunt = function (grunt) { - // *This is not useful but required for jshint* colors.setTheme({silly: 'rainbow'}); @@ -65,7 +102,7 @@ var _ = require('lodash'), files: ['core/shared/**/*.js'], tasks: ['concat:dev'] }, - 'emberTemplates': { + emberTemplates: { files: ['core/client/**/*.hbs'], tasks: ['emberTemplates:dev'] }, @@ -121,49 +158,56 @@ var _ = require('lodash'), // ### grunt-contrib-jshint // Linting rules, run as part of `grunt validate`. See [grunt validate](#validate) and its subtasks for // more information. - jshint: { - // Linting rules for server side or shared javascript code - server: { - options: { - jshintrc: '.jshintrc' + jshint: (function () { + return _.merge({ + server: { + options: { + jshintrc: '.jshintrc' + } }, - files: { - src: [ - '*.js', - 'core/*.js', - 'core/server/**/*.js', - 'core/shared/**/*.js', - '!core/shared/vendor/**/*.js', - '!core/shared/lib/**/*.js' - ] - } - }, - // Linting rules for client side javascript code - client: { - options: { - jshintrc: 'core/client/.jshintrc' + client: { + options: { + jshintrc: 'core/client/.jshintrc' + } }, - files: { - src: [ - 'core/client/**/*.js', - '!core/client/docs/js/*.js', - '!core/client/assets/vendor/**/*.js', - '!core/client/tpl/**/*.js' - ] + test: { + options: { + jshintrc: 'core/test/.jshintrc' + } } - }, + }, lintFiles); + })(), - test: { - options: { - jshintrc: 'core/test/.jshintrc' + // ### grunt-jscs + // Code style rules, run as part of `grunt validate`. See [grunt validate](#validate) and its subtasks for + // more information. + jscs: (function () { + var jscsConfig = _.merge({ + server: { + options: { + config: '.jscsrc' + } }, - files: { - src: [ - 'core/test/**/*.js' - ] + client: { + options: { + config: '.jscsrc' + } + }, + test: { + options: { + config: '.jscsrc' + } } - } - }, + }, lintFiles); + + // JSCS depends on Esprima which doesn't yet support ES6 module + // syntax. As such we cannot run JSCS on the client code yet. + // Related JSCS issue: https://github.com/jscs-dev/node-jscs/issues/561 + // @TODO(hswolff): remove this once JSCS supports ES6. + delete jscsConfig.client; + + return jscsConfig; + })(), // ### grunt-mocha-cli // Configuration for the mocha test runner, used to run unit, integration and route tests as part of @@ -280,7 +324,7 @@ var _ = require('lodash'), options: { silent: true, // suppress logging map: true, // Use and update the sourcemap - browsers: ["last 2 versions", "> 1%", "Explorer 10"] + browsers: ['last 2 versions', '> 1%', 'Explorer 10'] }, single_file: { src: 'core/client/assets/css/<%= pkg.name %>.min.css', @@ -288,7 +332,6 @@ var _ = require('lodash'), } }, - // ### grunt-ember-templates // Compiles handlebar templates for ember emberTemplates: { @@ -320,7 +363,7 @@ var _ = require('lodash'), files: { 'core/built/scripts/templates.js': 'core/client/templates/**/*.hbs' } - }, + } }, // ### grunt-es6-module-transpiler @@ -460,7 +503,7 @@ var _ = require('lodash'), // ### grunt-contrib-concat // concatenate multiple JS files into a single file ready for use concat: { - 'dev': { + dev: { nonull: true, dest: 'core/built/scripts/vendor-dev.js', src: [ @@ -492,12 +535,12 @@ var _ = require('lodash'), 'core/shared/lib/showdown/extensions/ghostimagepreview.js', 'core/shared/lib/showdown/extensions/ghostgfm.js', - + 'core/shared/lib/nanoscroller/nanoscroller.js' ] }, - 'prod': { + prod: { nonull: true, dest: 'core/built/scripts/vendor.js', src: [ @@ -529,7 +572,7 @@ var _ = require('lodash'), 'core/shared/lib/showdown/extensions/ghostimagepreview.js', 'core/shared/lib/showdown/extensions/ghostgfm.js', - + 'core/shared/lib/nanoscroller/nanoscroller.js' ] } @@ -562,7 +605,7 @@ var _ = require('lodash'), // ### grunt-update-submodules // Grunt task to update git submodules - 'update_submodules': { + update_submodules: { default: { options: { params: '--init' @@ -580,7 +623,6 @@ var _ = require('lodash'), // Custom test runner for our Casper.js functional tests // This really ought to be refactored into a separate grunt task module grunt.registerTask('spawnCasperJS', function (target) { - target = _.contains(['client', 'frontend', 'setup'], target) ? target + '/' : undefined; var done = this.async(), @@ -650,7 +692,6 @@ var _ = require('lodash'), // Run `grunt docs` to generate annotated source code using the documentation described in the code comments. grunt.registerTask('docs', 'Generate Docs', ['docker']); - // ## Testing // Ghost has an extensive set of test suites. The following section documents the various types of tests @@ -719,11 +760,11 @@ var _ = require('lodash'), // // `grunt test` will lint and test your pre-built local Ghost codebase. // - // `grunt test` runs jshint as well as the 4 test suites. See the individual sub tasks below for details of + // `grunt test` runs jshint and jscs as well as the 4 test suites. See the individual sub tasks below for details of // each of the test suites. // grunt.registerTask('test', 'Run tests and lint code', - ['jshint', 'test-routes', 'test-unit', 'test-integration', 'test-functional']); + ['jshint', 'jscs', 'test-routes', 'test-unit', 'test-integration', 'test-functional']); // ### Unit Tests *(sub task)* // `grunt test-unit` will run just the unit tests @@ -840,7 +881,6 @@ var _ = require('lodash'), grunt.registerTask('test-coverage', 'Generate unit and integration (mocha) tests coverage report', ['clean:test', 'setTestEnv', 'ensureConfig', 'shell:coverage']); - // ## Building assets // // Ghost's GitHub repository contains the un-built source code for Ghost. If you're looking for the already @@ -921,7 +961,7 @@ var _ = require('lodash'), grunt.verbose.writeln('Creating contributors template.'); grunt.file.write(templatePath, - //Map contributors to the template. + // Map contributors to the template. _.map(contributors, function (contributor) { return contributorTemplate .replace(/<%githubUrl%>/g, contributor.githubUrl) diff --git a/core/client/loader.js b/core/client/loader.js index e102b3a95c..584654dc75 100644 --- a/core/client/loader.js +++ b/core/client/loader.js @@ -1,4 +1,4 @@ // Loader to create the Ember.js application /*global require */ -window.App = require('ghost/app')['default'].create(); \ No newline at end of file +window.App = require('ghost/app')['default'].create(); diff --git a/core/server/GhostServer.js b/core/server/GhostServer.js index fbb19c256c..76f2ace352 100644 --- a/core/server/GhostServer.js +++ b/core/server/GhostServer.js @@ -31,12 +31,12 @@ GhostServer.prototype.logStartMessages = function () { // Tell users if their node version is not supported, and exit if (!semver.satisfies(process.versions.node, packageInfo.engines.node)) { console.log( - "\nERROR: Unsupported version of Node".red, - "\nGhost needs Node version".red, + '\nERROR: Unsupported version of Node'.red, + '\nGhost needs Node version'.red, packageInfo.engines.node.yellow, - "you are using version".red, + 'you are using version'.red, process.versions.node.yellow, - "\nPlease go to http://nodejs.org to get a supported version".green + '\nPlease go to http://nodejs.org to get a supported version'.green ); process.exit(0); @@ -45,36 +45,36 @@ GhostServer.prototype.logStartMessages = function () { // Startup & Shutdown messages if (process.env.NODE_ENV === 'production') { console.log( - "Ghost is running...".green, - "\nYour blog is now available on", + 'Ghost is running...'.green, + '\nYour blog is now available on', config.url, - "\nCtrl+C to shut down".grey + '\nCtrl+C to shut down'.grey ); // ensure that Ghost exits correctly on Ctrl+C process.removeAllListeners('SIGINT').on('SIGINT', function () { console.log( - "\nGhost has shut down".red, - "\nYour blog is now offline" + '\nGhost has shut down'.red, + '\nYour blog is now offline' ); process.exit(0); }); } else { console.log( - ("Ghost is running in " + process.env.NODE_ENV + "...").green, - "\nListening on", + ('Ghost is running in ' + process.env.NODE_ENV + '...').green, + '\nListening on', config.getSocket() || config.server.host + ':' + config.server.port, - "\nUrl configured as:", + '\nUrl configured as:', config.url, - "\nCtrl+C to shut down".grey + '\nCtrl+C to shut down'.grey ); // ensure that Ghost exits correctly on Ctrl+C process.removeAllListeners('SIGINT').on('SIGINT', function () { console.log( - "\nGhost has shutdown".red, - "\nGhost was running for", + '\nGhost has shutdown'.red, + '\nGhost was running for', Math.round(process.uptime()), - "seconds" + 'seconds' ); process.exit(0); }); @@ -115,7 +115,6 @@ GhostServer.prototype.start = function (externalApp) { ); fs.chmod(config.getSocket(), '0660'); - } else { self.httpServer = app.listen( config.server.port, diff --git a/core/server/api/authentication.js b/core/server/api/authentication.js index ea2599102d..f84d7c93fc 100644 --- a/core/server/api/authentication.js +++ b/core/server/api/authentication.js @@ -20,7 +20,7 @@ authentication = { /** * ## Generate Reset Token * generate a reset token for a given email address - * @param {{passwordreset}} + * @param {Object} object * @returns {Promise(passwordreset)} message */ generateResetToken: function generateResetToken(object) { @@ -42,7 +42,7 @@ authentication = { return Promise.reject(new errors.BadRequestError('No email provided.')); } - return users.read({ context: {internal: true}, email: email, status: 'active' }).then(function () { + return users.read({context: {internal: true}, email: email, status: 'active'}).then(function () { return settings.read({context: {internal: true}, key: 'dbHash'}); }).then(function (response) { var dbHash = response.settings[0].value; @@ -51,7 +51,7 @@ authentication = { var baseUrl = config.forceAdminSSL ? (config.urlSSL || config.url) : config.url, resetUrl = baseUrl.replace(/\/$/, '') + '/ghost/reset/' + resetToken + '/'; - return mail.generateContent({data: { resetUrl: resetUrl }, template: 'reset-password'}); + return mail.generateContent({data: {resetUrl: resetUrl}, template: 'reset-password'}); }).then(function (emailContent) { var payload = { mail: [{ @@ -76,7 +76,7 @@ authentication = { /** * ## Reset Password * reset password if a valid token and password (2x) is passed - * @param {{passwordreset}} + * @param {Object} object * @returns {Promise(passwordreset)} message */ resetPassword: function resetPassword(object) { @@ -150,14 +150,14 @@ authentication = { isSetup: function () { return dataProvider.User.query(function (qb) { - qb.whereIn('status', ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked']); - }).fetch().then(function (users) { - if (users) { - return Promise.resolve({ setup: [{status: true}]}); - } else { - return Promise.resolve({ setup: [{status: false}]}); - } - }); + qb.whereIn('status', ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked']); + }).fetch().then(function (users) { + if (users) { + return Promise.resolve({setup: [{status: true}]}); + } else { + return Promise.resolve({setup: [{status: false}]}); + } + }); }, setup: function (object) { @@ -226,13 +226,12 @@ authentication = { return mail.send(payload, {context: {internal: true}}).catch(function (error) { errors.logError( error.message, - "Unable to send welcome email, your blog will continue to function.", - "Please see http://support.ghost.org/mail/ for instructions on configuring email." + 'Unable to send welcome email, your blog will continue to function.', + 'Please see http://support.ghost.org/mail/ for instructions on configuring email.' ); }); - }).then(function () { - return Promise.resolve({ users: [setupUser]}); + return Promise.resolve({users: [setupUser]}); }); }, @@ -247,11 +246,11 @@ authentication = { return errors.BadRequestError('Invalid token_type_hint given.'); } - return token.destroyByToken({ token: object.token }).then(function () { - return Promise.resolve({ token: object.token }); + return token.destroyByToken({token: object.token}).then(function () { + return Promise.resolve({token: object.token}); }, function () { // On error we still want a 200. See https://tools.ietf.org/html/rfc7009#page-5 - return Promise.resolve({ token: object.token, error: 'Invalid token provided' }); + return Promise.resolve({token: object.token, error: 'Invalid token provided'}); }); } }; diff --git a/core/server/api/configuration.js b/core/server/api/configuration.js index afe241e044..64d3dd9d90 100644 --- a/core/server/api/configuration.js +++ b/core/server/api/configuration.js @@ -10,13 +10,13 @@ var _ = require('lodash'), function getValidKeys() { var validKeys = { - 'fileStorage': config.fileStorage === false ? false : true, - 'apps': config.apps === true ? true : false, - 'version': false, - 'environment': process.env.NODE_ENV, - 'database': config.database.client, - 'mail': _.isObject(config.mail) ? config.mail.transport : '', - 'blogUrl': config.url + fileStorage: config.fileStorage === false ? false : true, + apps: config.apps === true ? true : false, + version: false, + environment: process.env.NODE_ENV, + database: config.database.client, + mail: _.isObject(config.mail) ? config.mail.transport : '', + blogUrl: config.url }; return parsePackageJson('package.json').then(function (json) { @@ -39,7 +39,7 @@ configuration = { */ browse: function browse() { return getValidKeys().then(function (result) { - return Promise.resolve({ 'configuration': _.map(result, function (value, key) { + return Promise.resolve({configuration: _.map(result, function (value, key) { return { key: key, value: value @@ -55,7 +55,7 @@ configuration = { read: function read(options) { return getValidKeys().then(function (result) { if (_.has(result, options.key)) { - return Promise.resolve({ 'configuration': [{ + return Promise.resolve({configuration: [{ key: options.key, value: result[options.key] }]}); diff --git a/core/server/api/db.js b/core/server/api/db.js index b13e90c93b..ad0966273c 100644 --- a/core/server/api/db.js +++ b/core/server/api/db.js @@ -14,7 +14,6 @@ var dataExport = require('../data/export'), api.settings = require('./settings'); - function isValidFile(ext) { if (ext === '.json') { return true; @@ -35,19 +34,19 @@ db = { * @param {{context}} options * @returns {Promise} Ghost Export JSON format */ - 'exportContent': function (options) { + exportContent: function (options) { options = options || {}; // Export data, otherwise send error 500 return canThis(options.context).exportContent.db().then(function () { - return dataExport().then(function (exportedData) { - return { db: [exportedData] }; - }).catch(function (error) { - return Promise.reject(new errors.InternalServerError(error.message || error)); - }); - }, function () { - return Promise.reject(new errors.NoPermissionError('You do not have permission to export data. (no rights)')); + return dataExport().then(function (exportedData) { + return {db: [exportedData]}; + }).catch(function (error) { + return Promise.reject(new errors.InternalServerError(error.message || error)); }); + }, function () { + return Promise.reject(new errors.NoPermissionError('You do not have permission to export data. (no rights)')); + }); }, /** * ### Import Content @@ -57,7 +56,7 @@ db = { * @param {{context}} options * @returns {Promise} Success */ - 'importContent': function (options) { + importContent: function (options) { options = options || {}; var databaseVersion, type, @@ -79,7 +78,7 @@ db = { } }).then(function () { return api.settings.read( - {key: 'databaseVersion', context: { internal: true }} + {key: 'databaseVersion', context: {internal: true}} ).then(function (response) { var setting = response.settings[0]; @@ -113,9 +112,8 @@ db = { // Import for the current version return dataImport(databaseVersion, importData); - }).then(api.settings.updateSettingsCache) - .return({ db: [] }) + .return({db: []}) .finally(function () { // Unlink the file after import return Promise.promisify(fs.unlink)(filepath); @@ -132,12 +130,12 @@ db = { * @param {{context}} options * @returns {Promise} Success */ - 'deleteAllContent': function (options) { + deleteAllContent: function (options) { options = options || {}; return canThis(options.context).deleteAllContent.db().then(function () { return Promise.resolve(dataProvider.deleteAllContent()) - .return({ db: [] }) + .return({db: []}) .catch(function (error) { return Promise.reject(new errors.InternalServerError(error.message || error)); }); diff --git a/core/server/api/index.js b/core/server/api/index.js index 2741659c22..955a7d42be 100644 --- a/core/server/api/index.js +++ b/core/server/api/index.js @@ -146,7 +146,6 @@ contentDispositionHeader = function () { }); }; - /** * ### Format HTTP Errors * Converts the error response from the API into a format which can be returned over HTTP @@ -166,7 +165,7 @@ formatHttpErrors = function (error) { _.each(error, function (errorItem) { var errorContent = {}; - //TODO: add logic to set the correct status code + // TODO: add logic to set the correct status code statusCode = errorItem.code || 500; errorContent.message = _.isString(errorItem) ? errorItem : @@ -178,7 +177,6 @@ formatHttpErrors = function (error) { return {errors: errors, statusCode: statusCode}; }; - addHeaders = function (apiMethod, req, res, result) { var ops = [], cacheInvalidation, @@ -198,7 +196,7 @@ addHeaders = function (apiMethod, req, res, result) { location = locationHeader(req, result) .then(function addLocationHeader(header) { if (header) { - res.set({'Location': header}); + res.set({Location: header}); // The location header indicates that a new object was created. // In this case the status code should be 201 Created res.status(201); diff --git a/core/server/api/mail.js b/core/server/api/mail.js index 545a0d4977..8fa794c969 100644 --- a/core/server/api/mail.js +++ b/core/server/api/mail.js @@ -45,7 +45,6 @@ mail = { .catch(function (error) { return Promise.reject(new errors.EmailError(error.message)); }); - }, function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to send mail.')); }); @@ -56,7 +55,7 @@ mail = { * Send a test email * * @public - * @param {Object} required property 'to' which contains the recipient address + * @param {Object} options required property 'to' which contains the recipient address * @returns {Promise} */ sendTest: function (options) { @@ -79,14 +78,13 @@ mail = { /** * - * @param { + * @param {Object} options { * data: JSON object representing the data that will go into the email * template: which email template to load (files are stored in /core/server/email-templates/) * } * @returns {*} */ generateContent: function (options) { - var defaultData = { siteUrl: config.forceAdminSSL ? (config.urlSSL || config.url) : config.url }, @@ -94,28 +92,26 @@ mail = { _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; - //read the proper email body template + // read the proper email body template return new Promise(function (resolve, reject) { fs.readFile(templatesDir + '/' + options.template + '.html', {encoding: 'utf8'}, function (err, fileContent) { if (err) { reject(err); } - //insert user-specific data into the email + // insert user-specific data into the email var htmlContent = _.template(fileContent, emailData), textContent; - //generate a plain-text version of the same email + // generate a plain-text version of the same email textContent = htmlToText.fromString(htmlContent); resolve({ html: htmlContent, text: textContent }); - }); }); - } }; diff --git a/core/server/api/notifications.js b/core/server/api/notifications.js index 29a07a4f34..97ce9971d3 100644 --- a/core/server/api/notifications.js +++ b/core/server/api/notifications.js @@ -26,7 +26,7 @@ notifications = { */ browse: function browse(options) { return canThis(options.context).browse.notification().then(function () { - return { 'notifications': notificationsStore }; + return {notifications: notificationsStore}; }, function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to browse notifications.')); }); @@ -47,7 +47,6 @@ notifications = { * ``` */ add: function add(object, options) { - var defaults = { dismissible: true, location: 'bottom', @@ -62,14 +61,14 @@ notifications = { notification = _.assign(defaults, notification, { id: notificationCounter - //status: 'persistent' + // status: 'persistent' }); notificationsStore.push(notification); addedNotifications.push(notification); }); - return { notifications: addedNotifications }; + return {notifications: addedNotifications}; }); }, function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to add notifications.')); @@ -102,7 +101,7 @@ notifications = { notificationsStore = _.reject(notificationsStore, function (element) { return element.id === parseInt(options.id, 10); }); - return { notifications: [notification] }; + return {notifications: [notification]}; }, function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to destroy notifications.')); }); diff --git a/core/server/api/posts.js b/core/server/api/posts.js index 371b255f8a..9ebc1212ec 100644 --- a/core/server/api/posts.js +++ b/core/server/api/posts.js @@ -85,7 +85,7 @@ posts = { return dataProvider.Post.findOne(data, options).then(function (result) { if (result) { - return { posts: [ result.toJSON() ]}; + return {posts: [result.toJSON()]}; } return Promise.reject(new errors.NotFoundError('Post not found.')); @@ -118,7 +118,7 @@ posts = { if (result.updated('status') !== result.get('status')) { post.statusChanged = true; } - return { posts: [ post ]}; + return {posts: [post]}; } return Promise.reject(new errors.NotFoundError('Post not found.')); @@ -154,14 +154,13 @@ posts = { // When creating a new post that is published right now, signal the change post.statusChanged = true; } - return { posts: [ post ]}; + return {posts: [post]}; }); }, function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to add posts.')); }); }, - /** * ### Destroy * Delete a post, cleans up tag relations, but not unused tags @@ -193,4 +192,4 @@ posts = { }; -module.exports = posts; \ No newline at end of file +module.exports = posts; diff --git a/core/server/api/roles.js b/core/server/api/roles.js index ea07821aec..649470e63b 100644 --- a/core/server/api/roles.js +++ b/core/server/api/roles.js @@ -34,7 +34,6 @@ roles = { return canThis(options.context).browse.role().then(function () { return dataProvider.Role.findAll(options).then(function (foundRoles) { if (options.permissions === 'assign') { - // Hacky implementation of filtering because when.filter is only available in when 3.4.0, // but that's buggy and kills other tests and introduces Heisenbugs. Until we turn everything // to Bluebird, this works. Sorry. @@ -51,12 +50,12 @@ roles = { }); return Promise.all(permissionMap).then(function (resolved) { - return { roles: _.filter(resolved, function (role) { + return {roles: _.filter(resolved, function (role) { return role !== null; - }) }; + })}; }).catch(errors.logAndThrowError); } - return { roles: foundRoles.toJSON() }; + return {roles: foundRoles.toJSON()}; }); }) .catch(errors.logAndThrowError); diff --git a/core/server/api/settings.js b/core/server/api/settings.js index d8dfbc6467..bcfa735204 100644 --- a/core/server/api/settings.js +++ b/core/server/api/settings.js @@ -29,7 +29,6 @@ var _ = require('lodash'), */ settingsCache = {}; - /** * ### Updates Config Theme Settings * Maintains the cache of theme specific variables that are reliant on settings. @@ -50,7 +49,7 @@ updateConfigTheme = function () { * ### Update Settings Cache * Maintain the internal cache of the settings object * @public - * @param settings + * @param {Object} settings * @returns {Settings} */ updateSettingsCache = function (settings) { @@ -82,8 +81,8 @@ updateSettingsCache = function (settings) { * ### Settings Filter * Filters an object based on a given filter object * @private - * @param settings - * @param filter + * @param {Object} settings + * @param {String} filter * @returns {*} */ settingsFilter = function (settings, filter) { @@ -118,7 +117,7 @@ filterPaths = function (paths, active) { } _.each(pathKeys, function (key) { - //do not include hidden files or _messages + // do not include hidden files or _messages if (key.indexOf('.') !== 0 && key !== '_messages' && key !== 'README.md' @@ -141,11 +140,10 @@ filterPaths = function (paths, active) { return res; }; - /** * ### Read Settings Result * @private - * @param settingsModels + * @param {Array} settingsModels * @returns {Settings} */ readSettingsResult = function (settingsModels) { @@ -186,8 +184,8 @@ readSettingsResult = function (settingsModels) { /** * ### Settings Result * @private - * @param settings - * @param type + * @param {Object} settings + * @param {String} type * @returns {{settings: *}} */ settingsResult = function (settings, type) { @@ -209,8 +207,7 @@ settingsResult = function (settings, type) { /** * ### Populate Default Setting * @private - * @param key - * @param type + * @param {String} key * @returns Promise(Setting) */ populateDefaultSetting = function (key) { @@ -238,7 +235,7 @@ populateDefaultSetting = function (key) { * ### Can Edit All Settings * Check that this edit request is allowed for all settings requested to be updated * @private - * @param settingsInfo + * @param {Object} settingsInfo * @returns {*} */ canEditAllSettings = function (settingsInfo, options) { @@ -252,7 +249,6 @@ canEditAllSettings = function (settingsInfo, options) { return canThis(options.context).edit.setting(setting.key).catch(function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to edit settings.')); }); - }, checks = _.map(settingsInfo, function (settingInfo) { var setting = settingsCache[settingInfo.key]; @@ -280,7 +276,7 @@ settings = { /** * ### Browse - * @param options + * @param {Object} options * @returns {*} */ browse: function browse(options) { @@ -314,12 +310,12 @@ settings = { /** * ### Read - * @param options + * @param {Object} options * @returns {*} */ read: function read(options) { if (_.isString(options)) { - options = { key: options }; + options = {key: options}; } var getSettingsResult = function () { @@ -372,10 +368,10 @@ settings = { // Allow shorthand syntax where a single key and value are passed to edit instead of object and options if (_.isString(object)) { - object = { settings: [{ key: object, value: options }]}; + object = {settings: [{key: object, value: options}]}; } - //clean data + // clean data _.each(object.settings, function (setting) { if (!_.isString(setting.value)) { setting.value = JSON.stringify(setting.value); diff --git a/core/server/api/slugs.js b/core/server/api/slugs.js index ac1b8dc96a..4326d6d540 100644 --- a/core/server/api/slugs.js +++ b/core/server/api/slugs.js @@ -43,7 +43,7 @@ slugs = { return Promise.reject(new errors.InternalServerError('Could not generate slug.')); } - return { slugs: [{ slug: slug }] }; + return {slugs: [{slug: slug}]}; }); }).catch(function (err) { if (err) { diff --git a/core/server/api/tags.js b/core/server/api/tags.js index b49bc59aa6..2e8c8f2fdb 100644 --- a/core/server/api/tags.js +++ b/core/server/api/tags.js @@ -20,9 +20,8 @@ tags = { browse: function browse(options) { return canThis(options.context).browse.tag().then(function () { return dataProvider.Tag.findAll(options).then(function (result) { - return { tags: result.toJSON() }; + return {tags: result.toJSON()}; }); - }, function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to browse tags.')); }); diff --git a/core/server/api/themes.js b/core/server/api/themes.js index e3f23c812e..d0dc59f5c0 100644 --- a/core/server/api/themes.js +++ b/core/server/api/themes.js @@ -38,7 +38,6 @@ themes = { && key !== '_messages' && key !== 'README.md' ) { - var item = { uuid: key }; @@ -53,7 +52,7 @@ themes = { } }); - return { themes: themes }; + return {themes: themes}; }); }, function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to browse themes.')); @@ -92,10 +91,10 @@ themes = { // Activate the theme return settings.edit( - {settings: [{ key: 'activeTheme', value: themeName }]}, {context: {internal: true }} + {settings: [{key: 'activeTheme', value: themeName}]}, {context: {internal: true}} ).then(function () { theme.active = true; - return { themes: [theme]}; + return {themes: [theme]}; }); }); }, function () { diff --git a/core/server/api/users.js b/core/server/api/users.js index 8d5ae3bb6b..0c20703be2 100644 --- a/core/server/api/users.js +++ b/core/server/api/users.js @@ -27,8 +27,8 @@ sendInviteEmail = function sendInviteEmail(user) { var emailData; return Promise.join( - users.read({'id': user.created_by}), - settings.read({'key': 'title'}), + users.read({id: user.created_by}), + settings.read({key: 'title'}), settings.read({context: {internal: true}, key: 'dbHash'}) ).then(function (values) { var invitedBy = values[0].users[0], @@ -111,7 +111,7 @@ users = { return dataProvider.User.findOne(data, options).then(function (result) { if (result) { - return { users: [result.toJSON()] }; + return {users: [result.toJSON()]}; } return Promise.reject(new errors.NotFoundError('User not found.')); @@ -140,7 +140,7 @@ users = { return dataProvider.User.edit(data.users[0], options) .then(function (result) { if (result) { - return { users: [result.toJSON()]}; + return {users: [result.toJSON()]}; } return Promise.reject(new errors.NotFoundError('User not found.')); @@ -245,8 +245,8 @@ users = { // If sending the invitation failed, set status to invited-pending return dataProvider.User.edit({status: 'invited-pending'}, {id: user.id}).then(function (user) { - return dataProvider.User.findOne({ id: user.id, status: 'all' }, options).then(function (user) { - return { users: [user] }; + return dataProvider.User.findOne({id: user.id, status: 'all'}, options).then(function (user) { + return {users: [user]}; }); }); } @@ -273,13 +273,11 @@ users = { return addOperation(); }); - }).catch(function (error) { return errors.handleAPIError(error, 'You do not have permission to add this user'); }); }, - /** * ### Destroy * @param {{id, context}} options @@ -287,7 +285,7 @@ users = { */ destroy: function destroy(options) { return canThis(options.context).destroy.user(options.id).then(function () { - return users.read(_.merge(options, { status: 'all'})).then(function (result) { + return users.read(_.merge(options, {status: 'all'})).then(function (result) { return dataProvider.Base.transaction(function (t) { options.transacting = t; @@ -315,7 +313,6 @@ users = { }); }, - /** * ### Change Password * @param {password} object @@ -348,7 +345,7 @@ users = { }).then(function () { return utils.checkObject(object, 'owner').then(function (checkedOwnerTransfer) { return dataProvider.User.transferOwnership(checkedOwnerTransfer.owner[0], options).then(function (updatedUsers) { - return Promise.resolve({ users: updatedUsers }); + return Promise.resolve({users: updatedUsers}); }).catch(function (error) { return Promise.reject(new errors.ValidationError(error.message)); }); diff --git a/core/server/apps/dependencies.js b/core/server/apps/dependencies.js index 8a255309f6..775cea17a6 100644 --- a/core/server/apps/dependencies.js +++ b/core/server/apps/dependencies.js @@ -19,8 +19,7 @@ AppDependencies.prototype.install = function installAppDependencies() { if (!exists) { // Nothing to do, resolve right away? resolve(); - } - else { + } else { // Run npm install in the app directory spawnOpts = { cwd: self.appPath @@ -47,7 +46,7 @@ AppDependencies.prototype.spawnCommand = function (command, args, opt) { opt = opt || {}; - return spawn(winCommand, winArgs, _.defaults({ stdio: 'inherit' }, opt)); + return spawn(winCommand, winArgs, _.defaults({stdio: 'inherit'}, opt)); }; module.exports = AppDependencies; diff --git a/core/server/apps/loader.js b/core/server/apps/loader.js index ca6d9bcf20..4e924f5d3d 100644 --- a/core/server/apps/loader.js +++ b/core/server/apps/loader.js @@ -66,7 +66,7 @@ loader = { return perms.read().catch(function (err) { // Provide a helpful error about which app - return Promise.reject(new Error("Error loading app named " + name + "; problem reading permissions: " + err.message)); + return Promise.reject(new Error('Error loading app named ' + name + '; problem reading permissions: ' + err.message)); }); }) .then(function (appPerms) { @@ -76,7 +76,7 @@ loader = { // Check for an install() method on the app. if (!_.isFunction(app.install)) { - return Promise.reject(new Error("Error loading app named " + name + "; no install() method defined.")); + return Promise.reject(new Error('Error loading app named ' + name + '; no install() method defined.')); } // Run the app.install() method @@ -97,7 +97,7 @@ loader = { // Check for an activate() method on the app. if (!_.isFunction(app.activate)) { - return Promise.reject(new Error("Error loading app named " + name + "; no activate() method defined.")); + return Promise.reject(new Error('Error loading app named ' + name + '; no activate() method defined.')); } // Wrapping the activate() with a when because it's possible diff --git a/core/server/apps/permissions.js b/core/server/apps/permissions.js index ecc21efc94..9c5ea4edd8 100644 --- a/core/server/apps/permissions.js +++ b/core/server/apps/permissions.js @@ -13,23 +13,23 @@ AppPermissions.prototype.read = function () { var self = this; return this.checkPackageContentsExists().then(function (exists) { - if (!exists) { - // If no package.json, return default permissions + if (!exists) { + // If no package.json, return default permissions + return Promise.resolve(AppPermissions.DefaultPermissions); + } + + // Read and parse the package.json + return self.getPackageContents().then(function (parsed) { + // If no permissions in the package.json then return the default permissions. + if (!(parsed.ghost && parsed.ghost.permissions)) { return Promise.resolve(AppPermissions.DefaultPermissions); } - // Read and parse the package.json - return self.getPackageContents().then(function (parsed) { - // If no permissions in the package.json then return the default permissions. - if (!(parsed.ghost && parsed.ghost.permissions)) { - return Promise.resolve(AppPermissions.DefaultPermissions); - } + // TODO: Validation on permissions object? - // TODO: Validation on permissions object? - - return Promise.resolve(parsed.ghost.permissions); - }); + return Promise.resolve(parsed.ghost.permissions); }); + }); }; AppPermissions.prototype.checkPackageContentsExists = function () { diff --git a/core/server/apps/proxy.js b/core/server/apps/proxy.js index 1d4d397be0..11116bf1ab 100644 --- a/core/server/apps/proxy.js +++ b/core/server/apps/proxy.js @@ -1,9 +1,10 @@ var _ = require('lodash'), api = require('../api'), helpers = require('../helpers'), - filters = require('../filters'); + filters = require('../filters'), + generateProxyFunctions; -var generateProxyFunctions = function (name, permissions) { +generateProxyFunctions = function (name, permissions) { var getPermission = function (perm) { return permissions[perm]; }, @@ -82,7 +83,6 @@ var generateProxyFunctions = function (name, permissions) { }; function AppProxy(options) { - if (!options.name) { throw new Error('Must provide an app name for api context'); } diff --git a/core/server/apps/sandbox.js b/core/server/apps/sandbox.js index 2a5f0079c1..0d0676b183 100644 --- a/core/server/apps/sandbox.js +++ b/core/server/apps/sandbox.js @@ -38,7 +38,7 @@ AppSandbox.prototype.loadModule = function loadModuleSandboxed(modulePath) { currentModule.require = function requireProxy(module) { // check whitelist, plugin config, etc. if (_.contains(self.opts.blacklist, module)) { - throw new Error("Unsafe App require: " + module); + throw new Error('Unsafe App require: ' + module); } var firstTwo = module.slice(0, 2), diff --git a/core/server/config/index.js b/core/server/config/index.js index 69989d1fde..bd23e0f3c5 100644 --- a/core/server/config/index.js +++ b/core/server/config/index.js @@ -19,7 +19,6 @@ var path = require('path'), defaultConfig = {}, knexInstance; - function ConfigManager(config) { /** * Our internal true representation of our current config object. @@ -108,27 +107,27 @@ ConfigManager.prototype.set = function (config) { knex: knexInstance }, paths: { - 'appRoot': appRoot, - 'subdir': subdir, - 'config': this._config.paths.config || path.join(appRoot, 'config.js'), - 'configExample': path.join(appRoot, 'config.example.js'), - 'corePath': corePath, + appRoot: appRoot, + subdir: subdir, + config: this._config.paths.config || path.join(appRoot, 'config.js'), + configExample: path.join(appRoot, 'config.example.js'), + corePath: corePath, - 'contentPath': contentPath, - 'themePath': path.resolve(contentPath, 'themes'), - 'appPath': path.resolve(contentPath, 'apps'), - 'imagesPath': path.resolve(contentPath, 'images'), - 'imagesRelPath': 'content/images', + contentPath: contentPath, + themePath: path.resolve(contentPath, 'themes'), + appPath: path.resolve(contentPath, 'apps'), + imagesPath: path.resolve(contentPath, 'images'), + imagesRelPath: 'content/images', - 'adminViews': path.join(corePath, '/server/views/'), - 'helperTemplates': path.join(corePath, '/server/helpers/tpl/'), - 'exportPath': path.join(corePath, '/server/data/export/'), - 'lang': path.join(corePath, '/shared/lang/'), - 'debugPath': subdir + '/ghost/debug/', + adminViews: path.join(corePath, '/server/views/'), + helperTemplates: path.join(corePath, '/server/helpers/tpl/'), + exportPath: path.join(corePath, '/server/data/export/'), + lang: path.join(corePath, '/shared/lang/'), + debugPath: subdir + '/ghost/debug/', - 'availableThemes': this._config.paths.availableThemes || {}, - 'availableApps': this._config.paths.availableApps || {}, - 'builtScriptPath': path.join(corePath, 'built/scripts/') + availableThemes: this._config.paths.availableThemes || {}, + availableApps: this._config.paths.availableApps || {}, + builtScriptPath: path.join(corePath, 'built/scripts/') }, theme: { // normalise the URL by removing any trailing slash @@ -258,7 +257,7 @@ ConfigManager.prototype.validate = function () { } // Check that our url is valid - if (!validator.isURL(config.url, { protocols: ['http', 'https'], require_protocol: true })) { + if (!validator.isURL(config.url, {protocols: ['http', 'https'], require_protocol: true})) { errors.logError(new Error('Your site url in config.js is invalid.'), config.url, 'Please make sure this is a valid url before restarting'); return Promise.reject(new Error('invalid site url')); @@ -294,7 +293,7 @@ ConfigManager.prototype.validate = function () { /** * Helper method for checking the state of a particular privacy flag - * @param privacyFlag The flag to check + * @param {String} privacyFlag The flag to check * @returns {boolean} */ ConfigManager.prototype.isPrivacyDisabled = function (privacyFlag) { @@ -324,11 +323,9 @@ ConfigManager.prototype.checkDeprecated = function () { errors.logWarn(errorText, explinationText, helpText); } - }); }; - if (testingEnvs.indexOf(process.env.NODE_ENV) > -1) { defaultConfig = require('../../../config.example')[process.env.NODE_ENV]; } diff --git a/core/server/config/url.js b/core/server/config/url.js index 43a8f7810f..a34257c3dc 100644 --- a/core/server/config/url.js +++ b/core/server/config/url.js @@ -106,9 +106,9 @@ function urlFor(context, data, absolute) { // this will become really big knownPaths = { - 'home': '/', - 'rss': '/rss/', - 'api': '/ghost/api/v0.1' + home: '/', + rss: '/rss/', + api: '/ghost/api/v0.1' }; // Make data properly optional diff --git a/core/server/controllers/admin.js b/core/server/controllers/admin.js index 7b8bd35ca7..2196fdcc25 100644 --- a/core/server/controllers/admin.js +++ b/core/server/controllers/admin.js @@ -35,8 +35,8 @@ adminControllers = { }; return api.notifications.browse({context: {internal: true}}).then(function (results) { - if (!_.some(results.notifications, { message: notification.message })) { - return api.notifications.add({ notifications: [notification] }, {context: {internal: true}}); + if (!_.some(results.notifications, {message: notification.message})) { + return api.notifications.add({notifications: [notification]}, {context: {internal: true}}); } }); }).finally(function () { diff --git a/core/server/controllers/frontend.js b/core/server/controllers/frontend.js index 8723ca414f..b84242a93e 100644 --- a/core/server/controllers/frontend.js +++ b/core/server/controllers/frontend.js @@ -115,7 +115,7 @@ function getActiveThemePaths() { } frontendControllers = { - 'homepage': function (req, res, next) { + homepage: function (req, res, next) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1, options = { @@ -128,7 +128,6 @@ frontendControllers = { } return getPostPage(options).then(function (page) { - // If page is greater than number of pages we have, redirect to last page if (pageParam > page.meta.pagination.pages) { return res.redirect(page.meta.pagination.pages === 1 ? config.paths.subdir + '/' : (config.paths.subdir + '/page/' + page.meta.pagination.pages + '/')); @@ -152,7 +151,7 @@ frontendControllers = { }); }).catch(handleError(next)); }, - 'tag': function (req, res, next) { + tag: function (req, res, next) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1, options = { @@ -206,8 +205,7 @@ frontendControllers = { }); }).catch(handleError(next)); }, - 'author': function (req, res, next) { - + author: function (req, res, next) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1, options = { @@ -215,8 +213,6 @@ frontendControllers = { author: req.params.slug }; - - // Get url for tag page function authorUrl(author, page) { var url = config.paths.subdir + '/author/' + author + '/'; @@ -264,7 +260,7 @@ frontendControllers = { }).catch(handleError(next)); }, - 'single': function (req, res, next) { + single: function (req, res, next) { var path = req.path, params, editFormat, @@ -377,7 +373,6 @@ frontendControllers = { } return render(); - }).catch(function (err) { // If we've thrown an error message // of type: 'NotFound' then we found @@ -389,7 +384,7 @@ frontendControllers = { return handleError(next)(err); }); }, - 'rss': function (req, res, next) { + rss: function (req, res, next) { function isPaginated() { return req.route.path.indexOf(':page') !== -1; } @@ -486,7 +481,7 @@ frontendControllers = { categories: _.pluck(post.tags, 'name'), author: post.author ? post.author.name : null }, - htmlContent = cheerio.load(post.html, { decodeEntities: false }); + htmlContent = cheerio.load(post.html, {decodeEntities: false}); // convert relative resource urls to absolute ['href', 'src'].forEach(function (attributeName) { diff --git a/core/server/data/fixtures/index.js b/core/server/data/fixtures/index.js index 8a9f7bbe10..62a526c6b3 100644 --- a/core/server/data/fixtures/index.js +++ b/core/server/data/fixtures/index.js @@ -25,7 +25,6 @@ var Promise = require('bluebird'), populate, update; - logInfo = function logInfo(message) { errors.logInfo('Migrations', message); }; diff --git a/core/server/data/fixtures/permissions/index.js b/core/server/data/fixtures/permissions/index.js index c1dbe1d99f..9356e56020 100644 --- a/core/server/data/fixtures/permissions/index.js +++ b/core/server/data/fixtures/permissions/index.js @@ -55,13 +55,12 @@ addAllRolesPermissions = function () { return Promise.all(ops); }; - addAllPermissions = function (options) { var ops = []; - _.each(fixtures.permissions, function (permissions, object_type) { + _.each(fixtures.permissions, function (permissions, objectType) { _.each(permissions, function (permission) { ops.push(function () { - permission.object_type = object_type; + permission.object_type = objectType; return models.Permission.add(permission, options); }); }); diff --git a/core/server/data/import/000.js b/core/server/data/import/000.js index 2757ffd674..e02ec2ee46 100644 --- a/core/server/data/import/000.js +++ b/core/server/data/import/000.js @@ -5,7 +5,6 @@ var Promise = require('bluebird'), Importer000; - Importer000 = function () { _.bindAll(this, 'doImport'); @@ -34,13 +33,12 @@ Importer000.prototype.canImport = function (data) { return Promise.reject('Unsupported version of data: ' + data.meta.version); }; - Importer000.prototype.loadUsers = function () { var users = {all: {}}; return models.User.findAll({include: 'roles'}).then(function (_users) { _users.forEach(function (user) { - users.all[user.get('email')] = {'realId': user.get('id')}; + users.all[user.get('email')] = {realId: user.get('id')}; if (user.related('roles').toJSON()[0] && user.related('roles').toJSON()[0].name === 'Owner') { users.owner = user.toJSON(); } @@ -54,9 +52,9 @@ Importer000.prototype.loadUsers = function () { }); }; -//Importer000.prototype.importerFunction = function (t) { +// Importer000.prototype.importerFunction = function (t) { // -//}; +// }; Importer000.prototype.doUserImport = function (t, tableData, users, errors) { var userOps = [], @@ -104,7 +102,6 @@ Importer000.prototype.doImport = function (data) { users = result.all; return models.Base.transaction(function (t) { - // Step 1: Attempt to handle adding new users self.doUserImport(t, tableData, users, errors).then(function (result) { var importResults = []; @@ -167,7 +164,7 @@ Importer000.prototype.doImport = function (data) { */ }); }).then(function () { - //TODO: could return statistics of imported items + // TODO: could return statistics of imported items return Promise.resolve(); }); }); diff --git a/core/server/data/import/001.js b/core/server/data/import/001.js index cdfa03c139..5def4a9871 100644 --- a/core/server/data/import/001.js +++ b/core/server/data/import/001.js @@ -5,4 +5,4 @@ module.exports = { importData: function (data) { return new Importer000.importData(data); } -}; \ No newline at end of file +}; diff --git a/core/server/data/import/002.js b/core/server/data/import/002.js index 84ebbc71b6..b0a113d256 100644 --- a/core/server/data/import/002.js +++ b/core/server/data/import/002.js @@ -5,4 +5,4 @@ module.exports = { importData: function (data) { return new Importer000.importData(data); } -}; \ No newline at end of file +}; diff --git a/core/server/data/import/003.js b/core/server/data/import/003.js index 25ea111d96..349df223e7 100644 --- a/core/server/data/import/003.js +++ b/core/server/data/import/003.js @@ -5,4 +5,4 @@ module.exports = { importData: function (data) { return new Importer000.importData(data); } -}; \ No newline at end of file +}; diff --git a/core/server/data/import/index.js b/core/server/data/import/index.js index 823df50328..f4c534300d 100644 --- a/core/server/data/import/index.js +++ b/core/server/data/import/index.js @@ -44,7 +44,6 @@ cleanError = function cleanError(error) { return new errors.DataImportError(message, offendingProperty, value); }; - handleErrors = function handleErrors(errorList) { var processedErrors = []; @@ -67,11 +66,9 @@ handleErrors = function handleErrors(errorList) { }; sanitize = function sanitize(data) { - // Check for correct UUID and fix if neccessary _.each(_.keys(data.data), function (tableName) { _.each(data.data[tableName], function (importValues) { - var uuidMissing = (!importValues.uuid && tables[tableName].uuid) ? true : false, uuidMalformed = (importValues.uuid && !validator.isUUID(importValues.uuid)) ? true : false; diff --git a/core/server/data/import/utils.js b/core/server/data/import/utils.js index 6e5f1ca7f0..11e5a464ce 100644 --- a/core/server/data/import/utils.js +++ b/core/server/data/import/utils.js @@ -49,11 +49,11 @@ utils = { if (tableData[obj]) { // For each object in the tableData that matches _.each(tableData[obj], function (data) { - //console.log('checking ' + obj + ' ' + data.slug); + // console.log('checking ' + obj + ' ' + data.slug); // For each possible user foreign key _.each(userKeys, function (key) { if (_.has(data, key) && data[key] !== null) { - //console.log('found ' + key + ' with value ' + data[key]); + // console.log('found ' + key + ' with value ' + data[key]); userMap[data[key]] = {}; } }); @@ -105,23 +105,22 @@ utils = { var postTags, postsWithTags = {}; - postTags = tableData.posts_tags; - _.each(postTags, function (post_tag) { - if (!postsWithTags.hasOwnProperty(post_tag.post_id)) { - postsWithTags[post_tag.post_id] = []; + _.each(postTags, function (postTag) { + if (!postsWithTags.hasOwnProperty(postTag.post_id)) { + postsWithTags[postTag.post_id] = []; } - postsWithTags[post_tag.post_id].push(post_tag.tag_id); + postsWithTags[postTag.post_id].push(postTag.tag_id); }); - _.each(postsWithTags, function (tag_ids, post_id) { + _.each(postsWithTags, function (tagIds, postId) { var post, tags; post = _.find(tableData.posts, function (post) { - return post.id === parseInt(post_id, 10); + return post.id === parseInt(postId, 10); }); if (post) { tags = _.filter(tableData.tags, function (tag) { - return _.indexOf(tag_ids, tag.id) !== -1; + return _.indexOf(tagIds, tag.id) !== -1; }); post.tags = []; _.each(tags, function (tag) { @@ -136,13 +135,13 @@ utils = { }, preProcessRolesUsers: function preProcessRolesUsers(tableData) { - _.each(tableData.roles_users, function (role_user) { + _.each(tableData.roles_users, function (roleUser) { var user = _.find(tableData.users, function (user) { - return user.id === parseInt(role_user.user_id, 10); + return user.id === parseInt(roleUser.user_id, 10); }); // just the one role for now if (user && !user.roles) { - user.roles = [role_user.role_id]; + user.roles = [roleUser.role_id]; } }); @@ -265,10 +264,9 @@ utils = { datum.key = updatedSettingKeys[datum.key] || datum.key; }); - ops.push(models.Settings.edit(tableData, _.extend(internal, {transacting: transaction})) - .catch(function (error) { - return Promise.reject({raw: error, model: 'setting', data: tableData}); - })); + ops.push(models.Settings.edit(tableData, _.extend(internal, {transacting: transaction})).catch(function (error) { + return Promise.reject({raw: error, model: 'setting', data: tableData}); + })); return Promise.settle(ops); }, diff --git a/core/server/data/migration/commands.js b/core/server/data/migration/commands.js index 4d9afff7be..17a88250e8 100644 --- a/core/server/data/migration/commands.js +++ b/core/server/data/migration/commands.js @@ -3,7 +3,6 @@ var _ = require('lodash'), utils = require('../utils'), schema = require('../schema').tables, - // private logInfo, @@ -13,7 +12,6 @@ var _ = require('lodash'), addColumnCommands, modifyUniqueCommands; - logInfo = function logInfo(message) { errors.logInfo('Migrations', message); }; @@ -26,7 +24,6 @@ getDeleteCommands = function getDeleteCommands(oldTables, newTables) { return utils.deleteTable(table); }; }); - }; getAddCommands = function getAddCommands(oldTables, newTables) { var addTables = _.difference(newTables, oldTables); @@ -74,4 +71,4 @@ module.exports = { getAddCommands: getAddCommands, addColumnCommands: addColumnCommands, modifyUniqueCommands: modifyUniqueCommands -}; \ No newline at end of file +}; diff --git a/core/server/data/migration/index.js b/core/server/data/migration/index.js index 11bc2a4f79..93c7124749 100644 --- a/core/server/data/migration/index.js +++ b/core/server/data/migration/index.js @@ -118,11 +118,11 @@ reset = function () { migrateUpFreshDb = function (tablesOnly) { var tableSequence, tables = _.map(schemaTables, function (table) { - return function () { - logInfo('Creating table: ' + table); - return utils.createTable(table); - }; - }); + return function () { + logInfo('Creating table: ' + table); + return utils.createTable(table); + }; + }); logInfo('Creating tables...'); tableSequence = sequence(tables); @@ -168,7 +168,6 @@ migrateUp = function (fromVersion, toVersion) { }); }) ); - }).then(function () { migrateOps = migrateOps.concat(_.compact(modifyUniCommands)); diff --git a/core/server/data/schema.js b/core/server/data/schema.js index cad79aa250..d33780fa03 100644 --- a/core/server/data/schema.js +++ b/core/server/data/schema.js @@ -1,14 +1,14 @@ var db = { posts: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, title: {type: 'string', maxlength: 150, nullable: false}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, markdown: {type: 'text', maxlength: 16777215, fieldtype: 'medium', nullable: true}, html: {type: 'text', maxlength: 16777215, fieldtype: 'medium', nullable: true}, image: {type: 'text', maxlength: 2000, nullable: true}, - featured: {type: 'bool', nullable: false, defaultTo: false, validations: {'isIn': [[0, 1, false, true]]}}, - page: {type: 'bool', nullable: false, defaultTo: false, validations: {'isIn': [[0, 1, false, true]]}}, + featured: {type: 'bool', nullable: false, defaultTo: false, validations: {isIn: [[0, 1, false, true]]}}, + page: {type: 'bool', nullable: false, defaultTo: false, validations: {isIn: [[0, 1, false, true]]}}, status: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'draft'}, language: {type: 'string', maxlength: 6, nullable: false, defaultTo: 'en_US'}, meta_title: {type: 'string', maxlength: 150, nullable: true}, @@ -23,15 +23,15 @@ var db = { }, users: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, password: {type: 'string', maxlength: 60, nullable: false}, - email: {type: 'string', maxlength: 254, nullable: false, unique: true, validations: {'isEmail': true}}, + email: {type: 'string', maxlength: 254, nullable: false, unique: true, validations: {isEmail: true}}, image: {type: 'text', maxlength: 2000, nullable: true}, cover: {type: 'text', maxlength: 2000, nullable: true}, bio: {type: 'string', maxlength: 200, nullable: true}, - website: {type: 'text', maxlength: 2000, nullable: true, validations: {'isEmptyOrURL': true}}, + website: {type: 'text', maxlength: 2000, nullable: true, validations: {isEmptyOrURL: true}}, location: {type: 'text', maxlength: 65535, nullable: true}, accessibility: {type: 'text', maxlength: 65535, nullable: true}, status: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'active'}, @@ -46,7 +46,7 @@ var db = { }, roles: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false}, description: {type: 'string', maxlength: 200, nullable: true}, created_at: {type: 'dateTime', nullable: false}, @@ -61,7 +61,7 @@ var db = { }, permissions: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false}, object_type: {type: 'string', maxlength: 150, nullable: false}, action_type: {type: 'string', maxlength: 150, nullable: false}, @@ -88,10 +88,10 @@ var db = { }, settings: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, key: {type: 'string', maxlength: 150, nullable: false, unique: true}, value: {type: 'text', maxlength: 65535, nullable: true}, - type: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'core', validations: {'isIn': [['core', 'blog', 'theme', 'app', 'plugin']]}}, + type: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'core', validations: {isIn: [['core', 'blog', 'theme', 'app', 'plugin']]}}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, @@ -99,12 +99,12 @@ var db = { }, tags: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, description: {type: 'string', maxlength: 200, nullable: true}, image: {type: 'text', maxlength: 2000, nullable: true}, - hidden: {type: 'bool', nullable: false, defaultTo: false, validations: {'isIn': [[0, 1, false, true]]}}, + hidden: {type: 'bool', nullable: false, defaultTo: false, validations: {isIn: [[0, 1, false, true]]}}, parent_id: {type: 'integer', nullable: true}, meta_title: {type: 'string', maxlength: 150, nullable: true}, meta_description: {type: 'string', maxlength: 200, nullable: true}, @@ -120,7 +120,7 @@ var db = { }, apps: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, name: {type: 'string', maxlength: 150, nullable: false, unique: true}, slug: {type: 'string', maxlength: 150, nullable: false, unique: true}, version: {type: 'string', maxlength: 150, nullable: false}, @@ -132,7 +132,7 @@ var db = { }, app_settings: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, key: {type: 'string', maxlength: 150, nullable: false, unique: true}, value: {type: 'text', maxlength: 65535, nullable: true}, app_id: {type: 'integer', nullable: false, unsigned: true, references: 'apps.id'}, @@ -143,14 +143,14 @@ var db = { }, app_fields: { id: {type: 'increments', nullable: false, primary: true}, - uuid: {type: 'string', maxlength: 36, nullable: false, validations: {'isUUID': true}}, + uuid: {type: 'string', maxlength: 36, nullable: false, validations: {isUUID: true}}, key: {type: 'string', maxlength: 150, nullable: false}, value: {type: 'text', maxlength: 65535, nullable: true}, type: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'html'}, app_id: {type: 'integer', nullable: false, unsigned: true, references: 'apps.id'}, relatable_id: {type: 'integer', nullable: false, unsigned: true}, relatable_type: {type: 'string', maxlength: 150, nullable: false, defaultTo: 'posts'}, - active: {type: 'bool', nullable: false, defaultTo: true, validations: {'isIn': [[0, 1, false, true]]}}, + active: {type: 'bool', nullable: false, defaultTo: true, validations: {isIn: [[0, 1, false, true]]}}, created_at: {type: 'dateTime', nullable: false}, created_by: {type: 'integer', nullable: false}, updated_at: {type: 'dateTime', nullable: true}, diff --git a/core/server/data/utils/clients/index.js b/core/server/data/utils/clients/index.js index fbc5e90031..8c8df7ca6a 100644 --- a/core/server/data/utils/clients/index.js +++ b/core/server/data/utils/clients/index.js @@ -2,7 +2,6 @@ var sqlite3 = require('./sqlite3'), mysql = require('./mysql'), pg = require('./pg'); - module.exports = { sqlite3: sqlite3, mysql: mysql, diff --git a/core/server/data/utils/clients/mysql.js b/core/server/data/utils/clients/mysql.js index 4076bd3c7c..f336d6117e 100644 --- a/core/server/data/utils/clients/mysql.js +++ b/core/server/data/utils/clients/mysql.js @@ -1,7 +1,7 @@ var _ = require('lodash'), config = require('../../../config/index'), - //private + // private doRawAndFlatten, // public diff --git a/core/server/data/utils/clients/pg.js b/core/server/data/utils/clients/pg.js index 4c1b8baa92..15992baa17 100644 --- a/core/server/data/utils/clients/pg.js +++ b/core/server/data/utils/clients/pg.js @@ -9,7 +9,6 @@ var _ = require('lodash'), getIndexes, getColumns; - doRawFlattenAndPluck = function doRaw(query, name) { return config.database.knex.raw(query).then(function (response) { return _.flatten(_.pluck(response.rows, name)); @@ -41,4 +40,4 @@ module.exports = { getTables: getTables, getIndexes: getIndexes, getColumns: getColumns -}; \ No newline at end of file +}; diff --git a/core/server/data/utils/clients/sqlite3.js b/core/server/data/utils/clients/sqlite3.js index a24738ddcb..09806966e9 100644 --- a/core/server/data/utils/clients/sqlite3.js +++ b/core/server/data/utils/clients/sqlite3.js @@ -1,7 +1,7 @@ var _ = require('lodash'), config = require('../../../config/index'), - //private + // private doRaw, // public @@ -9,7 +9,6 @@ var _ = require('lodash'), getIndexes, getColumns; - doRaw = function doRaw(query, fn) { return config.database.knex.raw(query).then(function (response) { return fn(response); @@ -40,4 +39,4 @@ module.exports = { getTables: getTables, getIndexes: getIndexes, getColumns: getColumns -}; \ No newline at end of file +}; diff --git a/core/server/data/utils/index.js b/core/server/data/utils/index.js index 48ae15871c..f703508843 100644 --- a/core/server/data/utils/index.js +++ b/core/server/data/utils/index.js @@ -6,7 +6,6 @@ var _ = require('lodash'), dbConfig; - function addTableColumn(tablename, table, columnname) { var column, columnSpec = schema[tablename][columnname]; @@ -35,7 +34,7 @@ function addTableColumn(tablename, table, columnname) { column.unsigned(); } if (columnSpec.hasOwnProperty('references')) { - //check if table exists? + // check if table exists? column.references(columnSpec.references); } if (columnSpec.hasOwnProperty('defaultTo')) { @@ -131,4 +130,4 @@ module.exports = { dropUnique: dropUnique, addColumn: addColumn, getColumns: getColumns -}; \ No newline at end of file +}; diff --git a/core/server/data/validation/index.js b/core/server/data/validation/index.js index 90e72eb8b2..b3c239de55 100644 --- a/core/server/data/validation/index.js +++ b/core/server/data/validation/index.js @@ -24,7 +24,7 @@ validator.extend('notContains', function (str, badString) { }); validator.extend('isEmptyOrURL', function (str) { - return (_.isEmpty(str) || validator.isURL(str, { require_protocol: false })); + return (_.isEmpty(str) || validator.isURL(str, {require_protocol: false})); }); // Validation validation against schema attributes @@ -57,12 +57,12 @@ validateSchema = function (tableName, model) { } } - //check validations objects + // check validations objects if (schema[tableName][columnKey].hasOwnProperty('validations'))Â { validationErrors = validationErrors.concat(validate(model[columnKey], columnKey, schema[tableName][columnKey].validations)); } - //check type + // check type if (schema[tableName][columnKey].hasOwnProperty('type'))Â { if (schema[tableName][columnKey].type === 'integer' && !validator.isInt(model[columnKey])) { message = 'Value in [' + tableName + '.' + columnKey + '] is not an integer.'; diff --git a/core/server/data/versioning/index.js b/core/server/data/versioning/index.js index eb4a88420b..4b373fa18b 100644 --- a/core/server/data/versioning/index.js +++ b/core/server/data/versioning/index.js @@ -56,11 +56,11 @@ function getDatabaseVersion() { function setDatabaseVersion() { return config.database.knex('settings') .where('key', 'databaseVersion') - .update({ 'value': defaultDatabaseVersion }); + .update({value: defaultDatabaseVersion}); } module.exports = { getDefaultDatabaseVersion: getDefaultDatabaseVersion, getDatabaseVersion: getDatabaseVersion, setDatabaseVersion: setDatabaseVersion -}; \ No newline at end of file +}; diff --git a/core/server/errors/badrequesterror.js b/core/server/errors/badrequesterror.js index 12401f03e0..de4ae8d442 100644 --- a/core/server/errors/badrequesterror.js +++ b/core/server/errors/badrequesterror.js @@ -11,5 +11,4 @@ function BadRequestError(message) { BadRequestError.prototype = Object.create(Error.prototype); BadRequestError.prototype.name = 'BadRequestError'; - -module.exports = BadRequestError; \ No newline at end of file +module.exports = BadRequestError; diff --git a/core/server/errors/dataimporterror.js b/core/server/errors/dataimporterror.js index a67aa4646b..79df9da2f4 100644 --- a/core/server/errors/dataimporterror.js +++ b/core/server/errors/dataimporterror.js @@ -13,5 +13,4 @@ function DataImportError(message, offendingProperty, value) { DataImportError.prototype = Object.create(Error.prototype); DataImportError.prototype.name = 'DataImportError'; - -module.exports = DataImportError; \ No newline at end of file +module.exports = DataImportError; diff --git a/core/server/errors/emailerror.js b/core/server/errors/emailerror.js index e8053863db..a050a9d44c 100644 --- a/core/server/errors/emailerror.js +++ b/core/server/errors/emailerror.js @@ -11,5 +11,4 @@ function EmailError(message) { EmailError.prototype = Object.create(Error.prototype); EmailError.prototype.name = 'EmailError'; - -module.exports = EmailError; \ No newline at end of file +module.exports = EmailError; diff --git a/core/server/errors/index.js b/core/server/errors/index.js index 52f687f5cc..2f6fbc91ce 100644 --- a/core/server/errors/index.js +++ b/core/server/errors/index.js @@ -63,7 +63,6 @@ errors = { if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'staging' || process.env.NODE_ENV === 'production')) { - var msg = [component.cyan + ':'.cyan, info.cyan]; console.info.apply(console, msg); @@ -74,7 +73,6 @@ errors = { if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'staging' || process.env.NODE_ENV === 'production')) { - var msgs = ['\nWarning:'.yellow, warn.yellow, '\n']; if (context) { @@ -109,19 +107,18 @@ errors = { stack = err ? err.stack : null; err = _.isString(err) ? err : (_.isObject(err) ? err.message : 'An unknown error occurred.'); - + // Overwrite error to provide information that this is probably a permission problem // TODO: https://github.com/TryGhost/Ghost/issues/3687 if (err.indexOf('SQLITE_READONLY') !== -1) { - context = "Your database is in read only mode. Visitors can read your blog, but you can't log in or add posts."; - help = "Check your database file and make sure that file owner and permissions are correct."; + context = 'Your database is in read only mode. Visitors can read your blog, but you can\'t log in or add posts.'; + help = 'Check your database file and make sure that file owner and permissions are correct.'; } // TODO: Logging framework hookup // Eventually we'll have better logging which will know about envs if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'staging' || process.env.NODE_ENV === 'production')) { - msgs = ['\nERROR:'.red, err.red, '\n']; if (context) { @@ -216,8 +213,8 @@ errors = { } return { - 'function': parts[1], - 'at': parts[2] + function: parts[1], + at: parts[2] }; }) .filter(function (line) { diff --git a/core/server/errors/internalservererror.js b/core/server/errors/internalservererror.js index 67c4eaf3bf..25fb2f966a 100644 --- a/core/server/errors/internalservererror.js +++ b/core/server/errors/internalservererror.js @@ -11,5 +11,4 @@ function InternalServerError(message) { InternalServerError.prototype = Object.create(Error.prototype); InternalServerError.prototype.name = 'InternalServerError'; - -module.exports = InternalServerError; \ No newline at end of file +module.exports = InternalServerError; diff --git a/core/server/errors/nopermissionerror.js b/core/server/errors/nopermissionerror.js index d9bd5aac2a..48619abed4 100644 --- a/core/server/errors/nopermissionerror.js +++ b/core/server/errors/nopermissionerror.js @@ -11,5 +11,4 @@ function NoPermissionError(message) { NoPermissionError.prototype = Object.create(Error.prototype); NoPermissionError.prototype.name = 'NoPermissionError'; - -module.exports = NoPermissionError; \ No newline at end of file +module.exports = NoPermissionError; diff --git a/core/server/errors/notfounderror.js b/core/server/errors/notfounderror.js index c216a3a99a..fd0bee97d1 100644 --- a/core/server/errors/notfounderror.js +++ b/core/server/errors/notfounderror.js @@ -11,5 +11,4 @@ function NotFoundError(message) { NotFoundError.prototype = Object.create(Error.prototype); NotFoundError.prototype.name = 'NotFoundError'; - -module.exports = NotFoundError; \ No newline at end of file +module.exports = NotFoundError; diff --git a/core/server/errors/requesttoolargeerror.js b/core/server/errors/requesttoolargeerror.js index c8326c1033..eb3215d983 100644 --- a/core/server/errors/requesttoolargeerror.js +++ b/core/server/errors/requesttoolargeerror.js @@ -11,5 +11,4 @@ function RequestEntityTooLargeError(message) { RequestEntityTooLargeError.prototype = Object.create(Error.prototype); RequestEntityTooLargeError.prototype.name = 'RequestEntityTooLargeError'; - -module.exports = RequestEntityTooLargeError; \ No newline at end of file +module.exports = RequestEntityTooLargeError; diff --git a/core/server/errors/unauthorizederror.js b/core/server/errors/unauthorizederror.js index 666e35e803..b480118df4 100644 --- a/core/server/errors/unauthorizederror.js +++ b/core/server/errors/unauthorizederror.js @@ -11,5 +11,4 @@ function UnauthorizedError(message) { UnauthorizedError.prototype = Object.create(Error.prototype); UnauthorizedError.prototype.name = 'UnauthorizedError'; - -module.exports = UnauthorizedError; \ No newline at end of file +module.exports = UnauthorizedError; diff --git a/core/server/errors/unsupportedmediaerror.js b/core/server/errors/unsupportedmediaerror.js index 18c740ce3e..405b6f1c9f 100644 --- a/core/server/errors/unsupportedmediaerror.js +++ b/core/server/errors/unsupportedmediaerror.js @@ -11,5 +11,4 @@ function UnsupportedMediaTypeError(message) { UnsupportedMediaTypeError.prototype = Object.create(Error.prototype); UnsupportedMediaTypeError.prototype.name = 'UnsupportedMediaTypeError'; - -module.exports = UnsupportedMediaTypeError; \ No newline at end of file +module.exports = UnsupportedMediaTypeError; diff --git a/core/server/errors/validationerror.js b/core/server/errors/validationerror.js index 779b65e0f1..2fde6a8070 100644 --- a/core/server/errors/validationerror.js +++ b/core/server/errors/validationerror.js @@ -14,5 +14,4 @@ function ValidationError(message, offendingProperty) { ValidationError.prototype = Object.create(Error.prototype); ValidationError.prototype.name = 'ValidationError'; - module.exports = ValidationError; diff --git a/core/server/filters.js b/core/server/filters.js index ac91fc18d0..ea5697618f 100644 --- a/core/server/filters.js +++ b/core/server/filters.js @@ -13,13 +13,13 @@ defaults = { maxPriority: 9 }; -var Filters = function () { +function Filters() { // Holds the filters this.filterCallbacks = []; // Holds the filter hooks (that are built in to Ghost Core) this.filters = []; -}; +} // Register a new filter callback function Filters.prototype.registerFilter = function (name, priority, fn) { diff --git a/core/server/helpers/index.js b/core/server/helpers/index.js index c536c81738..ae6c346b87 100644 --- a/core/server/helpers/index.js +++ b/core/server/helpers/index.js @@ -22,7 +22,7 @@ var downsize = require('downsize'), scriptFiles = { production: [ 'vendor.min.js', - 'ghost.min.js', + 'ghost.min.js' ], development: [ 'vendor-dev.js', @@ -60,7 +60,6 @@ coreHelpers.date = function (context, options) { timeago = options.hash.timeago, date; - if (timeago) { date = moment(context).fromNow(); } else { @@ -154,7 +153,6 @@ coreHelpers.url = function (options) { return Promise.resolve(config.urlFor('author', {author: this}, absolute)); } - return Promise.resolve(config.urlFor(this, absolute)); }; @@ -291,7 +289,6 @@ coreHelpers.content = function (options) { }); if (truncateOptions.hasOwnProperty('words') || truncateOptions.hasOwnProperty('characters')) { - // Legacy function: {{content words="0"}} should return leading tags. if (truncateOptions.hasOwnProperty('words') && truncateOptions.words === 0) { return new hbs.handlebars.SafeString( @@ -314,7 +311,7 @@ coreHelpers.content = function (options) { }; coreHelpers.title = function () { - return new hbs.handlebars.SafeString(hbs.handlebars.Utils.escapeExpression(this.title || '')); + return new hbs.handlebars.SafeString(hbs.handlebars.Utils.escapeExpression(this.title || '')); }; // ### Excerpt Helper @@ -416,7 +413,6 @@ coreHelpers.body_class = function (options) { tags = this.post && this.post.tags ? this.post.tags : this.tags || [], page = this.post && this.post.page ? this.post.page : this.page || false; - if (this.tag !== undefined) { classes.push('tag-template'); classes.push('tag-' + this.tag.slug); @@ -431,7 +427,6 @@ coreHelpers.body_class = function (options) { classes.push('paged'); // To be removed from pages by #2597 when we're ready to deprecate this classes.push('archive-template'); - } else if (!this.relativeUrl || this.relativeUrl === '/' || this.relativeUrl === '') { classes.push('home-template'); } else if (post) { @@ -653,7 +648,7 @@ coreHelpers.foreach = function (context, options) { data.first = data.rowEnd = data.rowStart = data.last = data.even = data.odd = false; data = setKeys(data, i, j, columns); } - ret = ret + fn(context[i], { data: data }); + ret = ret + fn(context[i], {data: data}); } } else { for (key in context) { @@ -785,9 +780,9 @@ coreHelpers.plural = function (context, options) { if (context === 0) { return new hbs.handlebars.SafeString(options.hash.empty); } else if (context === 1) { - return new hbs.handlebars.SafeString(options.hash.singular.replace("%", context)); + return new hbs.handlebars.SafeString(options.hash.singular.replace('%', context)); } else if (context >= 2) { - return new hbs.handlebars.SafeString(options.hash.plural.replace("%", context)); + return new hbs.handlebars.SafeString(options.hash.plural.replace('%', context)); } }; @@ -836,17 +831,13 @@ function registerAdminHelper(name, fn) { coreHelpers.adminHbs.registerHelper(name, fn); } - - registerHelpers = function (adminHbs, assetHash) { - // Expose hbs instance for admin coreHelpers.adminHbs = adminHbs; // Store hash for assets coreHelpers.assetHash = assetHash; - // Register theme helpers registerThemeHelper('asset', coreHelpers.asset); @@ -892,7 +883,6 @@ registerHelpers = function (adminHbs, assetHash) { registerAsyncThemeHelper('url', coreHelpers.url); - // Register admin helpers registerAdminHelper('ghost_script_tags', coreHelpers.ghost_script_tags); diff --git a/core/server/helpers/template.js b/core/server/helpers/template.js index a508f2960d..676d3eff13 100644 --- a/core/server/helpers/template.js +++ b/core/server/helpers/template.js @@ -7,7 +7,6 @@ var templates = {}, // Execute a template helper // All template helpers are register as partial view. templates.execute = function (name, context) { - var partial = hbs.handlebars.partials[name]; if (partial === undefined) { @@ -66,4 +65,4 @@ templates.getThemeViewForTag = function (themePaths, tag) { return view; }; -module.exports = templates; \ No newline at end of file +module.exports = templates; diff --git a/core/server/index.js b/core/server/index.js index ba799a3c51..a9535f890c 100644 --- a/core/server/index.js +++ b/core/server/index.js @@ -36,10 +36,10 @@ function doFirstRun() { 'See http://support.ghost.org for instructions.' ]; - return api.notifications.add({ notifications: [{ + return api.notifications.add({notifications: [{ type: 'info', message: firstRunMessage.join(' ') - }] }, {context: {internal: true}}); + }]}, {context: {internal: true}}); } function initDbHashAndFirstRun() { @@ -73,9 +73,9 @@ function builtFilesExist() { helpers.scriptFiles.production : helpers.scriptFiles.development; function checkExist(fileName) { - var errorMessage = "Javascript files have not been built.", - errorHelp = "\nPlease read the getting started instructions at:" + - "\nhttps://github.com/TryGhost/Ghost#getting-started-guide-for-developers"; + var errorMessage = 'Javascript files have not been built.', + errorHelp = '\nPlease read the getting started instructions at:' + + '\nhttps://github.com/TryGhost/Ghost#getting-started-guide-for-developers'; return new Promise(function (resolve, reject) { fs.exists(fileName, function (exists) { @@ -105,23 +105,23 @@ function builtFilesExist() { // in the future apps will want to hook into here function initNotifications() { if (mailer.state && mailer.state.usingDirect) { - api.notifications.add({ notifications: [{ + api.notifications.add({notifications: [{ type: 'info', message: [ - "Ghost is attempting to use a direct method to send e-mail.", - "It is recommended that you explicitly configure an e-mail service.", - "See http://support.ghost.org/mail for instructions" + 'Ghost is attempting to use a direct method to send e-mail.', + 'It is recommended that you explicitly configure an e-mail service.', + 'See http://support.ghost.org/mail for instructions' ].join(' ') - }] }, {context: {internal: true}}); + }]}, {context: {internal: true}}); } if (mailer.state && mailer.state.emailDisabled) { - api.notifications.add({ notifications: [{ + api.notifications.add({notifications: [{ type: 'warn', message: [ - "Ghost is currently unable to send e-mail.", - "See http://support.ghost.org/mail for instructions" + 'Ghost is currently unable to send e-mail.', + 'See http://support.ghost.org/mail for instructions' ].join(' ') - }] }, {context: {internal: true}}); + }]}, {context: {internal: true}}); } } diff --git a/core/server/mail.js b/core/server/mail.js index 7ac2491cbb..4ac91aadc0 100644 --- a/core/server/mail.js +++ b/core/server/mail.js @@ -28,7 +28,6 @@ GhostMailer.prototype.createTransport = function () { this.transport = nodemailer.createTransport(config.mail.transport, _.clone(config.mail.options) || {}); }; - GhostMailer.prototype.fromAddress = function () { var from = config.mail && config.mail.fromaddress, domain; @@ -79,21 +78,21 @@ GhostMailer.prototype.send = function (message) { return resolve(response); } - response.statusHandler.once("failed", function (data) { + response.statusHandler.once('failed', function (data) { var reason = 'Email Error: Failed sending email'; - if (data.error.errno === "ENOTFOUND") { + if (data.error.errno === 'ENOTFOUND') { reason += ': there is no mail server at this address: ' + data.domain; } reason += '.'; return reject(new Error(reason)); }); - response.statusHandler.once("requeue", function (data) { - return reject(new Error("Email Error: message was not sent, requeued. Probably will not be sent. :( \nMore info: " + data.error.message)); + response.statusHandler.once('requeue', function (data) { + return reject(new Error('Email Error: message was not sent, requeued. Probably will not be sent. :( \nMore info: ' + data.error.message)); }); - response.statusHandler.once("sent", function () { - return resolve("Message was accepted by the mail server. Make sure to check inbox and spam folders. :)"); + response.statusHandler.once('sent', function () { + return resolve('Message was accepted by the mail server. Make sure to check inbox and spam folders. :)'); }); }); }); diff --git a/core/server/middleware/authStrategies.js b/core/server/middleware/authStrategies.js index 484a6b0cd1..cec441f145 100644 --- a/core/server/middleware/authStrategies.js +++ b/core/server/middleware/authStrategies.js @@ -50,7 +50,7 @@ passport.use(new BearerStrategy( .then(function (model) { if (model) { var user = model.toJSON(), - info = { scope: '*' }; + info = {scope: '*'}; return done(null, {id: user.id}, info); } return done(null, false); @@ -64,4 +64,3 @@ passport.use(new BearerStrategy( }); } )); - diff --git a/core/server/middleware/ghost-busboy.js b/core/server/middleware/ghost-busboy.js index dccba7511d..110860e9d1 100644 --- a/core/server/middleware/ghost-busboy.js +++ b/core/server/middleware/ghost-busboy.js @@ -16,7 +16,7 @@ function ghostBusBoy(req, res, next) { return next(); } - busboy = new BusBoy({ headers: req.headers }); + busboy = new BusBoy({headers: req.headers}); tmpDir = os.tmpdir(); req.files = req.files || {}; @@ -59,7 +59,6 @@ function ghostBusBoy(req, res, next) { }); file.pipe(stream); - }); busboy.on('error', function (error) { @@ -78,4 +77,4 @@ function ghostBusBoy(req, res, next) { req.pipe(busboy); } -module.exports = ghostBusBoy; \ No newline at end of file +module.exports = ghostBusBoy; diff --git a/core/server/middleware/index.js b/core/server/middleware/index.js index c58937d372..ad6e4b2c63 100644 --- a/core/server/middleware/index.js +++ b/core/server/middleware/index.js @@ -63,7 +63,7 @@ function activateTheme(activeTheme) { expressServer.cache = {}; // set view engine - hbsOptions = { partialsDir: [ config.paths.helperTemplates ] }; + hbsOptions = {partialsDir: [config.paths.helperTemplates]}; fs.stat(themePartials, function (err, stats) { // Check that the theme has a partials directory before trying to use it @@ -98,7 +98,7 @@ function configHbsForContext(req, res, next) { } else { expressServer.disable('admin'); var themeData = initThemeData(req.secure); - hbs.updateTemplateOptions({ data: {blog: themeData} }); + hbs.updateTemplateOptions({data: {blog: themeData}}); expressServer.engine('hbs', expressServer.get('theme view engine')); expressServer.set('views', path.join(config.paths.themePath, expressServer.get('activeTheme'))); } @@ -161,7 +161,7 @@ function uncapitalise(req, res, next) { if (isSignupOrReset) { pathToTest = isSignupOrReset[1]; } - + // Do not lowercase anything after /api/v0.1/ to protect :key/:slug if (isAPI) { pathToTest = isAPI[1]; @@ -218,7 +218,7 @@ function robots() { filePath = path.join(config.paths.corePath, '/shared/robots.txt'); return function robots(req, res, next) { - if ('/robots.txt' === req.url) { + if (req.url === '/robots.txt') { if (content) { res.writeHead(200, content.headers); res.end(content.body); @@ -314,7 +314,7 @@ setupMiddleware = function (server) { // Body parsing expressServer.use(bodyParser.json()); - expressServer.use(bodyParser.urlencoded({ extended: true })); + expressServer.use(bodyParser.urlencoded({extended: true})); expressServer.use(passport.initialize()); @@ -322,7 +322,6 @@ setupMiddleware = function (server) { expressServer.use(middleware.cacheControl('public')); expressServer.use('/ghost/', middleware.cacheControl('private')); - // enable authentication expressServer.use(middleware.authenticate); diff --git a/core/server/middleware/middleware.js b/core/server/middleware/middleware.js index 5775eaae6a..6d7b250028 100644 --- a/core/server/middleware/middleware.js +++ b/core/server/middleware/middleware.js @@ -12,6 +12,7 @@ var _ = require('lodash'), errors = require('../errors'), utils = require('../utils'), + middleware, expressServer, oauthServer, loginSecurity = [], @@ -31,7 +32,7 @@ function cacheOauthServer(server) { oauthServer = server; } -var middleware = { +middleware = { // ### Authenticate Middleware // authentication has to be done for /ghost/* routes with @@ -52,14 +53,13 @@ var middleware = { if (res.isAdmin) { if (subPath.indexOf('/ghost/api/') === 0 && path.indexOf('/ghost/api/v0.1/authentication/') !== 0) { - - return passport.authenticate('bearer', { session: false, failWithError: true }, + return passport.authenticate('bearer', {session: false, failWithError: true}, function (err, user, info) { if (err) { return next(err); // will generate a 500 error } // Generate a JSON response reflecting authentication status - if (! user) { + if (!user) { var msg = { type: 'error', message: 'Please Sign In', @@ -84,8 +84,8 @@ var middleware = { 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' + public: 'public, max-age=0', + private: 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0' }, output; @@ -212,8 +212,6 @@ var middleware = { deniedEmailRateLimit = (forgottenSecurity[index].count > rateForgottenAttempts); } - - if (deniedEmailRateLimit) { errors.logError( 'Only ' + rateForgottenAttempts + ' forgotten password attempts per email every ' + @@ -254,7 +252,7 @@ var middleware = { // ### Authenticate Client Middleware // authenticate client that is asking for an access token authenticateClient: function (req, res, next) { - return passport.authenticate(['oauth2-client-password'], { session: false })(req, res, next); + return passport.authenticate(['oauth2-client-password'], {session: false})(req, res, next); }, // ### Generate access token Middleware diff --git a/core/server/middleware/oauth.js b/core/server/middleware/oauth.js index 50f36061f3..d284532432 100644 --- a/core/server/middleware/oauth.js +++ b/core/server/middleware/oauth.js @@ -5,11 +5,9 @@ var oauth2orize = require('oauth2orize'), oauth; - oauth = { init: function (oauthServer, resetSpamCounter) { - // remove all expired accesstokens on startup models.Accesstoken.destroyAllExpired(); @@ -30,8 +28,7 @@ oauth = { } // Validate the user return models.User.check({email: username, password: password}).then(function (user) { - - //Everything validated, return the access- and refreshtoken + // Everything validated, return the access- and refreshtoken var accessToken = utils.uid(256), refreshToken = utils.uid(256), accessExpires = Date.now() + utils.ONE_HOUR_MS, @@ -53,7 +50,7 @@ oauth = { // Exchange the refresh token to obtain an access token. The callback accepts the // `client`, which is exchanging a `refreshToken` previously issued by the server - // for verification. If these values are validated, the application issues an + // 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) { models.Refreshtoken.forge({token: refreshToken}) @@ -89,4 +86,4 @@ oauth = { } }; -module.exports = oauth; \ No newline at end of file +module.exports = oauth; diff --git a/core/server/models/accesstoken.js b/core/server/models/accesstoken.js index d9559aca46..b18f1160d5 100644 --- a/core/server/models/accesstoken.js +++ b/core/server/models/accesstoken.js @@ -15,4 +15,4 @@ Accesstokens = ghostBookshelf.Collection.extend({ module.exports = { Accesstoken: ghostBookshelf.model('Accesstoken', Accesstoken), Accesstokens: ghostBookshelf.collection('Accesstokens', Accesstokens) -}; \ No newline at end of file +}; diff --git a/core/server/models/app.js b/core/server/models/app.js index 91036f6da7..085e28b64b 100644 --- a/core/server/models/app.js +++ b/core/server/models/app.js @@ -2,8 +2,6 @@ var ghostBookshelf = require('./base'), App, Apps; - - App = ghostBookshelf.Model.extend({ tableName: 'apps', diff --git a/core/server/models/appField.js b/core/server/models/appField.js index ee23a4dc05..8d84e7b1dd 100644 --- a/core/server/models/appField.js +++ b/core/server/models/appField.js @@ -17,4 +17,4 @@ AppFields = ghostBookshelf.Collection.extend({ module.exports = { AppField: ghostBookshelf.model('AppField', AppField), AppFields: ghostBookshelf.collection('AppFields', AppFields) -}; \ No newline at end of file +}; diff --git a/core/server/models/appSetting.js b/core/server/models/appSetting.js index ec1fac4328..8d4289215b 100644 --- a/core/server/models/appSetting.js +++ b/core/server/models/appSetting.js @@ -17,4 +17,4 @@ AppSettings = ghostBookshelf.Collection.extend({ module.exports = { AppSetting: ghostBookshelf.model('AppSetting', AppSetting), AppSettings: ghostBookshelf.collection('AppSettings', AppSettings) -}; \ No newline at end of file +}; diff --git a/core/server/models/base.js b/core/server/models/base.js index 2a4c796aaa..b4cb9dc975 100644 --- a/core/server/models/base.js +++ b/core/server/models/base.js @@ -319,7 +319,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ checkIfSlugExists = function (slugToFind) { var args = {slug: slugToFind}; - //status is needed for posts + // status is needed for posts if (options && options.status) { args.status = options.status; } @@ -356,7 +356,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ slug = /^(ghost|ghost\-admin|admin|wp\-admin|wp\-login|dashboard|logout|login|setup|signin|signup|signout|register|archive|archives|category|categories|tag|tags|page|pages|post|posts|public|user|users|rss|feed|app|apps)$/g .test(slug) ? slug + '-' + baseName : slug; - //if slug is empty after trimming use the model name + // if slug is empty after trimming use the model name if (!slug) { slug = baseName; } diff --git a/core/server/models/basetoken.js b/core/server/models/basetoken.js index dc5bdcd40d..fa98807918 100644 --- a/core/server/models/basetoken.js +++ b/core/server/models/basetoken.js @@ -78,7 +78,7 @@ Basetoken = ghostBookshelf.Model.extend({ } return Promise.reject(new errors.NotFoundError('Token not found')); - }, + } }); -module.exports = Basetoken; \ No newline at end of file +module.exports = Basetoken; diff --git a/core/server/models/client.js b/core/server/models/client.js index 11255d0eac..ac880d803b 100644 --- a/core/server/models/client.js +++ b/core/server/models/client.js @@ -3,7 +3,6 @@ var ghostBookshelf = require('./base'), Client, Clients; - Client = ghostBookshelf.Model.extend({ tableName: 'clients' }); @@ -15,4 +14,4 @@ Clients = ghostBookshelf.Collection.extend({ module.exports = { Client: ghostBookshelf.model('Client', Client), Clients: ghostBookshelf.collection('Clients', Clients) -}; \ No newline at end of file +}; diff --git a/core/server/models/index.js b/core/server/models/index.js index dcd1bf6006..757154f809 100644 --- a/core/server/models/index.js +++ b/core/server/models/index.js @@ -20,11 +20,9 @@ models = { // Require all files in this directory return requireTree.readAll(__dirname).then(function (modelFiles) { - // For each found file, excluding those we don't want, // we will require it and cache it here. _.each(modelFiles, function (path, fileName) { - // Return early if this fileName is one of the ones we want // to exclude. if (_.contains(self.excludeFiles, fileName)) { @@ -36,7 +34,6 @@ models = { // Cache its `export` object onto this object. _.extend(self, file); - }); return; diff --git a/core/server/models/post.js b/core/server/models/post.js index 3cf540532b..ae1ae4d7ce 100644 --- a/core/server/models/post.js +++ b/core/server/models/post.js @@ -62,7 +62,7 @@ Post = ghostBookshelf.Model.extend({ this.set('html', converter.makeHtml(this.get('markdown'))); // disabling sanitization until we can implement a better version - //this.set('title', this.sanitize('title').trim()); + // this.set('title', this.sanitize('title').trim()); this.set('title', this.get('title').trim()); if ((this.hasChanged('status') || !this.get('published_at')) && this.get('status') === 'published') { @@ -83,7 +83,6 @@ Post = ghostBookshelf.Model.extend({ self.set({slug: slug}); }); } - }, creating: function (newPage, attr, options) { @@ -244,16 +243,15 @@ Post = ghostBookshelf.Model.extend({ /** * ### Find All * - * @param options + * @param {Object} options * @returns {*} */ findAll: function (options) { options = options || {}; - options.withRelated = _.union([ 'tags', 'fields' ], options.include); + options.withRelated = _.union(['tags', 'fields'], options.include); return ghostBookshelf.Model.findAll.call(this, options); }, - /** * #### findPage * Find results by page - returns an object containing the @@ -272,7 +270,7 @@ Post = ghostBookshelf.Model.extend({ * total: __ * } * - * @params {Object} options + * @param {Object} options */ findPage: function (options) { options = options || {}; @@ -323,7 +321,7 @@ Post = ghostBookshelf.Model.extend({ } // Add related objects - options.withRelated = _.union([ 'tags', 'fields' ], options.include); + options.withRelated = _.union(['tags', 'fields'], options.include); // If a query param for a tag is attached // we need to fetch the tag model to find its id @@ -468,7 +466,7 @@ Post = ghostBookshelf.Model.extend({ } // Add related objects - options.withRelated = _.union([ 'tags', 'fields' ], options.include); + options.withRelated = _.union(['tags', 'fields'], options.include); return ghostBookshelf.Model.findOne.call(this, data, options); }, @@ -524,7 +522,6 @@ Post = ghostBookshelf.Model.extend({ }); }, - /** * ### destroyByAuthor * @param {[type]} options has context and id. Context is the user doing the destroy, id is the user to destroy @@ -548,7 +545,6 @@ Post = ghostBookshelf.Model.extend({ return Promise.reject(new errors.NotFoundError('No user found')); }, - permissible: function (postModelOrId, action, context, loadedPermissions, hasUserPermission, hasAppPermission) { var self = this, postModel = postModelOrId, diff --git a/core/server/models/refreshtoken.js b/core/server/models/refreshtoken.js index e8d55325b2..03ede041de 100644 --- a/core/server/models/refreshtoken.js +++ b/core/server/models/refreshtoken.js @@ -15,4 +15,4 @@ Refreshtokens = ghostBookshelf.Collection.extend({ module.exports = { Refreshtoken: ghostBookshelf.model('Refreshtoken', Refreshtoken), Refreshtokens: ghostBookshelf.collection('Refreshtokens', Refreshtokens) -}; \ No newline at end of file +}; diff --git a/core/server/models/role.js b/core/server/models/role.js index d1b5a96335..c2b7b53d48 100644 --- a/core/server/models/role.js +++ b/core/server/models/role.js @@ -39,7 +39,6 @@ Role = ghostBookshelf.Model.extend({ return options; }, - permissible: function (roleModelOrId, action, context, loadedPermissions, hasUserPermission, hasAppPermission) { var self = this, checkAgainst = [], @@ -60,11 +59,11 @@ Role = ghostBookshelf.Model.extend({ } if (action === 'assign' && loadedPermissions.user) { - if (_.any(loadedPermissions.user.roles, { 'name': 'Owner' })) { + if (_.any(loadedPermissions.user.roles, {name: 'Owner'})) { checkAgainst = ['Owner', 'Administrator', 'Editor', 'Author']; - } else if (_.any(loadedPermissions.user.roles, { 'name': 'Administrator' })) { + } else if (_.any(loadedPermissions.user.roles, {name: 'Administrator'})) { checkAgainst = ['Administrator', 'Editor', 'Author']; - } else if (_.any(loadedPermissions.user.roles, { 'name': 'Editor' })) { + } else if (_.any(loadedPermissions.user.roles, {name: 'Editor'})) { checkAgainst = ['Author']; } diff --git a/core/server/models/settings.js b/core/server/models/settings.js index 051e3bd26f..a101fc5325 100644 --- a/core/server/models/settings.js +++ b/core/server/models/settings.js @@ -80,7 +80,7 @@ Settings = ghostBookshelf.Model.extend({ findOne: function (options) { // Allow for just passing the key instead of attributes if (!_.isObject(options)) { - options = { key: options }; + options = {key: options}; } return Promise.resolve(ghostBookshelf.Model.findOne.call(this, options)); }, @@ -102,14 +102,12 @@ Settings = ghostBookshelf.Model.extend({ item = self.filterData(item); - return Settings.forge({ key: item.key }).fetch(options).then(function (setting) { - + return Settings.forge({key: item.key}).fetch(options).then(function (setting) { if (setting) { return setting.save({value: item.value}, options); } return Promise.reject(new errors.NotFoundError('Unable to find setting to update: ' + item.key)); - }, errors.logAndThrowError); }); }, @@ -119,7 +117,7 @@ Settings = ghostBookshelf.Model.extend({ return Promise.reject(new errors.NotFoundError('Unable to find default setting: ' + key)); } - return this.findOne({ key: key }).then(function (foundSetting) { + return this.findOne({key: key}).then(function (foundSetting) { if (foundSetting) { return foundSetting; } diff --git a/core/server/models/user.js b/core/server/models/user.js index 1449a8601e..906ebfff72 100644 --- a/core/server/models/user.js +++ b/core/server/models/user.js @@ -143,12 +143,12 @@ User = ghostBookshelf.Model.extend({ /** * ### Find All * - * @param options + * @param {Object} options * @returns {*} */ findAll: function (options) { options = options || {}; - options.withRelated = _.union([ 'roles' ], options.include); + options.withRelated = _.union(['roles'], options.include); return ghostBookshelf.Model.findAll.call(this, options); }, @@ -172,7 +172,7 @@ User = ghostBookshelf.Model.extend({ * } * } * - * @params {Object} options + * @param {Object} options */ findPage: function (options) { options = options || {}; @@ -199,14 +199,14 @@ User = ghostBookshelf.Model.extend({ whereIn: {} }, options); - //TODO: there are multiple statuses that make a user "active" or "invited" - we a way to translate/map them: - //TODO (cont'd from above): * valid "active" statuses: active, warn-1, warn-2, warn-3, warn-4, locked - //TODO (cont'd from above): * valid "invited" statuses" invited, invited-pending + // TODO: there are multiple statuses that make a user "active" or "invited" - we a way to translate/map them: + // TODO (cont'd from above): * valid "active" statuses: active, warn-1, warn-2, warn-3, warn-4, locked + // TODO (cont'd from above): * valid "invited" statuses" invited, invited-pending // Filter on the status. A status of 'all' translates to no filter since we want all statuses if (options.status && options.status !== 'all') { // make sure that status is valid - //TODO: need a better way of getting a list of statuses other than hard-coding them... + // TODO: need a better way of getting a list of statuses other than hard-coding them... options.status = _.indexOf( ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked', 'invited', 'inactive'], options.status) !== -1 ? options.status : 'active'; @@ -227,9 +227,9 @@ User = ghostBookshelf.Model.extend({ } // Add related objects - options.withRelated = _.union([ 'roles' ], options.include); + options.withRelated = _.union(['roles'], options.include); - //only include a limit-query if a numeric limit is provided + // only include a limit-query if a numeric limit is provided if (_.isNumber(options.limit)) { userCollection .query('limit', options.limit) @@ -245,7 +245,6 @@ User = ghostBookshelf.Model.extend({ return Promise.resolve(fetchRoleQuery()) .then(function () { - if (roleInstance) { userCollection .query('join', 'roles_users', 'roles_users.user_id', '=', 'users.id') @@ -325,7 +324,6 @@ User = ghostBookshelf.Model.extend({ } } - return data; }) .catch(errors.logAndThrowError); @@ -348,12 +346,12 @@ User = ghostBookshelf.Model.extend({ delete data.status; options = options || {}; - options.withRelated = _.union([ 'roles' ], options.include); + options.withRelated = _.union(['roles'], options.include); // Support finding by role if (data.role) { options.withRelated = [{ - 'roles': function (qb) { + roles: function (qb) { qb.where('name', data.role); } }]; @@ -365,13 +363,12 @@ User = ghostBookshelf.Model.extend({ data = this.filterData(data); - if (status === 'active') { query.query('whereIn', 'status', activeStates); } else if (status === 'invited') { query.query('whereIn', 'status', invitedStates); } else if (status !== 'all') { - query.query('where', { 'status': options.status}); + query.query('where', {status: options.status}); } options = this.filterOptions(options, 'findOne'); @@ -390,10 +387,9 @@ User = ghostBookshelf.Model.extend({ roleId; options = options || {}; - options.withRelated = _.union([ 'roles' ], options.include); + options.withRelated = _.union(['roles'], options.include); return ghostBookshelf.Model.edit.call(this, data, options).then(function (user) { - if (data.roles) { roleId = parseInt(data.roles[0].id || data.roles[0], 10); @@ -443,7 +439,7 @@ User = ghostBookshelf.Model.extend({ roles; options = this.filterOptions(options, 'add'); - options.withRelated = _.union([ 'roles' ], options.include); + options.withRelated = _.union(['roles'], options.include); return ghostBookshelf.model('Role').findOne({name: 'Author'}, _.pick(options, 'transacting')).then(function (authorRole) { // Get the role we're going to assign to this user, or the author role if there isn't one @@ -473,7 +469,7 @@ User = ghostBookshelf.Model.extend({ }).then(function (addedUser) { // Assign the userData to our created user so we can pass it back userData = addedUser; - //if we are given a "role" object, only pass in the role ID in place of the full object + // if we are given a "role" object, only pass in the role ID in place of the full object roles = _.map(roles, function (role) { if (_.isString(role)) { return parseInt(role, 10); @@ -496,7 +492,7 @@ User = ghostBookshelf.Model.extend({ userData = this.filterData(data); options = this.filterOptions(options, 'setup'); - options.withRelated = _.union([ 'roles' ], options.include); + options.withRelated = _.union(['roles'], options.include); return validatePasswordLength(userData.password).then(function () { // Generate a new password hash @@ -524,7 +520,6 @@ User = ghostBookshelf.Model.extend({ // If we passed in an id instead of a model, get the model then check the permissions if (_.isNumber(userModelOrId) || _.isString(userModelOrId)) { - // Grab the original args without the first one origArgs = _.toArray(arguments).slice(1); // Get the actual post model @@ -539,12 +534,12 @@ User = ghostBookshelf.Model.extend({ if (action === 'edit') { // Users with the role 'Editor' and 'Author' have complex permissions when the action === 'edit' // We now have all the info we need to construct the permissions - if (_.any(loadedPermissions.user.roles, { 'name': 'Author' })) { + if (_.any(loadedPermissions.user.roles, {name: 'Author'})) { // If this is the same user that requests the operation allow it. hasUserPermission = hasUserPermission || context.user === userModel.get('id'); } - if (_.any(loadedPermissions.user.roles, { 'name': 'Editor' })) { + if (_.any(loadedPermissions.user.roles, {name: 'Editor'})) { // If this is the same user that requests the operation allow it. hasUserPermission = context.user === userModel.get('id'); @@ -560,7 +555,7 @@ User = ghostBookshelf.Model.extend({ } // Users with the role 'Editor' have complex permissions when the action === 'destroy' - if (_.any(loadedPermissions.user.roles, { 'name': 'Editor' })) { + if (_.any(loadedPermissions.user.roles, {name: 'Editor'})) { // If this is the same user that requests the operation allow it. hasUserPermission = context.user === userModel.get('id'); @@ -620,7 +615,6 @@ User = ghostBookshelf.Model.extend({ // Use comma structure, not .catch, because we don't want to catch incorrect passwords }, function (error) { - // If we get a validation or other error during this save, catch it and log it, but don't // cause a login error because of it. The user validation is not important here. errors.logError( @@ -632,7 +626,7 @@ User = ghostBookshelf.Model.extend({ }); } - return Promise.resolve(user.set({status : 'active', last_login : new Date()}).save({validate: false})) + return Promise.resolve(user.set({status: 'active', last_login: new Date()}).save({validate: false})) .catch(function (error) { // If we get a validation or other error during this save, catch it and log it, but don't // cause a login error because of it. The user validation is not important here. @@ -648,7 +642,6 @@ User = ghostBookshelf.Model.extend({ return Promise.reject(new errors.NoPermissionError('Your account is locked due to too many ' + 'login attempts. Please reset your password to log in again by clicking ' + 'the "Forgotten password?" link!')); - }, function (error) { if (error.message === 'NotFound' || error.message === 'EmptyResponse') { return Promise.reject(new errors.NotFoundError('There is no user with that email address.')); @@ -660,7 +653,10 @@ User = ghostBookshelf.Model.extend({ /** * Naive change password method - * @param {object} _userdata email, old pw, new pw, new pw2 + * @param {String} oldPassword + * @param {String} newPassword + * @param {String} ne2Password + * @param {Object} options */ changePassword: function (oldPassword, newPassword, ne2Password, options) { var self = this, @@ -818,7 +814,6 @@ User = ghostBookshelf.Model.extend({ contextUser = ctxUser; return User.findOne({id: object.id}); }).then(function (user) { - var currentRoles = user.toJSON().roles; if (!_.contains(currentRoles, adminRole.id)) { return Promise.reject(new errors.ValidationError('Only administrators can be assigned the owner role.')); @@ -833,9 +828,9 @@ User = ghostBookshelf.Model.extend({ }).then(function () { return Users.forge() .query('whereIn', 'id', [contextUser.id, assignUser.id]) - .fetch({ withRelated: ['roles'] }); + .fetch({withRelated: ['roles']}); }).then(function (users) { - return users.toJSON({ include: ['roles'] }); + return users.toJSON({include: ['roles']}); }); }, @@ -856,7 +851,7 @@ User = ghostBookshelf.Model.extend({ resolve(userData); }).on('error', function () { - //Error making request just continue. + // Error making request just continue. resolve(userData); }); }); diff --git a/core/server/permissions/effective.js b/core/server/permissions/effective.js index 5428d514f0..c955dda627 100644 --- a/core/server/permissions/effective.js +++ b/core/server/permissions/effective.js @@ -1,10 +1,11 @@ var _ = require('lodash'), Models = require('../models'), - errors = require('../errors'); + errors = require('../errors'), + effective; -var effective = { +effective = { user: function (id) { - return Models.User.findOne({id: id, status: 'all'}, { include: ['permissions', 'roles', 'roles.permissions'] }) + return Models.User.findOne({id: id, status: 'all'}, {include: ['permissions', 'roles', 'roles.permissions']}) .then(function (foundUser) { var seenPerms = {}, rolePerms = _.map(foundUser.related('roles').models, function (role) { @@ -34,7 +35,7 @@ var effective = { }, app: function (appName) { - return Models.App.findOne({name: appName}, { withRelated: ['permissions'] }) + return Models.App.findOne({name: appName}, {withRelated: ['permissions']}) .then(function (foundApp) { if (!foundApp) { return []; @@ -45,4 +46,4 @@ var effective = { } }; -module.exports = effective; \ No newline at end of file +module.exports = effective; diff --git a/core/server/permissions/index.js b/core/server/permissions/index.js index 0c7079365d..42d5c0c91e 100644 --- a/core/server/permissions/index.js +++ b/core/server/permissions/index.js @@ -49,18 +49,18 @@ CanThisResult = function () { return; }; -CanThisResult.prototype.buildObjectTypeHandlers = function (obj_types, act_type, context, permissionLoad) { +CanThisResult.prototype.buildObjectTypeHandlers = function (objTypes, actType, context, permissionLoad) { // @TODO: remove this lazy require var objectTypeModelMap = require('./objectTypeModelMap'); // Iterate through the object types, i.e. ['post', 'tag', 'user'] - return _.reduce(obj_types, function (obj_type_handlers, obj_type) { + return _.reduce(objTypes, function (objTypeHandlers, objType) { // Grab the TargetModel through the objectTypeModelMap - var TargetModel = objectTypeModelMap[obj_type]; + var TargetModel = objectTypeModelMap[objType]; // Create the 'handler' for the object type; // the '.post()' in canThis(user).edit.post() - obj_type_handlers[obj_type] = function (modelOrId) { + objTypeHandlers[objType] = function (modelOrId) { var modelId; // If it's an internal request, resolve immediately @@ -86,7 +86,7 @@ CanThisResult.prototype.buildObjectTypeHandlers = function (obj_types, act_type, var permObjId; // Look for a matching action type and object type first - if (perm.get('action_type') !== act_type || perm.get('object_type') !== obj_type) { + if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { return false; } @@ -106,13 +106,12 @@ CanThisResult.prototype.buildObjectTypeHandlers = function (obj_types, act_type, }; // Check user permissions for matching action, object and id. - if (_.any(loadedPermissions.user.roles, { 'name': 'Owner' })) { + if (_.any(loadedPermissions.user.roles, {name: 'Owner'})) { hasUserPermission = true; } else if (!_.isEmpty(userPermissions)) { hasUserPermission = _.any(userPermissions, checkPermission); } - // Check app permissions if they were passed hasAppPermission = true; if (!_.isNull(appPermissions)) { @@ -122,7 +121,7 @@ CanThisResult.prototype.buildObjectTypeHandlers = function (obj_types, act_type, // Offer a chance for the TargetModel to override the results if (TargetModel && _.isFunction(TargetModel.permissible)) { return TargetModel.permissible( - modelId, act_type, context, loadedPermissions, hasUserPermission, hasAppPermission + modelId, actType, context, loadedPermissions, hasUserPermission, hasAppPermission ); } @@ -134,7 +133,7 @@ CanThisResult.prototype.buildObjectTypeHandlers = function (obj_types, act_type, }); }; - return obj_type_handlers; + return objTypeHandlers; }, {}); }; @@ -148,7 +147,7 @@ CanThisResult.prototype.beginCheck = function (context) { context = parseContext(context); if (!hasActionsMap()) { - throw new Error("No actions map found, please call permissions.init() before use."); + throw new Error('No actions map found, please call permissions.init() before use.'); } // Kick off loading of effective user permissions if necessary @@ -159,7 +158,6 @@ CanThisResult.prototype.beginCheck = function (context) { userPermissionLoad = Promise.resolve(null); } - // Kick off loading of effective app permissions if necessary if (context.app) { appPermissionLoad = effectivePerms.app(context.app); @@ -177,18 +175,18 @@ CanThisResult.prototype.beginCheck = function (context) { }); // Iterate through the actions and their related object types - _.each(exported.actionsMap, function (obj_types, act_type) { + _.each(exported.actionsMap, function (objTypes, actType) { // Build up the object type handlers; // the '.post()' parts in canThis(user).edit.post() - var obj_type_handlers = self.buildObjectTypeHandlers(obj_types, act_type, context, permissionsLoad); + var objTypeHandlers = self.buildObjectTypeHandlers(objTypes, actType, context, permissionsLoad); // Define a property for the action on the result; // the '.edit' in canThis(user).edit.post() - Object.defineProperty(self, act_type, { + Object.defineProperty(self, actType, { writable: false, enumerable: false, configurable: false, - value: obj_type_handlers + value: objTypeHandlers }); }); @@ -218,19 +216,19 @@ init = refresh = function () { } */ _.each(perms.models, function (perm) { - var action_type = perm.get('action_type'), - object_type = perm.get('object_type'); + var actionType = perm.get('action_type'), + objectType = perm.get('object_type'); - exported.actionsMap[action_type] = exported.actionsMap[action_type] || []; - seenActions[action_type] = seenActions[action_type] || {}; + exported.actionsMap[actionType] = exported.actionsMap[actionType] || []; + seenActions[actionType] = seenActions[actionType] || {}; // Check if we've already seen this action -> object combo - if (seenActions[action_type][object_type]) { + if (seenActions[actionType][objectType]) { return; } - exported.actionsMap[action_type].push(object_type); - seenActions[action_type][object_type] = true; + exported.actionsMap[actionType].push(objectType); + seenActions[actionType][objectType] = true; }); return exported.actionsMap; diff --git a/core/server/permissions/objectTypeModelMap.js b/core/server/permissions/objectTypeModelMap.js index 58efe95a69..9845093489 100644 --- a/core/server/permissions/objectTypeModelMap.js +++ b/core/server/permissions/objectTypeModelMap.js @@ -1,7 +1,7 @@ module.exports = { - 'post': require('../models/post').Post, - 'role': require('../models/role').Role, - 'user': require('../models/user').User, - 'permission': require('../models/permission').Permission, - 'setting': require('../models/settings').Settings + post: require('../models/post').Post, + role: require('../models/role').Role, + user: require('../models/user').User, + permission: require('../models/permission').Permission, + setting: require('../models/settings').Settings }; diff --git a/core/server/require-tree.js b/core/server/require-tree.js index 956ae5c067..ede13b25b6 100644 --- a/core/server/require-tree.js +++ b/core/server/require-tree.js @@ -110,7 +110,7 @@ var _ = require('lodash'), return paths; }).catch(function () { - return {'_messages': messages}; + return {_messages: messages}; }); }; diff --git a/core/server/routes/admin.js b/core/server/routes/admin.js index d4d4381844..70aa62d1eb 100644 --- a/core/server/routes/admin.js +++ b/core/server/routes/admin.js @@ -32,4 +32,4 @@ adminRoutes = function (middleware) { return router; }; -module.exports = adminRoutes; \ No newline at end of file +module.exports = adminRoutes; diff --git a/core/server/routes/api.js b/core/server/routes/api.js index b7afc0f86e..595ca1a069 100644 --- a/core/server/routes/api.js +++ b/core/server/routes/api.js @@ -65,7 +65,6 @@ apiRoutes = function (middleware) { api.http(api.mail.sendTest)(req, res); }); - // ## Authentication router.post('/authentication/passwordreset', middleware.spamForgottenPrevention, diff --git a/core/server/routes/frontend.js b/core/server/routes/frontend.js index 24046eac52..c25bc3b1cc 100644 --- a/core/server/routes/frontend.js +++ b/core/server/routes/frontend.js @@ -38,4 +38,4 @@ frontendRoutes = function () { return router; }; -module.exports = frontendRoutes; \ No newline at end of file +module.exports = frontendRoutes; diff --git a/core/server/routes/index.js b/core/server/routes/index.js index 0f65cf26ba..0c2d4346a4 100644 --- a/core/server/routes/index.js +++ b/core/server/routes/index.js @@ -7,4 +7,4 @@ module.exports = { api: api, admin: admin, frontend: frontend -}; \ No newline at end of file +}; diff --git a/core/server/storage/index.js b/core/server/storage/index.js index ea46ded97c..f680f277b3 100644 --- a/core/server/storage/index.js +++ b/core/server/storage/index.js @@ -23,4 +23,4 @@ function getStorage(storageChoice) { return storage[storageChoice]; } -module.exports.getStorage = getStorage; \ No newline at end of file +module.exports.getStorage = getStorage; diff --git a/core/server/update-check.js b/core/server/update-check.js index db025ffacc..ec659b86a3 100644 --- a/core/server/update-check.js +++ b/core/server/update-check.js @@ -168,7 +168,7 @@ function updateCheck() { // 1. updateCheck is defined as false in config.js // 2. we've already done a check this session // 3. we're not in production or development mode - //TODO: need to remove config.updateCheck in favor of config.privacy.updateCheck in future version (it is now deprecated) + // TODO: need to remove config.updateCheck in favor of config.privacy.updateCheck in future version (it is now deprecated) if (config.updateCheck === false || config.isPrivacyDisabled('useUpdateCheck') || _.indexOf(allowedCheckEnvironments, process.env.NODE_ENV) === -1) { // No update check return Promise.resolve(); diff --git a/core/server/utils/downzero.js b/core/server/utils/downzero.js index 3cf214a27b..95e01a0a74 100644 --- a/core/server/utils/downzero.js +++ b/core/server/utils/downzero.js @@ -1,50 +1,48 @@ // Functions to imitate the behavior of Downsize@0.0.5 with 'words: "0"' (heavily based on Downsize) var stack, tagName, tagBuffer, truncatedText, parseState, pointer, - states = {unitialized: 0, tag_commenced: 1, tag_string: -1, tag_string_single: -2, comment: -3 }, + states = {unitialized: 0, tag_commenced: 1, tag_string: -1, tag_string_single: -2, comment: -3}, voidElements = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', - 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']; + 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']; function getTagName(tag) { - var tagName = (tag || "").match(/<\/*([a-z0-9\:\-\_]+)/i); + var tagName = (tag || '').match(/<\/*([a-z0-9\:\-\_]+)/i); return tagName ? tagName[1] : null; } function closeTag(openingTag) { - var tagName = (getTagName(openingTag)) ? "" + getTagName(openingTag) + ">" : ""; + var tagName = (getTagName(openingTag)) ? '' + getTagName(openingTag) + '>' : ''; return tagName; } function downzero(text) { - stack = []; tagName = ''; tagBuffer = ''; - truncatedText = ""; + truncatedText = ''; parseState = 0; pointer = 0; for (; pointer < text.length; pointer += 1) { - if (parseState !== states.unitialized) { tagBuffer += text[pointer]; } switch (text[pointer]) { - case "<": + case '<': if (parseState === states.unitialized && text[pointer + 1].match(/[a-z0-9\-\_\/\!]/)) { parseState = states.tag_commenced; tagBuffer += text[pointer]; } break; - case "!": - if (parseState === states.tag_commenced && text[pointer - 1] === "<") { + case '!': + if (parseState === states.tag_commenced && text[pointer - 1] === '<') { parseState = states.comment; } break; - case "\"": + case '\"': if (parseState === states.tag_string) { parseState = states.tag_commenced; } else if (parseState === states.tag_string_single) { @@ -55,7 +53,7 @@ function downzero(text) { } break; - case "'": + case '\'': if (parseState === states.tag_string_single) { parseState = states.tag_commenced; } else if (parseState === states.tag_string) { @@ -65,7 +63,7 @@ function downzero(text) { } break; - case ">": + case '>': if (parseState === states.tag_commenced) { parseState = states.unitialized; truncatedText += tagBuffer; @@ -76,21 +74,21 @@ function downzero(text) { } else if (voidElements.indexOf(tagName) < 0 && !tagBuffer.match(/\/\s*>$/)) { stack.push(tagBuffer); } - tagBuffer = ""; + tagBuffer = ''; continue; } - if (parseState === states.comment && text.substring(pointer - 2, pointer) === "--") { + if (parseState === states.comment && text.substring(pointer - 2, pointer) === '--') { parseState = states.unitialized; truncatedText += tagBuffer; - tagBuffer = ""; + tagBuffer = ''; continue; } break; - case "-": + case '-': break; } @@ -108,4 +106,4 @@ function downzero(text) { return truncatedText; } -module.exports = downzero; \ No newline at end of file +module.exports = downzero; diff --git a/core/server/utils/index.js b/core/server/utils/index.js index a8c1add796..45c0f06552 100644 --- a/core/server/utils/index.js +++ b/core/server/utils/index.js @@ -67,4 +67,4 @@ utils = { } }; -module.exports = utils; \ No newline at end of file +module.exports = utils; diff --git a/core/server/xmlrpc.js b/core/server/xmlrpc.js index ccca447e7a..6a088de73d 100644 --- a/core/server/xmlrpc.js +++ b/core/server/xmlrpc.js @@ -7,10 +7,13 @@ var _ = require('lodash'), pingList; // ToDo: Make this configurable -pingList = [ - { host: 'blogsearch.google.com', path: '/ping/RPC2' }, - { host: 'rpc.pingomatic.com', path: '/' } -]; +pingList = [{ + host: 'blogsearch.google.com', + path: '/ping/RPC2' +}, { + host: 'rpc.pingomatic.com', + path: '/' +}]; function ping(post) { var pingXML, @@ -31,19 +34,25 @@ function ping(post) { // Need to require here because of circular dependency return config.urlForPost(api.settings, post, true).then(function (url) { - // Build XML object. pingXML = xml({ - methodCall: [ - { methodName: 'weblogUpdate.ping' }, - { - params: [{ - param: [{ value: [{ string: title }]}], - }, { - param: [{ value: [{ string: url }]}], + methodCall: [{ + methodName: 'weblogUpdate.ping' + }, { + params: [{ + param: [{ + value: [{ + string: title + }] }] - } - ] + }, { + param: [{ + value: [{ + string: url + }] + }] + }] + }] }, {declaration: true}); // Ping each of the defined services. @@ -60,8 +69,8 @@ function ping(post) { req.on('error', function (error) { errors.logError( error, - "Pinging services for updates on your blog failed, your blog will continue to function.", - "If you get this error repeatedly, please seek help from https://ghost.org/forum." + 'Pinging services for updates on your blog failed, your blog will continue to function.', + 'If you get this error repeatedly, please seek help from https://ghost.org/forum.' ); }); req.end(); @@ -71,4 +80,4 @@ function ping(post) { module.exports = { ping: ping -}; \ No newline at end of file +}; diff --git a/core/test/blanket_coverage.js b/core/test/blanket_coverage.js index 973bd1b2b5..1972c7637e 100644 --- a/core/test/blanket_coverage.js +++ b/core/test/blanket_coverage.js @@ -1,7 +1,7 @@ // Posts /*jshint unused:false */ var blanket = require('blanket')({ - 'pattern': ['/core/server/', '/core/client/', '/core/shared/'], + pattern: ['/core/server/', '/core/client/', '/core/shared/'], 'data-cover-only': ['/core/server/', '/core/client/', '/core/shared/'] }), requireDir = require('require-dir'); diff --git a/core/test/functional/base.js b/core/test/functional/base.js index f1a9881416..538c740d2f 100644 --- a/core/test/functional/base.js +++ b/core/test/functional/base.js @@ -52,25 +52,30 @@ var DEBUG = false, // TOGGLE THIS TO GET MORE SCREENSHOTS title: 'Bacon ipsum dolor sit amet', html: 'I am a test post.\n#I have some small content' }, - screens; + screens, + CasperTest, + // ## Debugging + jsErrors = [], + pageErrors = [], + resourceErrors = []; screens = { - 'root': { + root: { url: 'ghost/', linkSelector: '.nav-content', selector: '.nav-content.active' }, - 'content': { + content: { url: 'ghost/content/', linkSelector: '.nav-content', selector: '.nav-content.active' }, - 'editor': { + editor: { url: 'ghost/editor/', linkSelector: '.nav-new', selector: '#entry-title' }, - 'settings': { + settings: { url: 'ghost/settings/', linkSelector: '.nav-settings', selector: '.nav-settings.active' @@ -89,26 +94,26 @@ screens = { linkSelector: '.user-menu-profile', selector: '.user-profile' }, - 'signin': { + signin: { url: 'ghost/signin/', selector: '.btn-blue' }, 'signin-authenticated': { url: 'ghost/signin/', - //signin with authenticated user redirects to posts + // signin with authenticated user redirects to posts selector: '.nav-content.active' }, - 'signout': { + signout: { url: 'ghost/signout/', linkSelector: '.user-menu-signout', // When no user exists we get redirected to setup which has btn-green selector: '.btn-blue, .btn-green' }, - 'signup': { + signup: { url: 'ghost/signup/', selector: '.btn-blue' }, - 'setup': { + setup: { url: 'ghost/setup/', selector: '.btn-green' }, @@ -162,7 +167,6 @@ casper.waitForTransparent = function (classname, then, timeout) { casper.waitForOpacity(classname, '0', then, timeout); }; - // ### Then Open And Wait For Page Load // Always wait for the `.page-content` element as some indication that the ember app has loaded. casper.thenOpenAndWaitForPageLoad = function (screen, then, timeout) { @@ -211,11 +215,6 @@ casper.fillAndAdd = function (selector, data) { }); }; -// ## Debugging -var jsErrors = [], - pageErrors = [], - resourceErrors = []; - // ## Echo Concise // Does casper.echo but checks for the presence of the --concise flag casper.echoConcise = function (message, style) { @@ -303,8 +302,7 @@ casper.test.on('exit', function () { } }); -var CasperTest = (function () { - +CasperTest = (function () { var _beforeDoneHandler, _noop = function noop() { }, _isUserRegistered = false; @@ -330,7 +328,6 @@ var CasperTest = (function () { if (!doNotAutoLogin) { // Only call register once for the lifetime of CasperTest if (!_isUserRegistered) { - CasperTest.Routines.signout.run(); CasperTest.Routines.setup.run(); @@ -350,7 +347,6 @@ var CasperTest = (function () { }); }; - if (typeof expect === 'function') { doNotAutoLogin = suite; suite = expect; @@ -374,11 +370,9 @@ var CasperTest = (function () { begin: begin, beforeDone: beforeDone }; - }()); CasperTest.Routines = (function () { - function setup() { casper.thenOpenAndWaitForPageLoad('setup', function then() { casper.captureScreenshot('setting_up1.png'); @@ -399,13 +393,11 @@ CasperTest.Routines = (function () { }, 2000); casper.captureScreenshot('setting_up3.png'); - }); } function signin() { casper.thenOpenAndWaitForPageLoad('signin', function then() { - casper.waitForOpaque('.login-box', function then() { casper.captureScreenshot('signing_in.png'); this.fillAndSave('#login', user); @@ -476,10 +468,10 @@ CasperTest.Routines = (function () { function _createRunner(fn) { fn.run = function run(test) { - var routine = this; + var self = this; casper.then(function () { - routine.call(casper, test); + self.call(casper, test); }); }; @@ -493,5 +485,4 @@ CasperTest.Routines = (function () { createTestPost: _createRunner(createTestPost), togglePermalinks: _createRunner(togglePermalinks) }; - }()); diff --git a/core/test/functional/client/content_test.js b/core/test/functional/client/content_test.js index 401f45cffd..80f1adab7c 100644 --- a/core/test/functional/client/content_test.js +++ b/core/test/functional/client/content_test.js @@ -97,19 +97,17 @@ CasperTest.begin('Content list shows correct post status', 5, function testStati // test.assert(false, 'status did not change'); // }); // }); - }); - // TODO: Implement this test... much needed! -//CasperTest.begin('Infinite scrolling', 2, function suite(test) { +// CasperTest.begin('Infinite scrolling', 2, function suite(test) { // // Placeholder for infinite scrolling/pagination tests (will need to setup 16+ posts). // // casper.thenOpenAndWaitForPageLoad('content', function testTitleAndUrl() { // test.assertTitle('Ghost Admin', 'Title is "Ghost Admin"'); // test.assertUrlMatch(/ghost\/\d+\/$/, 'Landed on the correct URL'); // }); -//}); +// }); CasperTest.begin('Posts can be marked as featured', 8, function suite(test) { // Create a sample post @@ -129,7 +127,7 @@ CasperTest.begin('Posts can be marked as featured', 8, function suite(test) { }); casper.waitForResource(/\/posts\/\d+\/\?include=tags/, function (resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); }); casper.waitForSelector('.content-list-content li.featured:first-of-type', function () { @@ -143,7 +141,7 @@ CasperTest.begin('Posts can be marked as featured', 8, function suite(test) { casper.thenClick('.content-preview .featured'); casper.waitForResource(/\/posts\/\d+\/\?include=tags/, function waitForSuccess(resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); }); casper.then(function untoggledFeaturedTest() { @@ -152,4 +150,4 @@ CasperTest.begin('Posts can be marked as featured', 8, function suite(test) { }, function onTimeout() { test.assert(false, 'Couldn\'t unfeature post.'); }); -}); \ No newline at end of file +}); diff --git a/core/test/functional/client/editor_test.js b/core/test/functional/client/editor_test.js index 4863cad2f4..e12a263ac4 100644 --- a/core/test/functional/client/editor_test.js +++ b/core/test/functional/client/editor_test.js @@ -516,7 +516,6 @@ CasperTest.begin('Publish menu - existing post status is correct after failed sa }); }); - // test the markdown help modal CasperTest.begin('Markdown help modal', 5, function suite(test) { casper.thenOpenAndWaitForPageLoad('editor', function testTitleAndUrl() { @@ -580,7 +579,7 @@ CasperTest.begin('Title input is set correctly after using the Post-Settings-Men }); casper.waitForResource(/\/posts\/\d+\/\?include=tags/, function testGoodResponse(resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); }); casper.then(function checkTitleInput() { @@ -627,7 +626,7 @@ CasperTest.begin('Editor content is set correctly after using the Post-Settings- }); casper.waitForResource(/\/posts\/\d+\/\?include=tags/, function testGoodResponse(resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); }); casper.waitForSelectorTextChange('.entry-preview .rendered-markdown', function onSuccess() { diff --git a/core/test/functional/client/psm_test.js b/core/test/functional/client/psm_test.js index 3ad2747397..413431db66 100644 --- a/core/test/functional/client/psm_test.js +++ b/core/test/functional/client/psm_test.js @@ -3,7 +3,6 @@ /*globals CasperTest, casper, __utils__ */ - CasperTest.begin('Post settings menu', 14, function suite(test) { casper.thenOpenAndWaitForPageLoad('editor', function testTitleAndUrl() { test.assertTitle('Ghost Admin', 'Ghost admin has no title'); @@ -56,7 +55,6 @@ CasperTest.begin('Post settings menu', 14, function suite(test) { casper.waitUntilVisible('.post-settings-menu button.delete', function onSuccess() { test.assert(true, 'delete post button should be visible for saved drafts'); }); - }); CasperTest.begin('Delete post modal', 7, function testDeleteModal(test) { @@ -135,11 +133,11 @@ CasperTest.begin('Post url can be changed', 4, function suite(test) { }); casper.waitForResource(/\/posts\/\d+\/\?include=tags/, function testGoodResponse(resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); }); casper.then(function checkValueMatches() { - //using assertField(name) checks the htmls initial "value" attribute, so have to hack around it. + // using assertField(name) checks the htmls initial "value" attribute, so have to hack around it. var slugVal = this.evaluate(function () { return __utils__.getFieldValue('post-setting-slug'); }); @@ -173,11 +171,11 @@ CasperTest.begin('Post published date can be changed', 4, function suite(test) { }); casper.waitForResource(/\/posts\/\d+\/\?include=tags/, function testGoodResponse(resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); }); casper.then(function checkValueMatches() { - //using assertField(name) checks the htmls initial "value" attribute, so have to hack around it. + // using assertField(name) checks the htmls initial "value" attribute, so have to hack around it. var dateVal = this.evaluate(function () { return __utils__.getFieldValue('post-setting-date'); }); @@ -204,7 +202,7 @@ CasperTest.begin('Post can be changed to static page', 6, function suite(test) { casper.thenClick('label[for=static-page]'); casper.waitForResource(/\/posts\/\d+\/\?include=tags/, function waitForSuccess(resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); test.assertExists('.post-setting-static-page:checked', 'can turn on static page'); }); @@ -212,7 +210,7 @@ CasperTest.begin('Post can be changed to static page', 6, function suite(test) { casper.thenClick('label[for=static-page]'); casper.waitForResource(/\/posts\/\d+\/\?include=tags/, function waitForSuccess(resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); test.assertDoesntExist('.post-setting-static-page:checked', 'can turn off static page'); }); @@ -251,10 +249,10 @@ CasperTest.begin('Post url input is reset from all whitespace back to original v }); casper.then(function checkValueMatches() { - //using assertField(name) checks the htmls initial "value" attribute, so have to hack around it. + // using assertField(name) checks the htmls initial "value" attribute, so have to hack around it. var slugVal = this.evaluate(function () { return __utils__.getFieldValue('post-setting-slug'); }); test.assertEqual(slugVal, originalSlug); }); -}); \ No newline at end of file +}); diff --git a/core/test/functional/client/settings_test.js b/core/test/functional/client/settings_test.js index 6679722566..8433dfe793 100644 --- a/core/test/functional/client/settings_test.js +++ b/core/test/functional/client/settings_test.js @@ -107,7 +107,7 @@ CasperTest.begin('General settings pane is correct', 8, function suite(test) { }, casper.failOnTimeout(test, 'No success notification :(')); }); -//// ## General settings validations tests +// ## General settings validations tests CasperTest.begin('General settings validation is correct', 6, function suite(test) { casper.thenOpenAndWaitForPageLoad('settings.general', function testTitleAndUrl() { test.assertTitle('Ghost Admin', 'Ghost admin has no title'); @@ -136,7 +136,7 @@ CasperTest.begin('General settings validation is correct', 6, function suite(tes casper.thenClick('.js-bb-notification .close'); - // Check postsPerPage autocorrect + // Check postsPerPage autocorrect casper.fillAndSave('form#settings-general', { 'general[postsPerPage]': 'notaninteger' }); @@ -181,7 +181,7 @@ CasperTest.begin('Users screen is correct', 9, function suite(test) { return true; }, '"Owner" is not a role option for new users'); }); - //role options get loaded asynchronously; give them a chance to come in + // role options get loaded asynchronously; give them a chance to come in casper.waitForSelector('.invite-new-user select#new-user-role option', function then() { test.assertEval(function authorIsSelectedByDefault() { var options = document.querySelectorAll('.invite-new-user select#new-user-role option'), @@ -312,7 +312,7 @@ CasperTest.begin('User settings screen change slug handles duplicate slug', 4, f casper.thenClick('body'); casper.waitForResource(/\/slugs\/user\//, function testGoodResponse(resource) { - test.assert(400 > resource.status); + test.assert(resource.status < 400); }); casper.then(function checkSlugInputValue() { diff --git a/core/test/functional/client/signin_test.js b/core/test/functional/client/signin_test.js index 63ba23b411..aeb5ecbca1 100644 --- a/core/test/functional/client/signin_test.js +++ b/core/test/functional/client/signin_test.js @@ -112,7 +112,6 @@ CasperTest.begin('Authenticated user is redirected', 8, function suite(test) { }); }, true); - CasperTest.begin('Ensure email field form validation', 3, function suite(test) { CasperTest.Routines.signout.run(test); @@ -124,7 +123,7 @@ CasperTest.begin('Ensure email field form validation', 3, function suite(test) { casper.waitForOpaque('.js-login-box', function then() { this.fillAndSave('form.login-form', { - 'identification': 'notanemail' + identification: 'notanemail' }); }, function onTimeout() { @@ -136,4 +135,4 @@ CasperTest.begin('Ensure email field form validation', 3, function suite(test) { }, function onTimeout() { test.fail('Email validation error did not appear'); }, 2000); -}, true); \ No newline at end of file +}, true); diff --git a/core/test/functional/client/signout_test.js b/core/test/functional/client/signout_test.js index 6502843a9d..535bcd64f4 100644 --- a/core/test/functional/client/signout_test.js +++ b/core/test/functional/client/signout_test.js @@ -29,5 +29,4 @@ CasperTest.begin('Ghost signout works correctly', 3, function suite(test) { }); casper.captureScreenshot('user-menu-logout-clicked.png'); - }, true); diff --git a/core/test/functional/frontend/error_test.js b/core/test/functional/frontend/error_test.js index 3db9dcfc21..34e632b1e1 100644 --- a/core/test/functional/frontend/error_test.js +++ b/core/test/functional/frontend/error_test.js @@ -5,14 +5,14 @@ CasperTest.begin('Check post not found (404)', 2, function suite(test) { casper.thenOpen(url + 'asdf/', function (response) { test.assertEqual(response.status, 404, 'Response status should be 404.'); - test.assertSelectorHasText('.error-code', '404'); + test.assertSelectorHasText('.error-code', '404'); }); }, true); CasperTest.begin('Check frontend route not found (404)', 2, function suite(test) { casper.thenOpen(url + 'asdf/asdf/', function (response) { test.assertEqual(response.status, 404, 'Response status should be 404.'); - test.assertSelectorHasText('.error-code', '404'); + test.assertSelectorHasText('.error-code', '404'); }); }, true); diff --git a/core/test/functional/frontend/feed_test.js b/core/test/functional/frontend/feed_test.js index fa98fd6a49..d3ad3f8f32 100644 --- a/core/test/functional/frontend/feed_test.js +++ b/core/test/functional/frontend/feed_test.js @@ -64,4 +64,3 @@ CasperTest.begin('Ensure that character set is UTF-8 for RSS feed', 1, function test.assertEqual(response.headers.get('Content-Type'), 'text/xml; charset=utf-8', 'Content type should include UTF-8 character set encoding.'); }); }, false); - diff --git a/core/test/functional/frontend/home_test.js b/core/test/functional/frontend/home_test.js index 6ec269284e..3cfebd3c75 100644 --- a/core/test/functional/frontend/home_test.js +++ b/core/test/functional/frontend/home_test.js @@ -75,4 +75,3 @@ CasperTest.begin('Test navigating to Post with date permalink', 4, function suit }); CasperTest.Routines.togglePermalinks.run('off'); }, false); - diff --git a/core/test/functional/frontend/post_test.js b/core/test/functional/frontend/post_test.js index 84296d50ec..232c71efb1 100644 --- a/core/test/functional/frontend/post_test.js +++ b/core/test/functional/frontend/post_test.js @@ -31,4 +31,4 @@ CasperTest.begin('Test helpers on welcome post', 4, function suite(test) { test.assertExists('article.post', 'post_class outputs correct post class'); test.assertExists('article.tag-getting-started', 'post_class outputs correct tag class'); }); -}, true); \ No newline at end of file +}, true); diff --git a/core/test/functional/frontend/route_test.js b/core/test/functional/frontend/route_test.js index 53f0a03019..d24bb5dc47 100644 --- a/core/test/functional/frontend/route_test.js +++ b/core/test/functional/frontend/route_test.js @@ -7,4 +7,4 @@ CasperTest.begin('Redirects page 1 request', 1, function suite(test) { casper.thenOpen(url + 'page/1/', function then() { test.assertEqual(casper.getCurrentUrl().indexOf('page/'), -1, 'Should be redirected to "/".'); }); -}, true); \ No newline at end of file +}, true); diff --git a/core/test/functional/routes/admin_test.js b/core/test/functional/routes/admin_test.js index 418a2c1921..a71e31eb90 100644 --- a/core/test/functional/routes/admin_test.js +++ b/core/test/functional/routes/admin_test.js @@ -13,10 +13,10 @@ var request = require('supertest'), ghost = require('../../../../core'), cacheRules = { - 'public': 'public, max-age=0', - 'hour': 'public, max-age=' + testUtils.ONE_HOUR_S, - 'year': 'public, max-age=' + testUtils.ONE_YEAR_S, - 'private': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0' + public: 'public, max-age=0', + hour: 'public, max-age=' + testUtils.ONE_HOUR_S, + year: 'public, max-age=' + testUtils.ONE_YEAR_S, + private: 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0' }; describe('Admin Routing', function () { @@ -67,7 +67,6 @@ describe('Admin Routing', function () { }); describe('Legacy Redirects', function () { - it('should redirect /logout/ to /ghost/signout/', function (done) { request.get('/logout/') .expect('Location', '/ghost/signout/') @@ -235,7 +234,6 @@ describe('Admin Routing', function () { // it('should redirect from /ghost/signup to /ghost/ when logged in', function (done) { // done(); // }); - }); // // describe('Ghost Admin Forgot Password', function () { @@ -277,7 +275,7 @@ describe('Admin Routing', function () { // .end(doEnd(done)); // }); // }); -//}); +// }); // TODO: not working anymore, needs new test for Ember // describe('Authenticated Admin Routing', function () { @@ -306,7 +304,6 @@ describe('Admin Routing', function () { // return done(err); // } - // process.nextTick(function () { // request.post('/ghost/signin/') // .send({email: user.email, password: user.password}) diff --git a/core/test/functional/routes/api/authentication_test.js b/core/test/functional/routes/api/authentication_test.js index 389e4beee8..db5867925b 100644 --- a/core/test/functional/routes/api/authentication_test.js +++ b/core/test/functional/routes/api/authentication_test.js @@ -8,7 +8,6 @@ var supertest = require('supertest'), ghost = require('../../../../../core'), request; - describe('Authentication API', function () { var accesstoken = ''; @@ -38,7 +37,7 @@ describe('Authentication API', function () { it('can authenticate', function (done) { request.post(testUtils.API.getApiQuery('authentication/token')) - .send({ grant_type: 'password', username: user.email, password: user.password, client_id: 'ghost-admin'}) + .send({grant_type: 'password', username: user.email, password: user.password, client_id: 'ghost-admin'}) .expect('Content-Type', /json/) .expect(200) .end(function (err, res) { @@ -57,7 +56,7 @@ describe('Authentication API', function () { it('can\'t authenticate unknown user', function (done) { request.post(testUtils.API.getApiQuery('authentication/token')) - .send({ grant_type: 'password', username: 'invalid@email.com', password: user.password, client_id: 'ghost-admin'}) + .send({grant_type: 'password', username: 'invalid@email.com', password: user.password, client_id: 'ghost-admin'}) .expect('Content-Type', /json/) .expect(404) .end(function (err, res) { @@ -73,7 +72,7 @@ describe('Authentication API', function () { it('can\'t authenticate invalid password user', function (done) { request.post(testUtils.API.getApiQuery('authentication/token')) - .send({ grant_type: 'password', username: user.email, password: 'invalid', client_id: 'ghost-admin'}) + .send({grant_type: 'password', username: user.email, password: 'invalid', client_id: 'ghost-admin'}) .expect('Content-Type', /json/) .expect(401) .end(function (err, res) { @@ -89,7 +88,7 @@ describe('Authentication API', function () { it('can request new access token', function (done) { request.post(testUtils.API.getApiQuery('authentication/token')) - .send({ grant_type: 'password', username: user.email, password: user.password, client_id: 'ghost-admin'}) + .send({grant_type: 'password', username: user.email, password: user.password, client_id: 'ghost-admin'}) .expect('Content-Type', /json/) .expect(200) .end(function (err, res) { @@ -98,7 +97,7 @@ describe('Authentication API', function () { } var refreshToken = res.body.refresh_token; request.post(testUtils.API.getApiQuery('authentication/token')) - .send({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: 'ghost-admin'}) + .send({grant_type: 'refresh_token', refresh_token: refreshToken, client_id: 'ghost-admin'}) .expect('Content-Type', /json/) .expect(200) .end(function (err, res) { @@ -115,7 +114,7 @@ describe('Authentication API', function () { it('can\'t request new access token with invalid refresh token', function (done) { request.post(testUtils.API.getApiQuery('authentication/token')) - .send({ grant_type: 'refresh_token', refresh_token: 'invalid', client_id: 'ghost-admin'}) + .send({grant_type: 'refresh_token', refresh_token: 'invalid', client_id: 'ghost-admin'}) .expect('Content-Type', /json/) .expect(403) .end(function (err, res) { diff --git a/core/test/functional/routes/api/db_test.js b/core/test/functional/routes/api/db_test.js index ef75726c9d..d33384d4e8 100644 --- a/core/test/functional/routes/api/db_test.js +++ b/core/test/functional/routes/api/db_test.js @@ -7,7 +7,6 @@ var supertest = require('supertest'), ghost = require('../../../../../core'), request; - describe('DB API', function () { var accesstoken = ''; diff --git a/core/test/functional/routes/api/error_test.js b/core/test/functional/routes/api/error_test.js index e7b79d52d5..39dbecc118 100644 --- a/core/test/functional/routes/api/error_test.js +++ b/core/test/functional/routes/api/error_test.js @@ -14,7 +14,6 @@ var supertest = require('supertest'), request; describe('Unauthorized', function () { - before(function (done) { var app = express(); @@ -31,7 +30,6 @@ describe('Unauthorized', function () { }).catch(done); }); - describe('Unauthorized API', function () { it('can\'t retrieve posts', function (done) { request.get(testUtils.API.getApiQuery('posts/')) @@ -45,13 +43,9 @@ describe('Unauthorized', function () { res.should.be.json; var jsonResponse = res.body; jsonResponse.should.exist; - //TODO: testUtils.API.checkResponseValue(jsonResponse, ['error']); + // TODO: testUtils.API.checkResponseValue(jsonResponse, ['error']); done(); - }); }); - }); - - }); diff --git a/core/test/functional/routes/api/notifications_test.js b/core/test/functional/routes/api/notifications_test.js index 1baa26c85f..05eb93ffc2 100644 --- a/core/test/functional/routes/api/notifications_test.js +++ b/core/test/functional/routes/api/notifications_test.js @@ -18,7 +18,6 @@ describe('Notifications API', function () { // TODO: prevent db init, and manage bringing up the DB with fixtures ourselves ghost({app: app}).then(function () { request = supertest.agent(app); - }).then(function () { return testUtils.doAuth(request); }).then(function (token) { @@ -45,7 +44,7 @@ describe('Notifications API', function () { it('creates a new notification', function (done) { request.post(testUtils.API.getApiQuery('notifications/')) .set('Authorization', 'Bearer ' + accesstoken) - .send({ notifications: [newNotification] }) + .send({notifications: [newNotification]}) .expect('Content-Type', /json/) .expect(201) .end(function (err, res) { @@ -79,7 +78,7 @@ describe('Notifications API', function () { // create the notification that is to be deleted request.post(testUtils.API.getApiQuery('notifications/')) .set('Authorization', 'Bearer ' + accesstoken) - .send({ notifications: [newNotification] }) + .send({notifications: [newNotification]}) .expect('Content-Type', /json/) .expect(201) .end(function (err, res) { @@ -87,7 +86,7 @@ describe('Notifications API', function () { return done(err); } - var location = res.headers['location'], + var location = res.headers.location, jsonResponse = res.body; jsonResponse.notifications.should.exist; diff --git a/core/test/functional/routes/api/posts_test.js b/core/test/functional/routes/api/posts_test.js index 2a2fdbd29a..bfba99f182 100644 --- a/core/test/functional/routes/api/posts_test.js +++ b/core/test/functional/routes/api/posts_test.js @@ -10,7 +10,6 @@ var testUtils = require('../../../utils'), request; - describe('Post API', function () { var accesstoken = ''; @@ -21,7 +20,6 @@ describe('Post API', function () { // TODO: prevent db init, and manage bringing up the DB with fixtures ourselves ghost({app: app}).then(function () { request = supertest.agent(app); - }).then(function () { return testUtils.doAuth(request, 'posts'); }).then(function (token) { @@ -40,7 +38,6 @@ describe('Post API', function () { }); describe('Browse', function () { - it('retrieves all published posts only by default', function (done) { request.get(testUtils.API.getApiQuery('posts/')) .set('Authorization', 'Bearer ' + accesstoken) @@ -83,7 +80,6 @@ describe('Post API', function () { testUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination'); done(); }); - }); // Test bits of the API we don't use in the app yet to ensure the API behaves properly @@ -152,7 +148,6 @@ describe('Post API', function () { }); }); - // ## Read describe('Read', function () { it('can retrieve a post by id', function (done) { @@ -310,7 +305,6 @@ describe('Post API', function () { done(); }); }); - }); // ## Add @@ -333,7 +327,7 @@ describe('Post API', function () { } var draftPost = res.body; - res.headers['location'].should.equal('/ghost/api/v0.1/posts/' + draftPost.posts[0].id + '/?status=draft'); + res.headers.location.should.equal('/ghost/api/v0.1/posts/' + draftPost.posts[0].id + '/?status=draft'); draftPost.posts.should.exist; draftPost.posts.length.should.be.above(0); draftPost.posts[0].title.should.eql(newTitle); @@ -403,10 +397,8 @@ describe('Post API', function () { done(); }); }); - }); }); - }); // ## edit @@ -466,7 +458,7 @@ describe('Post API', function () { } var draftPost = res.body; - res.headers['location'].should.equal('/ghost/api/v0.1/posts/' + draftPost.posts[0].id + '/?status=draft'); + res.headers.location.should.equal('/ghost/api/v0.1/posts/' + draftPost.posts[0].id + '/?status=draft'); draftPost.posts.should.exist; draftPost.posts.length.should.be.above(0); draftPost.posts[0].title.should.eql(newTitle); @@ -509,7 +501,7 @@ describe('Post API', function () { } var draftPost = res.body; - res.headers['location'].should.equal('/ghost/api/v0.1/posts/' + draftPost.posts[0].id + '/?status=published'); + res.headers.location.should.equal('/ghost/api/v0.1/posts/' + draftPost.posts[0].id + '/?status=published'); draftPost.posts.should.exist; draftPost.posts.length.should.be.above(0); draftPost.posts[0].title.should.eql(newTitle); @@ -740,7 +732,6 @@ describe('Post API', function () { }); }); }); - }); // ## delete @@ -826,7 +817,6 @@ describe('Post API', function () { }); }); }); - }); describe('Dated Permalinks', function () { diff --git a/core/test/functional/routes/api/settings_test.js b/core/test/functional/routes/api/settings_test.js index e9a5e8e370..4e0f534cf2 100644 --- a/core/test/functional/routes/api/settings_test.js +++ b/core/test/functional/routes/api/settings_test.js @@ -111,7 +111,7 @@ describe('Settings API', function () { changedValue = 'Ghost changed', settingToChange = { settings: [ - { key: 'title', value: changedValue } + {key: 'title', value: changedValue} ] }; @@ -167,7 +167,6 @@ describe('Settings API', function () { }); }); - it('can\'t edit non existent setting', function (done) { request.get(testUtils.API.getApiQuery('settings/')) .set('Authorization', 'Bearer ' + accesstoken) @@ -181,7 +180,7 @@ describe('Settings API', function () { newValue = 'new value'; jsonResponse.should.exist; should.exist(jsonResponse.settings); - jsonResponse.settings = [{ key: 'testvalue', value: newValue }]; + jsonResponse.settings = [{key: 'testvalue', value: newValue}]; request.put(testUtils.API.getApiQuery('settings/')) .set('Authorization', 'Bearer ' + accesstoken) @@ -201,6 +200,4 @@ describe('Settings API', function () { }); }); }); - - }); diff --git a/core/test/functional/routes/api/tags_test.js b/core/test/functional/routes/api/tags_test.js index c9bc8bfaa3..7a64d2c435 100644 --- a/core/test/functional/routes/api/tags_test.js +++ b/core/test/functional/routes/api/tags_test.js @@ -57,6 +57,4 @@ describe('Tag API', function () { done(); }); }); - - }); diff --git a/core/test/functional/routes/api/users_test.js b/core/test/functional/routes/api/users_test.js index e303e1e9f1..cb03b42f7b 100644 --- a/core/test/functional/routes/api/users_test.js +++ b/core/test/functional/routes/api/users_test.js @@ -37,7 +37,6 @@ describe('User API', function () { }); describe('Browse', function () { - it('returns dates in ISO 8601 format', function (done) { request.get(testUtils.API.getApiQuery('users/')) .set('Authorization', 'Bearer ' + accesstoken) @@ -294,7 +293,7 @@ describe('User API', function () { jsonResponse.users[0].should.exist; testUtils.API.checkResponse(jsonResponse.users[0], 'user', ['roles']); - dataToSend = { users: [ + dataToSend = {users: [ {website: changedValue} ]}; @@ -346,7 +345,6 @@ describe('User API', function () { done(); }); - }); }); }); diff --git a/core/test/functional/routes/frontend_test.js b/core/test/functional/routes/frontend_test.js index ebe03da630..e8d226e1f9 100644 --- a/core/test/functional/routes/frontend_test.js +++ b/core/test/functional/routes/frontend_test.js @@ -14,10 +14,10 @@ var request = require('supertest'), ghost = require('../../../../core'), cacheRules = { - 'public': 'public, max-age=0', - 'hour': 'public, max-age=' + testUtils.ONE_HOUR_S, - 'year': 'public, max-age=' + testUtils.ONE_YEAR_S, - 'private': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0' + public: 'public, max-age=0', + hour: 'public, max-age=' + testUtils.ONE_HOUR_S, + year: 'public, max-age=' + testUtils.ONE_YEAR_S, + private: 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0' }; describe('Frontend Routing', function () { @@ -103,7 +103,7 @@ describe('Frontend Routing', function () { var date = moment().format('YYYY/MM/DD'); request.get('/' + date + '/welcome-to-ghost/') - //.expect('Cache-Control', cacheRules['private']) + // .expect('Cache-Control', cacheRules['private']) .expect(404) .expect(/Page Not Found/) .end(doEnd(done)); @@ -222,7 +222,6 @@ describe('Frontend Routing', function () { // ### The rest of the tests require more data describe('Archive pages', function () { - // Add enough posts to trigger pages for both the archive (5 pp) and rss (15 pp) // insertPosts adds 5 published posts, 1 draft post, 1 published static page and one draft page // we then insert with max 11 which ensures we have 16 published posts @@ -477,14 +476,12 @@ describe('Frontend Routing', function () { }); describe('Tag pages', function () { - // Add enough posts to trigger tag pages before(function (done) { testUtils.clearData().then(function () { // we initialise data, but not a user. No user should be required for navigating the frontend return testUtils.initData(); }).then(function () { - return testUtils.fixtures.insertPosts(); }).then(function () { return testUtils.fixtures.insertMorePosts(22); @@ -493,7 +490,6 @@ describe('Frontend Routing', function () { }).then(function () { done(); }).catch(done); - }); it('should redirect without slash', function (done) { @@ -539,14 +535,12 @@ describe('Frontend Routing', function () { }); describe('Author pages', function () { - // Add enough posts to trigger tag pages before(function (done) { testUtils.clearData().then(function () { // we initialise data, but not a user. No user should be required for navigating the frontend return testUtils.initData(); }).then(function () { - return testUtils.fixtures.insertPosts(); }).then(function () { return testUtils.fixtures.insertMorePosts(10); @@ -597,7 +591,6 @@ describe('Frontend Routing', function () { }); }); - // ### The rest of the tests switch to date permalinks // describe('Date permalinks', function () { @@ -618,8 +611,4 @@ describe('Frontend Routing', function () { // .end(doEnd(done)); // }); // }); - }); - - - diff --git a/core/test/functional/setup/setup_test.js b/core/test/functional/setup/setup_test.js index 7d73b02329..f853748c23 100644 --- a/core/test/functional/setup/setup_test.js +++ b/core/test/functional/setup/setup_test.js @@ -9,7 +9,7 @@ CasperTest.begin('Ghost setup fails properly', 6, function suite(test) { }); casper.then(function setupWithShortPassword() { - casper.fillAndAdd('#setup', { 'blog-title': 'ghost', name: 'slimer', email: email, password: 'short' }); + casper.fillAndAdd('#setup', {'blog-title': 'ghost', name: 'slimer', email: email, password: 'short'}); }); // should now throw a short password error @@ -21,7 +21,7 @@ CasperTest.begin('Ghost setup fails properly', 6, function suite(test) { }); casper.then(function setupWithLongPassword() { - casper.fillAndAdd('#setup', { 'blog-title': 'ghost', name: 'slimer', email: email, password: password }); + casper.fillAndAdd('#setup', {'blog-title': 'ghost', name: 'slimer', email: email, password: password}); }); // This can take quite a long time diff --git a/core/test/integration/api/api_authentication_spec.js b/core/test/integration/api/api_authentication_spec.js index 9959a3d648..9521bbd7a4 100644 --- a/core/test/integration/api/api_authentication_spec.js +++ b/core/test/integration/api/api_authentication_spec.js @@ -17,9 +17,7 @@ describe('Authentication API', function () { should.exist(AuthAPI); describe('Setup', function () { - describe('Not completed', function () { - // TODO: stub settings beforeEach(testUtils.setup('roles', 'owner:pre', 'settings', 'perms:setting', 'perms:mail', 'perms:init')); @@ -46,7 +44,7 @@ describe('Authentication API', function () { return Promise.resolve(); }); - AuthAPI.setup({ setup: [setupData] }).then(function (result) { + AuthAPI.setup({setup: [setupData]}).then(function (result) { should.exist(result); should.exist(result.users); should.not.exist(result.meta); @@ -67,7 +65,6 @@ describe('Authentication API', function () { }); describe('Completed', function () { - beforeEach(testUtils.setup('owner')); it('should report that setup has been completed', function (done) { @@ -87,7 +84,7 @@ describe('Authentication API', function () { title: 'a test blog' }; - AuthAPI.setup({ setup: [setupData] }).then(function () { + AuthAPI.setup({setup: [setupData]}).then(function () { done(new Error('Setup was able to be run')); }).catch(function (err) { should.exist(err); diff --git a/core/test/integration/api/api_configuration_spec.js b/core/test/integration/api/api_configuration_spec.js index cf0175414b..4e8e674769 100644 --- a/core/test/integration/api/api_configuration_spec.js +++ b/core/test/integration/api/api_configuration_spec.js @@ -2,7 +2,7 @@ /*jshint expr:true*/ var testUtils = require('../../utils'), should = require('should'), - + rewire = require('rewire'), _ = require('lodash'), config = rewire('../../../server/config'), @@ -12,18 +12,18 @@ var testUtils = require('../../utils'), describe('Configuration API', function () { var newConfig = { - 'fileStorage': true, - 'apps': true, - 'version': '0.5.0', - 'environment': process.env.NODE_ENV, - 'database': { - 'client': 'mysql' - }, - 'mail': { - 'transport': 'SMTP' - }, - 'blogUrl': 'http://local.tryghost.org' - }; + fileStorage: true, + apps: true, + version: '0.5.0', + environment: process.env.NODE_ENV, + database: { + client: 'mysql' + }, + mail: { + transport: 'SMTP' + }, + blogUrl: 'http://local.tryghost.org' + }; // Keep the DB clean before(testUtils.teardown); @@ -35,7 +35,7 @@ describe('Configuration API', function () { var updatedConfig = _.extend(config, newConfig); config.set(updatedConfig); ConfigurationAPI.__set__('config', updatedConfig); - + ConfigurationAPI.browse(testUtils.context.owner).then(function (response) { should.exist(response); should.exist(response.configuration); @@ -52,8 +52,8 @@ describe('Configuration API', function () { var updatedConfig = _.extend(config, newConfig); config.set(updatedConfig); ConfigurationAPI.__set__('config', updatedConfig); - - ConfigurationAPI.read(_.extend(testUtils.context.owner, { key: 'database' })).then(function (response) { + + ConfigurationAPI.read(_.extend(testUtils.context.owner, {key: 'database'})).then(function (response) { should.exist(response); should.exist(response.configuration); testUtils.API.checkResponse(response.configuration[0], 'configuration'); @@ -66,4 +66,4 @@ describe('Configuration API', function () { done(); }).catch(done); }); -}); \ No newline at end of file +}); diff --git a/core/test/integration/api/api_db_spec.js b/core/test/integration/api/api_db_spec.js index 386d67dc74..9a863aec88 100644 --- a/core/test/integration/api/api_db_spec.js +++ b/core/test/integration/api/api_db_spec.js @@ -8,8 +8,6 @@ var testUtils = require('../../utils'), ModelTag = require('../../../server/models/tag'), ModelPost = require('../../../server/models/post'); - - describe('DB API', function () { // Keep the DB clean before(testUtils.teardown); @@ -112,4 +110,4 @@ describe('DB API', function () { done(); }).catch(done); }); -}); \ No newline at end of file +}); diff --git a/core/test/integration/api/api_mail_spec.js b/core/test/integration/api/api_mail_spec.js index 9bff4b8936..24498e8f8f 100644 --- a/core/test/integration/api/api_mail_spec.js +++ b/core/test/integration/api/api_mail_spec.js @@ -116,8 +116,6 @@ describe('Mail API Direct', function () { }); }); - - describe('Mail API Stub', function () { // Keep the DB clean @@ -150,7 +148,6 @@ describe('Mail API Stub', function () { mailer.transport.transportType.should.eql('STUB'); return MailAPI.send(mailDataNoServer, testUtils.context.internal); }).then(function (response) { - /*jshint unused:false */ done(); }).catch(function (error) { diff --git a/core/test/integration/api/api_notifications_spec.js b/core/test/integration/api/api_notifications_spec.js index c875114938..6d7730beb9 100644 --- a/core/test/integration/api/api_notifications_spec.js +++ b/core/test/integration/api/api_notifications_spec.js @@ -8,7 +8,6 @@ var testUtils = require('../../utils'), NotificationsAPI = require('../../../server/api/notifications'); describe('Notifications API', function () { - // Keep the DB clean before(testUtils.teardown); afterEach(testUtils.teardown); @@ -22,7 +21,7 @@ describe('Notifications API', function () { message: 'Hello, this is dog' }; - NotificationsAPI.add({ notifications: [msg] }, testUtils.context.internal).then(function (result) { + NotificationsAPI.add({notifications: [msg]}, testUtils.context.internal).then(function (result) { var notification; should.exist(result); @@ -43,7 +42,7 @@ describe('Notifications API', function () { message: 'Hello, this is dog' }; - NotificationsAPI.add({ notifications: [msg] }, testUtils.context.owner).then(function (result) { + NotificationsAPI.add({notifications: [msg]}, testUtils.context.owner).then(function (result) { var notification; should.exist(result); @@ -65,7 +64,7 @@ describe('Notifications API', function () { id: 99 }; - NotificationsAPI.add({ notifications: [msg] }, testUtils.context.internal).then(function (result) { + NotificationsAPI.add({notifications: [msg]}, testUtils.context.internal).then(function (result) { var notification; should.exist(result); @@ -86,7 +85,7 @@ describe('Notifications API', function () { type: 'error', // this can be 'error', 'success', 'warn' and 'info' message: 'This is an error' // A string. Should fit in one line. }; - NotificationsAPI.add({ notifications: [msg] }, testUtils.context.internal).then(function () { + NotificationsAPI.add({notifications: [msg]}, testUtils.context.internal).then(function () { NotificationsAPI.browse(testUtils.context.internal).then(function (results) { should.exist(results); should.exist(results.notifications); @@ -102,7 +101,7 @@ describe('Notifications API', function () { type: 'error', // this can be 'error', 'success', 'warn' and 'info' message: 'This is an error' // A string. Should fit in one line. }; - NotificationsAPI.add({ notifications: [msg] }, testUtils.context.owner).then(function () { + NotificationsAPI.add({notifications: [msg]}, testUtils.context.owner).then(function () { NotificationsAPI.browse(testUtils.context.owner).then(function (results) { should.exist(results); should.exist(results.notifications); @@ -113,26 +112,24 @@ describe('Notifications API', function () { }); }); - - it('can destroy (internal)', function (done) { var msg = { type: 'error', message: 'Goodbye, cruel world!' }; - NotificationsAPI.add({ notifications: [msg] }, testUtils.context.internal).then(function (result) { + NotificationsAPI.add({notifications: [msg]}, testUtils.context.internal).then(function (result) { var notification = result.notifications[0]; NotificationsAPI.destroy( _.extend(testUtils.context.internal, {id: notification.id}) ).then(function (result) { - should.exist(result); - should.exist(result.notifications); - result.notifications[0].id.should.equal(notification.id); + should.exist(result); + should.exist(result.notifications); + result.notifications[0].id.should.equal(notification.id); - done(); - }).catch(done); + done(); + }).catch(done); }); }); @@ -142,18 +139,18 @@ describe('Notifications API', function () { message: 'Goodbye, cruel world!' }; - NotificationsAPI.add({ notifications: [msg] }, testUtils.context.internal).then(function (result) { + NotificationsAPI.add({notifications: [msg]}, testUtils.context.internal).then(function (result) { var notification = result.notifications[0]; NotificationsAPI.destroy( _.extend(testUtils.context.owner, {id: notification.id}) ).then(function (result) { - should.exist(result); - should.exist(result.notifications); - result.notifications[0].id.should.equal(notification.id); + should.exist(result); + should.exist(result.notifications); + result.notifications[0].id.should.equal(notification.id); - done(); - }).catch(done); + done(); + }).catch(done); }); }); }); diff --git a/core/test/integration/api/api_posts_spec.js b/core/test/integration/api/api_posts_spec.js index 112ef0aaf5..b0960eacea 100644 --- a/core/test/integration/api/api_posts_spec.js +++ b/core/test/integration/api/api_posts_spec.js @@ -8,14 +8,13 @@ var testUtils = require('../../utils'), PostAPI = require('../../../server/api/posts'); describe('Post API', function () { - // Keep the DB clean before(testUtils.teardown); afterEach(testUtils.teardown); beforeEach(testUtils.setup('users:roles', 'perms:post', 'posts', 'perms:init')); function extractFirstPost(posts) { - return _.filter(posts, { id: 1 })[0]; + return _.filter(posts, {id: 1})[0]; } should.exist(PostAPI); @@ -57,4 +56,4 @@ describe('Post API', function () { done(); }).catch(done); }); -}); \ No newline at end of file +}); diff --git a/core/test/integration/api/api_roles_spec.js b/core/test/integration/api/api_roles_spec.js index 10af87eb4a..7a4557bb7e 100644 --- a/core/test/integration/api/api_roles_spec.js +++ b/core/test/integration/api/api_roles_spec.js @@ -121,4 +121,4 @@ describe('Roles API', function () { }).catch(done); }); }); -}); \ No newline at end of file +}); diff --git a/core/test/integration/api/api_settings_spec.js b/core/test/integration/api/api_settings_spec.js index d42f952eda..5508595791 100644 --- a/core/test/integration/api/api_settings_spec.js +++ b/core/test/integration/api/api_settings_spec.js @@ -12,7 +12,6 @@ var testUtils = require('../../utils'), getErrorDetails; describe('Settings API', function () { - // Keep the DB clean before(testUtils.teardown); afterEach(testUtils.teardown); @@ -64,7 +63,6 @@ describe('Settings API', function () { }).catch(getErrorDetails(done)); }); - it('can browse by type', function (done) { return callApiWithContext(defaultContext, 'browse', {type: 'blog'}).then(function (results) { should.exist(results); @@ -126,7 +124,7 @@ describe('Settings API', function () { }); it('can read by object key', function (done) { - return callApiWithContext(defaultContext, 'read', { key: 'title' }).then(function (response) { + return callApiWithContext(defaultContext, 'read', {key: 'title'}).then(function (response) { should.exist(response); testUtils.API.checkResponse(response, 'settings'); response.settings.length.should.equal(1); @@ -137,7 +135,7 @@ describe('Settings API', function () { }); it('can edit', function (done) { - return callApiWithContext(defaultContext, 'edit', {settings: [{ key: 'title', value: 'UpdatedGhost'}]}, {}) + return callApiWithContext(defaultContext, 'edit', {settings: [{key: 'title', value: 'UpdatedGhost'}]}, {}) .then(function (response) { should.exist(response); testUtils.API.checkResponse(response, 'settings'); @@ -149,7 +147,7 @@ describe('Settings API', function () { }); it('cannot edit a core setting if not an internal request', function (done) { - return callApiWithContext(defaultContext, 'edit', {settings: [{ key: 'databaseVersion', value: '999'}]}, {}) + return callApiWithContext(defaultContext, 'edit', {settings: [{key: 'databaseVersion', value: '999'}]}, {}) .then(function () { done(new Error('Allowed to edit a core setting as external request')); }).catch(function (err) { @@ -162,7 +160,7 @@ describe('Settings API', function () { }); it('can edit a core setting with an internal request', function (done) { - return callApiWithContext(internalContext, 'edit', {settings: [{ key: 'databaseVersion', value: '999'}]}, {}) + return callApiWithContext(internalContext, 'edit', {settings: [{key: 'databaseVersion', value: '999'}]}, {}) .then(function (response) { should.exist(response); testUtils.API.checkResponse(response, 'settings'); @@ -187,7 +185,7 @@ describe('Settings API', function () { it('does not allow an active theme which is not installed', function (done) { return callApiWithContext(defaultContext, 'edit', 'activeTheme', { - settings: [{ key: 'activeTheme', value: 'rasper' }] + settings: [{key: 'activeTheme', value: 'rasper'}] }).then(function () { done(new Error('Allowed to set an active theme which is not installed')); }).catch(function (err) { diff --git a/core/test/integration/api/api_slugs_spec.js b/core/test/integration/api/api_slugs_spec.js index 0c5830597f..c010904112 100644 --- a/core/test/integration/api/api_slugs_spec.js +++ b/core/test/integration/api/api_slugs_spec.js @@ -15,7 +15,7 @@ describe('Slug API', function () { should.exist(SlugAPI); it('can generate post slug', function (done) { - SlugAPI.generate({ context: { user: 1 }, type: 'post', name: 'A fancy Title' }) + SlugAPI.generate({context: {user: 1}, type: 'post', name: 'A fancy Title'}) .then(function (results) { should.exist(results); testUtils.API.checkResponse(results, 'slugs'); @@ -27,7 +27,7 @@ describe('Slug API', function () { }); it('can generate tag slug', function (done) { - SlugAPI.generate({ context: { user: 1 }, type: 'tag', name: 'A fancy Title' }) + SlugAPI.generate({context: {user: 1}, type: 'tag', name: 'A fancy Title'}) .then(function (results) { should.exist(results); testUtils.API.checkResponse(results, 'slugs'); @@ -39,7 +39,7 @@ describe('Slug API', function () { }); it('can generate user slug', function (done) { - SlugAPI.generate({ context: { user: 1 }, type: 'tag', name: 'user name' }) + SlugAPI.generate({context: {user: 1}, type: 'tag', name: 'user name'}) .then(function (results) { should.exist(results); testUtils.API.checkResponse(results, 'slugs'); @@ -51,7 +51,7 @@ describe('Slug API', function () { }); it('can generate app slug', function (done) { - SlugAPI.generate({ context: { user: 1 }, type: 'tag', name: 'app name' }) + SlugAPI.generate({context: {user: 1}, type: 'tag', name: 'app name'}) .then(function (results) { should.exist(results); testUtils.API.checkResponse(results, 'slugs'); @@ -63,7 +63,7 @@ describe('Slug API', function () { }); it('rejects unknown types', function (done) { - SlugAPI.generate({ context: { user: 1 }, type: 'unknown type', name: 'A fancy Title' }) + SlugAPI.generate({context: {user: 1}, type: 'unknown type', name: 'A fancy Title'}) .then(function () { done(new Error('Generate a slug for an unknown type is not rejected.')); }).catch(function (error) { @@ -71,5 +71,4 @@ describe('Slug API', function () { done(); }).catch(done); }); - -}); \ No newline at end of file +}); diff --git a/core/test/integration/api/api_tags_spec.js b/core/test/integration/api/api_tags_spec.js index d52b635196..fb251af9f3 100644 --- a/core/test/integration/api/api_tags_spec.js +++ b/core/test/integration/api/api_tags_spec.js @@ -73,4 +73,4 @@ describe('Tags API', function () { done(); }).catch(done); }); -}); \ No newline at end of file +}); diff --git a/core/test/integration/api/api_themes_spec.js b/core/test/integration/api/api_themes_spec.js index af8ac459b1..70c7701828 100644 --- a/core/test/integration/api/api_themes_spec.js +++ b/core/test/integration/api/api_themes_spec.js @@ -13,7 +13,6 @@ var _ = require('lodash'), sandbox = sinon.sandbox.create(); - describe('Themes API', function () { var config, configStub; @@ -30,22 +29,22 @@ describe('Themes API', function () { beforeEach(function () { // Override settings.read for activeTheme sandbox.stub(SettingsAPI, 'read', function () { - return Promise.resolve({ settings: [{value: 'casper'}] }); + return Promise.resolve({settings: [{value: 'casper'}]}); }); sandbox.stub(SettingsAPI, 'edit', function () { - return Promise.resolve({ settings: [{value: 'rasper'}] }); + return Promise.resolve({settings: [{value: 'rasper'}]}); }); configStub = { - 'paths': { - 'subdir': '', - 'availableThemes': { - 'casper': { - 'package.json': { name: 'Casper', version: '0.9.3' } + paths: { + subdir: '', + availableThemes: { + casper: { + 'package.json': {name: 'Casper', version: '0.9.3'} }, - 'rasper': { - 'package.json': { name: 'Rasper', version: '0.9.6' } + rasper: { + 'package.json': {name: 'Rasper', version: '0.9.6'} } } } @@ -53,7 +52,6 @@ describe('Themes API', function () { config = ThemeAPI.__get__('config'); _.extend(config, configStub); - }); should.exist(ThemeAPI); @@ -70,7 +68,7 @@ describe('Themes API', function () { }); it('can edit', function (done) { - ThemeAPI.edit({themes: [{uuid: 'rasper', active: true }]}, testUtils.context.owner).then(function (result) { + ThemeAPI.edit({themes: [{uuid: 'rasper', active: true}]}, testUtils.context.owner).then(function (result) { should.exist(result); should.exist(result.themes); result.themes.length.should.be.above(0); diff --git a/core/test/integration/api/api_upload_spec.js b/core/test/integration/api/api_upload_spec.js index 4eb5260d82..8810093f6b 100644 --- a/core/test/integration/api/api_upload_spec.js +++ b/core/test/integration/api/api_upload_spec.js @@ -77,7 +77,6 @@ describe('Upload API', function () { result.should.equal('URL'); done(); }); - }); it('cannot upload jpg with incorrect extension', function (done) { @@ -119,4 +118,4 @@ describe('Upload API', function () { }); }); }); -}); \ No newline at end of file +}); diff --git a/core/test/integration/api/api_users_spec.js b/core/test/integration/api/api_users_spec.js index b3a6c7b624..cff6c3c1d4 100644 --- a/core/test/integration/api/api_users_spec.js +++ b/core/test/integration/api/api_users_spec.js @@ -26,8 +26,8 @@ describe('Users API', function () { it('dateTime fields are returned as Date objects', function (done) { var userData = testUtils.DataGenerator.forModel.users[0]; - ModelUser.User.check({ email: userData.email, password: userData.password }).then(function (user) { - return UserAPI.read({ id: user.id }); + ModelUser.User.check({email: userData.email, password: userData.password}).then(function (user) { + return UserAPI.read({id: user.id}); }).then(function (response) { response.users[0].created_at.should.be.an.instanceof(Date); response.users[0].updated_at.should.be.an.instanceof(Date); @@ -87,7 +87,7 @@ describe('Users API', function () { it('Can browse invited/invited-pending (admin)', function (done) { testUtils.fixtures.createInvitedUsers().then(function () { - UserAPI.browse(_.extend(testUtils.context.admin, { status: 'invited' })).then(function (response) { + UserAPI.browse(_.extend(testUtils.context.admin, {status: 'invited'})).then(function (response) { should.exist(response); testUtils.API.checkResponse(response, 'users'); should.exist(response.users); @@ -116,7 +116,7 @@ describe('Users API', function () { }); it('Can browse all', function (done) { - UserAPI.browse(_.extend(testUtils.context.admin, { status: 'all'})).then(function (response) { + UserAPI.browse(_.extend(testUtils.context.admin, {status: 'all'})).then(function (response) { checkBrowseResponse(response, 7); done(); }).catch(done); @@ -140,7 +140,6 @@ describe('Users API', function () { }).catch(done); }); - it('Admin can read', function (done) { UserAPI.read(_.extend({}, context.admin, {id: userIdFor.owner})).then(function (response) { checkReadResponse(response); @@ -191,7 +190,6 @@ describe('Users API', function () { return UserAPI.edit({users: [{name: newName}]}, _.extend({}, context.owner, {id: userIdFor.admin})); }).then(function (response) { - checkEditResponse(response); return UserAPI.edit({users: [{name: newName}]}, _.extend({}, context.owner, {id: userIdFor.editor})); }).then(function (response) { @@ -212,7 +210,6 @@ describe('Users API', function () { return UserAPI.edit({users: [{name: newName}]}, _.extend({}, context.admin, {id: userIdFor.admin})); }).then(function (response) { - checkEditResponse(response); return UserAPI.edit({users: [{name: newName}]}, _.extend({}, context.admin, {id: userIdFor.editor})); }).then(function (response) { @@ -316,9 +313,9 @@ describe('Users API', function () { UserAPI.edit( {users: [{name: newName, roles: [roleIdFor.author]}]}, _.extend({}, context.author, {id: userIdFor.author}) ).then(function (response) { - checkEditResponse(response); - done(); - }).catch(done); + checkEditResponse(response); + done(); + }).catch(done); }); it('Author can edit self with role set as string', function (done) { @@ -326,9 +323,9 @@ describe('Users API', function () { UserAPI.edit( {users: [{name: newName, roles: [roleIdFor.author.toString()]}]}, _.extend({}, context.author, {id: userIdFor.author}) ).then(function (response) { - checkEditResponse(response); - done(); - }).catch(done); + checkEditResponse(response); + done(); + }).catch(done); }); }); @@ -532,7 +529,6 @@ describe('Users API', function () { }); }); - describe('Destroy', function () { function checkDestroyResponse(response) { should.exist(response); @@ -543,7 +539,6 @@ describe('Users API', function () { response.users[0].created_at.should.be.a.Date; } - describe('Owner', function () { it('CANNOT destroy self', function (done) { UserAPI.destroy(_.extend({}, context.owner, {id: userIdFor.owner})) @@ -653,7 +648,6 @@ describe('Users API', function () { done(); }).catch(done); }); - }); describe('Author', function () { @@ -706,7 +700,6 @@ describe('Users API', function () { done(); }); }); - }); }); @@ -730,18 +723,17 @@ describe('Users API', function () { response.users[0].id.should.equal(userIdFor.author); response.users[0].roles[0].name.should.equal('Author'); - return UserAPI.edit( - {users: [ + return UserAPI.edit({ + users: [ {name: newName, roles: [roleIdFor.admin]} - ]}, - options - ).then(function (response) { - checkEditResponse(response); - response.users[0].id.should.equal(userIdFor.author); - response.users[0].roles[0].name.should.equal('Administrator'); + ] + }, options).then(function (response) { + checkEditResponse(response); + response.users[0].id.should.equal(userIdFor.author); + response.users[0].roles[0].name.should.equal('Administrator'); - done(); - }).catch(done); + done(); + }).catch(done); }); }); @@ -751,18 +743,17 @@ describe('Users API', function () { response.users[0].id.should.equal(userIdFor.admin); response.users[0].roles[0].name.should.equal('Administrator'); - return UserAPI.edit( - {users: [ + return UserAPI.edit({ + users: [ {name: newName, roles: [roleIdFor.editor]} - ]}, - options - ).then(function (response) { - checkEditResponse(response); - response.users[0].id.should.equal(userIdFor.admin); - response.users[0].roles[0].name.should.equal('Editor'); + ] + }, options).then(function (response) { + checkEditResponse(response); + response.users[0].id.should.equal(userIdFor.admin); + response.users[0].roles[0].name.should.equal('Editor'); - done(); - }).catch(done); + done(); + }).catch(done); }); }); @@ -772,18 +763,17 @@ describe('Users API', function () { response.users[0].id.should.equal(userIdFor.admin); response.users[0].roles[0].name.should.equal('Administrator'); - return UserAPI.edit( - {users: [ + return UserAPI.edit({ + users: [ {name: newName, roles: [roleIdFor.author]} - ]}, - options - ).then(function (response) { - checkEditResponse(response); - response.users[0].id.should.equal(userIdFor.admin); - response.users[0].roles[0].name.should.equal('Author'); + ] + }, options).then(function (response) { + checkEditResponse(response); + response.users[0].id.should.equal(userIdFor.admin); + response.users[0].roles[0].name.should.equal('Author'); - done(); - }).catch(done); + done(); + }).catch(done); }); }); }); @@ -795,18 +785,17 @@ describe('Users API', function () { response.users[0].id.should.equal(userIdFor.author); response.users[0].roles[0].name.should.equal('Author'); - return UserAPI.edit( - {users: [ + return UserAPI.edit({ + users: [ {name: newName, roles: [roleIdFor.admin]} - ]}, - options - ).then(function (response) { - checkEditResponse(response); - response.users[0].id.should.equal(userIdFor.author); - response.users[0].roles[0].name.should.equal('Administrator'); + ] + }, options).then(function (response) { + checkEditResponse(response); + response.users[0].id.should.equal(userIdFor.author); + response.users[0].roles[0].name.should.equal('Administrator'); - done(); - }).catch(done); + done(); + }).catch(done); }); }); @@ -816,18 +805,17 @@ describe('Users API', function () { response.users[0].id.should.equal(userIdFor.author); response.users[0].roles[0].name.should.equal('Author'); - return UserAPI.edit( - {users: [ + return UserAPI.edit({ + users: [ {name: newName, roles: [roleIdFor.editor]} - ]}, - options - ).then(function (response) { - checkEditResponse(response); - response.users[0].id.should.equal(userIdFor.author); - response.users[0].roles[0].name.should.equal('Editor'); + ] + }, options).then(function (response) { + checkEditResponse(response); + response.users[0].id.should.equal(userIdFor.author); + response.users[0].roles[0].name.should.equal('Editor'); - done(); - }).catch(done); + done(); + }).catch(done); }); }); @@ -837,18 +825,17 @@ describe('Users API', function () { response.users[0].id.should.equal(userIdFor.editor); response.users[0].roles[0].name.should.equal('Editor'); - return UserAPI.edit( - {users: [ + return UserAPI.edit({ + users: [ {name: newName, roles: [roleIdFor.author]} - ]}, - options - ).then(function (response) { - checkEditResponse(response); - response.users[0].id.should.equal(userIdFor.editor); - response.users[0].roles[0].name.should.equal('Author'); + ] + }, options).then(function (response) { + checkEditResponse(response); + response.users[0].id.should.equal(userIdFor.editor); + response.users[0].roles[0].name.should.equal('Author'); - done(); - }).catch(done); + done(); + }).catch(done); }); }); @@ -858,10 +845,9 @@ describe('Users API', function () { response.users[0].id.should.equal(userIdFor.owner); response.users[0].roles[0].name.should.equal('Owner'); - return UserAPI.edit( - { users: [{name: newName, roles: [roleIdFor.author]}]}, - options - ).then(function () { + return UserAPI.edit({ + users: [{name: newName, roles: [roleIdFor.author]}] + }, options).then(function () { done(new Error('Author should not be able to downgrade owner')); }).catch(function (error) { error.type.should.eql('NoPermissionError'); @@ -874,7 +860,7 @@ describe('Users API', function () { describe('Editor', function () { it('Can assign author role to author', function (done) { UserAPI.edit( - { users: [{name: newName, roles: [roleIdFor.author]}]}, + {users: [{name: newName, roles: [roleIdFor.author]}]}, _.extend({}, context.editor, {id: userIdFor.author2}, {include: 'roles'}) ).then(function (response) { checkEditResponse(response); @@ -887,7 +873,7 @@ describe('Users API', function () { it('CANNOT assign author role to self', function (done) { UserAPI.edit( - { users: [{name: newName, roles: [roleIdFor.author]}]}, + {users: [{name: newName, roles: [roleIdFor.author]}]}, _.extend({}, context.editor, {id: userIdFor.editor}, {include: 'roles'}) ).then(function () { done(new Error('Editor should not be able to upgrade their role')); @@ -899,7 +885,7 @@ describe('Users API', function () { it('CANNOT assign author role to other Editor', function (done) { UserAPI.edit( - { users: [{name: newName, roles: [roleIdFor.author]}]}, + {users: [{name: newName, roles: [roleIdFor.author]}]}, _.extend({}, context.editor, {id: userIdFor.editor2}, {include: 'roles'}) ).then(function () { done(new Error('Editor should not be able to change the roles of other editors')); @@ -911,7 +897,7 @@ describe('Users API', function () { it('CANNOT assign author role to admin', function (done) { UserAPI.edit( - { users: [{name: newName, roles: [roleIdFor.author]}]}, + {users: [{name: newName, roles: [roleIdFor.author]}]}, _.extend({}, context.editor, {id: userIdFor.admin}, {include: 'roles'}) ).then(function () { done(new Error('Editor should not be able to change the roles of admins')); @@ -922,7 +908,7 @@ describe('Users API', function () { }); it('CANNOT assign admin role to author', function (done) { UserAPI.edit( - { users: [{name: newName, roles: [roleIdFor.admin]}]}, + {users: [{name: newName, roles: [roleIdFor.admin]}]}, _.extend({}, context.editor, {id: userIdFor.author}, {include: 'roles'}) ).then(function () { done(new Error('Editor should not be able to upgrade the role of authors')); @@ -936,7 +922,7 @@ describe('Users API', function () { describe('Author', function () { it('CANNOT assign higher role to self', function (done) { UserAPI.edit( - { users: [{name: newName, roles: [roleIdFor.editor]}]}, + {users: [{name: newName, roles: [roleIdFor.editor]}]}, _.extend({}, context.author, {id: userIdFor.author}, {include: 'roles'}) ).then(function () { done(new Error('Author should not be able to upgrade their role')); @@ -952,7 +938,7 @@ describe('Users API', function () { it('Owner can transfer ownership', function (done) { // transfer ownership to admin user id:2 UserAPI.transferOwnership( - { owner: [{id: userIdFor.admin}]}, + {owner: [{id: userIdFor.admin}]}, context.owner ).then(function (response) { should.exist(response); @@ -968,7 +954,7 @@ describe('Users API', function () { it('Owner CANNOT downgrade own role', function (done) { // Cannot change own role to admin UserAPI.transferOwnership( - { owner: [{id: userIdFor.owner}]}, + {owner: [{id: userIdFor.owner}]}, context.owner ).then(function () { done(new Error('Owner should not be able to downgrade their role')); @@ -981,7 +967,7 @@ describe('Users API', function () { it('Admin CANNOT transfer ownership', function (done) { // transfer ownership to user id: 2 UserAPI.transferOwnership( - { owner: [{id: userIdFor.editor}]}, + {owner: [{id: userIdFor.editor}]}, context.admin ).then(function () { done(new Error('Admin is not denied transferring ownership.')); @@ -994,7 +980,7 @@ describe('Users API', function () { it('Editor CANNOT transfer ownership', function (done) { // transfer ownership to user id: 2 UserAPI.transferOwnership( - { owner: [{id: userIdFor.admin}]}, + {owner: [{id: userIdFor.admin}]}, context.editor ).then(function () { done(new Error('Admin is not denied transferring ownership.')); @@ -1007,7 +993,7 @@ describe('Users API', function () { it('Author CANNOT transfer ownership', function (done) { // transfer ownership to user id: 2 UserAPI.transferOwnership( - { owner: [{id: userIdFor.admin}]}, + {owner: [{id: userIdFor.admin}]}, context.author ).then(function () { done(new Error('Admin is not denied transferring ownership.')); diff --git a/core/test/integration/export_spec.js b/core/test/integration/export_spec.js index dfadb4b043..d14fb5e9b7 100644 --- a/core/test/integration/export_spec.js +++ b/core/test/integration/export_spec.js @@ -12,7 +12,6 @@ var testUtils = require('../utils/index'), sandbox = sinon.sandbox.create(); describe('Exporter', function () { - before(testUtils.teardown); afterEach(testUtils.teardown); afterEach(function () { diff --git a/core/test/integration/import_spec.js b/core/test/integration/import_spec.js index 8f65d2691d..6bd434deba 100644 --- a/core/test/integration/import_spec.js +++ b/core/test/integration/import_spec.js @@ -36,7 +36,6 @@ describe('Import', function () { should.exist(importer); describe('Resolves', function () { - beforeEach(testUtils.setup()); beforeEach(function () { var newConfig = _.extend(config, defaultConfig); @@ -50,7 +49,7 @@ describe('Import', function () { var importStub = sandbox.stub(Importer000, 'importData', function () { return Promise.resolve(); }), - fakeData = { test: true }; + fakeData = {test: true}; importer('000', fakeData).then(function () { importStub.calledWith(fakeData).should.equal(true); @@ -65,7 +64,7 @@ describe('Import', function () { var importStub = sandbox.stub(Importer001, 'importData', function () { return Promise.resolve(); }), - fakeData = { test: true }; + fakeData = {test: true}; importer('001', fakeData).then(function () { importStub.calledWith(fakeData).should.equal(true); @@ -80,7 +79,7 @@ describe('Import', function () { var importStub = sandbox.stub(Importer002, 'importData', function () { return Promise.resolve(); }), - fakeData = { test: true }; + fakeData = {test: true}; importer('002', fakeData).then(function () { importStub.calledWith(fakeData).should.equal(true); @@ -95,7 +94,7 @@ describe('Import', function () { var importStub = sandbox.stub(Importer003, 'importData', function () { return Promise.resolve(); }), - fakeData = { test: true }; + fakeData = {test: true}; importer('003', fakeData).then(function () { importStub.calledWith(fakeData).should.equal(true); @@ -163,7 +162,6 @@ describe('Import', function () { }); describe('001', function () { - before(function () { knex = config.database.knex; }); @@ -250,14 +248,13 @@ describe('Import', function () { testUtils.fixtures.loadExportFixture('export-001').then(function (exported) { exportData = exported; - //change title to 151 characters + // change title to 151 characters exportData.data.posts[0].title = new Array(152).join('a'); exportData.data.posts[0].tags = 'Tag'; return importer('001', exportData); }).then(function () { (1).should.eql(0, 'Data import should not resolve promise.'); }, function (error) { - error[0].message.should.eql('Value in [posts.title] exceeds maximum length of 150 characters.'); error[0].type.should.eql('ValidationError'); @@ -287,11 +284,8 @@ describe('Import', function () { settings.length.should.be.above(0, 'Wrong number of settings'); _.findWhere(settings, {key: 'databaseVersion'}).value.should.equal('003', 'Wrong database version'); - - done(); }); - }).catch(done); }); @@ -300,13 +294,12 @@ describe('Import', function () { testUtils.fixtures.loadExportFixture('export-001').then(function (exported) { exportData = exported; - //change to blank settings key + // change to blank settings key exportData.data.settings[3].key = null; return importer('001', exportData); }).then(function () { (1).should.eql(0, 'Data import should not resolve promise.'); }, function (error) { - error[0].message.should.eql('Value in [settings.key] cannot be blank.'); error[0].type.should.eql('ValidationError'); @@ -338,13 +331,11 @@ describe('Import', function () { done(); }); - }).catch(done); }); }); describe('002', function () { - before(function () { knex = config.database.knex; }); @@ -428,18 +419,16 @@ describe('Import', function () { it('doesn\'t import invalid post data from 002', function (done) { var exportData; - testUtils.fixtures.loadExportFixture('export-002').then(function (exported) { exportData = exported; - //change title to 151 characters + // change title to 151 characters exportData.data.posts[0].title = new Array(152).join('a'); exportData.data.posts[0].tags = 'Tag'; return importer('002', exportData); }).then(function () { (1).should.eql(0, 'Data import should not resolve promise.'); }, function (error) { - error[0].message.should.eql('Value in [posts.title] exceeds maximum length of 150 characters.'); error[0].type.should.eql('ValidationError'); @@ -470,7 +459,6 @@ describe('Import', function () { done(); }); - }).catch(done); }); @@ -479,13 +467,12 @@ describe('Import', function () { testUtils.fixtures.loadExportFixture('export-002').then(function (exported) { exportData = exported; - //change to blank settings key + // change to blank settings key exportData.data.settings[3].key = null; return importer('002', exportData); }).then(function () { (1).should.eql(0, 'Data import should not resolve promise.'); }, function (error) { - error[0].message.should.eql('Value in [settings.key] cannot be blank.'); error[0].type.should.eql('ValidationError'); @@ -516,7 +503,6 @@ describe('Import', function () { done(); }); - }).catch(done); }); }); @@ -691,17 +677,14 @@ describe('Import', function () { done(); }).catch(done); }); - }); }); - // Tests in here do an import-per-describe, and then have several tests to check various bits of data describe('Import (new test structure)', function () { before(testUtils.teardown); describe('003', function () { - after(testUtils.teardown); should.exist(Importer003); @@ -785,7 +768,7 @@ describe('Import (new test structure)', function () { user2, user3, users, - roles_users; + rolesUsers; // General data checks should.exist(importedData); @@ -793,7 +776,7 @@ describe('Import (new test structure)', function () { // Test the users and roles users = importedData[0]; - roles_users = importedData[1]; + rolesUsers = importedData[1]; // we imported 3 users // the original user should be untouched @@ -830,9 +813,9 @@ describe('Import (new test structure)', function () { user3.updated_by.should.equal(user1.id); user3.updated_at.should.not.equal(exportData.data.users[2].updated_at); - roles_users.length.should.equal(3, 'There should be 3 role relations'); + rolesUsers.length.should.equal(3, 'There should be 3 role relations'); - _.each(roles_users, function (roleUser) { + _.each(rolesUsers, function (roleUser) { if (roleUser.user_id === user1.id) { roleUser.role_id.should.equal(4, 'Original user should be an owner'); } @@ -898,7 +881,7 @@ describe('Import (new test structure)', function () { return tag.slug === exportData.data.tags[2].slug; }); - //Check the authors are correct + // Check the authors are correct post1.author_id.should.equal(user2.id); post2.author_id.should.equal(user3.id); post3.author_id.should.equal(user1.id); @@ -934,231 +917,231 @@ describe('Import (new test structure)', function () { }); describe('imports multi user data with no owner onto blank ghost install', function () { - var exportData; + var exportData; - before(function doImport(done) { - knex = config.database.knex; + before(function doImport(done) { + knex = config.database.knex; - testUtils.initFixtures('roles', 'owner', 'settings').then(function () { - return testUtils.fixtures.loadExportFixture('export-003-mu-noOwner'); - }).then(function (exported) { - exportData = exported; - return importer('003', exportData); - }).then(function () { - done(); - }).catch(done); + testUtils.initFixtures('roles', 'owner', 'settings').then(function () { + return testUtils.fixtures.loadExportFixture('export-003-mu-noOwner'); + }).then(function (exported) { + exportData = exported; + return importer('003', exportData); + }).then(function () { + done(); + }).catch(done); + }); + after(testUtils.teardown); + + it('gets the right data', function (done) { + var fetchImported = Promise.join( + knex('posts').select(), + knex('settings').select(), + knex('tags').select() + ); + + fetchImported.then(function (importedData) { + var posts, + settings, + tags, + post1, + post2, + post3; + + // General data checks + should.exist(importedData); + importedData.length.should.equal(3, 'Did not get data successfully'); + + // Test posts, settings and tags + posts = importedData[0]; + settings = importedData[1]; + tags = importedData[2]; + + post1 = _.find(posts, function (post) { + return post.slug === exportData.data.posts[0].slug; }); - after(testUtils.teardown); - - it('gets the right data', function (done) { - var fetchImported = Promise.join( - knex('posts').select(), - knex('settings').select(), - knex('tags').select() - ); - - fetchImported.then(function (importedData) { - var posts, - settings, - tags, - post1, - post2, - post3; - - // General data checks - should.exist(importedData); - importedData.length.should.equal(3, 'Did not get data successfully'); - - // Test posts, settings and tags - posts = importedData[0]; - settings = importedData[1]; - tags = importedData[2]; - - post1 = _.find(posts, function (post) { - return post.slug === exportData.data.posts[0].slug; - }); - post2 = _.find(posts, function (post) { - return post.slug === exportData.data.posts[1].slug; - }); - post3 = _.find(posts, function (post) { - return post.slug === exportData.data.posts[2].slug; - }); - - // test posts - posts.length.should.equal(3, 'Wrong number of posts'); - post1.title.should.equal(exportData.data.posts[0].title); - post2.title.should.equal(exportData.data.posts[1].title); - post3.title.should.equal(exportData.data.posts[2].title); - - // test tags - tags.length.should.equal(3, 'should be 3 tags'); - - // test settings - settings.length.should.be.above(0, 'Wrong number of settings'); - _.findWhere(settings, {key: 'databaseVersion'}).value.should.equal('003', 'Wrong database version'); - - done(); - }).catch(done); + post2 = _.find(posts, function (post) { + return post.slug === exportData.data.posts[1].slug; + }); + post3 = _.find(posts, function (post) { + return post.slug === exportData.data.posts[2].slug; }); - it('imports users with correct roles and status', function (done) { - var fetchImported = Promise.join( - knex('users').select(), - knex('roles_users').select() - ); + // test posts + posts.length.should.equal(3, 'Wrong number of posts'); + post1.title.should.equal(exportData.data.posts[0].title); + post2.title.should.equal(exportData.data.posts[1].title); + post3.title.should.equal(exportData.data.posts[2].title); - fetchImported.then(function (importedData) { - var user1, - user2, - user3, - users, - roles_users; + // test tags + tags.length.should.equal(3, 'should be 3 tags'); - // General data checks - should.exist(importedData); - importedData.length.should.equal(2, 'Did not get data successfully'); + // test settings + settings.length.should.be.above(0, 'Wrong number of settings'); + _.findWhere(settings, {key: 'databaseVersion'}).value.should.equal('003', 'Wrong database version'); - // Test the users and roles - users = importedData[0]; - roles_users = importedData[1]; + done(); + }).catch(done); + }); - // we imported 3 users - // the original user should be untouched - // the two news users should have been created - users.length.should.equal(3, 'There should only be three users'); + it('imports users with correct roles and status', function (done) { + var fetchImported = Promise.join( + knex('users').select(), + knex('roles_users').select() + ); - // the owner user is first - user1 = users[0]; - // the other two users should have the imported data, but they get inserted in different orders - user2 = _.find(users, function (user) { - return user.name === exportData.data.users[0].name; - }); - user3 = _.find(users, function (user) { - return user.name === exportData.data.users[1].name; - }); + fetchImported.then(function (importedData) { + var user1, + user2, + user3, + users, + rolesUsers; - user1.email.should.equal(testUtils.DataGenerator.Content.users[0].email); - user1.password.should.equal(testUtils.DataGenerator.Content.users[0].password); - user1.status.should.equal('active'); - user2.email.should.equal(exportData.data.users[0].email); - user3.email.should.equal(exportData.data.users[1].email); + // General data checks + should.exist(importedData); + importedData.length.should.equal(2, 'Did not get data successfully'); - // Newly created users should have a status of locked - user2.status.should.equal('locked'); - user3.status.should.equal('locked'); + // Test the users and roles + users = importedData[0]; + rolesUsers = importedData[1]; - // Newly created users should have created_at/_by and updated_at/_by set to when they were imported - user2.created_by.should.equal(user1.id); - user2.created_at.should.not.equal(exportData.data.users[0].created_at); - user2.updated_by.should.equal(user1.id); - user2.updated_at.should.not.equal(exportData.data.users[0].updated_at); - user3.created_by.should.equal(user1.id); - user3.created_at.should.not.equal(exportData.data.users[1].created_at); - user3.updated_by.should.equal(user1.id); - user3.updated_at.should.not.equal(exportData.data.users[1].updated_at); + // we imported 3 users + // the original user should be untouched + // the two news users should have been created + users.length.should.equal(3, 'There should only be three users'); - roles_users.length.should.equal(3, 'There should be 3 role relations'); - - _.each(roles_users, function (roleUser) { - if (roleUser.user_id === user1.id) { - roleUser.role_id.should.equal(4, 'Original user should be an owner'); - } - if (roleUser.user_id === user2.id) { - roleUser.role_id.should.equal(1, 'Josephine should be an admin'); - } - if (roleUser.user_id === user3.id) { - roleUser.role_id.should.equal(3, 'Smith should be an author by default'); - } - }); - - done(); - }).catch(done); + // the owner user is first + user1 = users[0]; + // the other two users should have the imported data, but they get inserted in different orders + user2 = _.find(users, function (user) { + return user.name === exportData.data.users[0].name; + }); + user3 = _.find(users, function (user) { + return user.name === exportData.data.users[1].name; }); - it('imports posts & tags with correct authors, owners etc', function (done) { - var fetchImported = Promise.join( - knex('users').select(), - knex('posts').select(), - knex('tags').select() - ); + user1.email.should.equal(testUtils.DataGenerator.Content.users[0].email); + user1.password.should.equal(testUtils.DataGenerator.Content.users[0].password); + user1.status.should.equal('active'); + user2.email.should.equal(exportData.data.users[0].email); + user3.email.should.equal(exportData.data.users[1].email); - fetchImported.then(function (importedData) { - var users, user1, user2, user3, - posts, post1, post2, post3, - tags, tag1, tag2, tag3; + // Newly created users should have a status of locked + user2.status.should.equal('locked'); + user3.status.should.equal('locked'); - // General data checks - should.exist(importedData); - importedData.length.should.equal(3, 'Did not get data successfully'); + // Newly created users should have created_at/_by and updated_at/_by set to when they were imported + user2.created_by.should.equal(user1.id); + user2.created_at.should.not.equal(exportData.data.users[0].created_at); + user2.updated_by.should.equal(user1.id); + user2.updated_at.should.not.equal(exportData.data.users[0].updated_at); + user3.created_by.should.equal(user1.id); + user3.created_at.should.not.equal(exportData.data.users[1].created_at); + user3.updated_by.should.equal(user1.id); + user3.updated_at.should.not.equal(exportData.data.users[1].updated_at); - // Test the users and roles - users = importedData[0]; - posts = importedData[1]; - tags = importedData[2]; + rolesUsers.length.should.equal(3, 'There should be 3 role relations'); - // Grab the users - // the owner user is first - user1 = users[0]; - // the other two users should have the imported data, but they get inserted in different orders - user2 = _.find(users, function (user) { - return user.name === exportData.data.users[0].name; - }); - user3 = _.find(users, function (user) { - return user.name === exportData.data.users[1].name; - }); - post1 = _.find(posts, function (post) { - return post.slug === exportData.data.posts[0].slug; - }); - post2 = _.find(posts, function (post) { - return post.slug === exportData.data.posts[1].slug; - }); - post3 = _.find(posts, function (post) { - return post.slug === exportData.data.posts[2].slug; - }); - tag1 = _.find(tags, function (tag) { - return tag.slug === exportData.data.tags[0].slug; - }); - tag2 = _.find(tags, function (tag) { - return tag.slug === exportData.data.tags[1].slug; - }); - tag3 = _.find(tags, function (tag) { - return tag.slug === exportData.data.tags[2].slug; - }); - - //Check the authors are correct - post1.author_id.should.equal(user2.id); - post2.author_id.should.equal(user3.id); - post3.author_id.should.equal(user1.id); - - // Created by should be what was in the import file - post1.created_by.should.equal(user1.id); - post2.created_by.should.equal(user3.id); - post3.created_by.should.equal(user1.id); - - // Updated by gets set to the current user - post1.updated_by.should.equal(user1.id); - post2.updated_by.should.equal(user1.id); - post3.updated_by.should.equal(user1.id); - - // Published by should be what was in the import file - post1.published_by.should.equal(user2.id); - post2.published_by.should.equal(user3.id); - post3.published_by.should.equal(user1.id); - - // Created by should be what was in the import file - tag1.created_by.should.equal(user1.id); - tag2.created_by.should.equal(user2.id); - tag3.created_by.should.equal(user3.id); - - // Updated by gets set to the current user - tag1.updated_by.should.equal(user1.id); - tag2.updated_by.should.equal(user1.id); - tag3.updated_by.should.equal(user1.id); - - done(); - }).catch(done); + _.each(rolesUsers, function (roleUser) { + if (roleUser.user_id === user1.id) { + roleUser.role_id.should.equal(4, 'Original user should be an owner'); + } + if (roleUser.user_id === user2.id) { + roleUser.role_id.should.equal(1, 'Josephine should be an admin'); + } + if (roleUser.user_id === user3.id) { + roleUser.role_id.should.equal(3, 'Smith should be an author by default'); + } }); - }); + + done(); + }).catch(done); + }); + + it('imports posts & tags with correct authors, owners etc', function (done) { + var fetchImported = Promise.join( + knex('users').select(), + knex('posts').select(), + knex('tags').select() + ); + + fetchImported.then(function (importedData) { + var users, user1, user2, user3, + posts, post1, post2, post3, + tags, tag1, tag2, tag3; + + // General data checks + should.exist(importedData); + importedData.length.should.equal(3, 'Did not get data successfully'); + + // Test the users and roles + users = importedData[0]; + posts = importedData[1]; + tags = importedData[2]; + + // Grab the users + // the owner user is first + user1 = users[0]; + // the other two users should have the imported data, but they get inserted in different orders + user2 = _.find(users, function (user) { + return user.name === exportData.data.users[0].name; + }); + user3 = _.find(users, function (user) { + return user.name === exportData.data.users[1].name; + }); + post1 = _.find(posts, function (post) { + return post.slug === exportData.data.posts[0].slug; + }); + post2 = _.find(posts, function (post) { + return post.slug === exportData.data.posts[1].slug; + }); + post3 = _.find(posts, function (post) { + return post.slug === exportData.data.posts[2].slug; + }); + tag1 = _.find(tags, function (tag) { + return tag.slug === exportData.data.tags[0].slug; + }); + tag2 = _.find(tags, function (tag) { + return tag.slug === exportData.data.tags[1].slug; + }); + tag3 = _.find(tags, function (tag) { + return tag.slug === exportData.data.tags[2].slug; + }); + + // Check the authors are correct + post1.author_id.should.equal(user2.id); + post2.author_id.should.equal(user3.id); + post3.author_id.should.equal(user1.id); + + // Created by should be what was in the import file + post1.created_by.should.equal(user1.id); + post2.created_by.should.equal(user3.id); + post3.created_by.should.equal(user1.id); + + // Updated by gets set to the current user + post1.updated_by.should.equal(user1.id); + post2.updated_by.should.equal(user1.id); + post3.updated_by.should.equal(user1.id); + + // Published by should be what was in the import file + post1.published_by.should.equal(user2.id); + post2.published_by.should.equal(user3.id); + post3.published_by.should.equal(user1.id); + + // Created by should be what was in the import file + tag1.created_by.should.equal(user1.id); + tag2.created_by.should.equal(user2.id); + tag3.created_by.should.equal(user3.id); + + // Updated by gets set to the current user + tag1.updated_by.should.equal(user1.id); + tag2.updated_by.should.equal(user1.id); + tag3.updated_by.should.equal(user1.id); + + done(); + }).catch(done); + }); + }); describe('imports multi user data onto existing data', function () { var exportData; @@ -1251,7 +1234,7 @@ describe('Import (new test structure)', function () { newUser, existingUser, users, - roles_users; + rolesUsers; // General data checks should.exist(importedData); @@ -1259,7 +1242,7 @@ describe('Import (new test structure)', function () { // Test the users and roles users = importedData[0]; - roles_users = importedData[1]; + rolesUsers = importedData[1]; // we imported 3 users, there were already 4 users, only one of the imported users is new users.length.should.equal(5, 'There should only be three users'); @@ -1291,9 +1274,9 @@ describe('Import (new test structure)', function () { newUser.updated_by.should.equal(ownerUser.id); newUser.updated_at.should.not.equal(exportData.data.users[1].updated_at); - roles_users.length.should.equal(5, 'There should be 5 role relations'); + rolesUsers.length.should.equal(5, 'There should be 5 role relations'); - _.each(roles_users, function (roleUser) { + _.each(rolesUsers, function (roleUser) { if (roleUser.user_id === ownerUser.id) { roleUser.role_id.should.equal(4, 'Original user should be an owner'); } @@ -1359,7 +1342,7 @@ describe('Import (new test structure)', function () { return tag.slug === exportData.data.tags[2].slug; }); - //Check the authors are correct + // Check the authors are correct post1.author_id.should.equal(newUser.id); post2.author_id.should.equal(existingUser.id); post3.author_id.should.equal(ownerUser.id); diff --git a/core/test/integration/model/model_app_fields_spec.js b/core/test/integration/model/model_app_fields_spec.js index 9a3dd9a08c..dc4eabbd78 100644 --- a/core/test/integration/model/model_app_fields_spec.js +++ b/core/test/integration/model/model_app_fields_spec.js @@ -19,7 +19,6 @@ describe('App Fields Model', function () { it('can findAll', function (done) { AppFieldsModel.findAll().then(function (results) { - should.exist(results); results.length.should.be.above(0); diff --git a/core/test/integration/model/model_app_settings_spec.js b/core/test/integration/model/model_app_settings_spec.js index 9931baca13..4829a50a90 100644 --- a/core/test/integration/model/model_app_settings_spec.js +++ b/core/test/integration/model/model_app_settings_spec.js @@ -19,7 +19,6 @@ describe('App Setting Model', function () { it('can findAll', function (done) { AppSettingModel.findAll().then(function (results) { - should.exist(results); results.length.should.be.above(0); diff --git a/core/test/integration/model/model_apps_spec.js b/core/test/integration/model/model_apps_spec.js index 4a5d8de88e..b94ec9fe50 100644 --- a/core/test/integration/model/model_apps_spec.js +++ b/core/test/integration/model/model_apps_spec.js @@ -21,7 +21,6 @@ describe('App Model', function () { it('can findAll', function (done) { AppModel.findAll().then(function (results) { - should.exist(results); results.length.should.be.above(0); diff --git a/core/test/integration/model/model_permissions_spec.js b/core/test/integration/model/model_permissions_spec.js index eca2ac660b..a8683fac4c 100644 --- a/core/test/integration/model/model_permissions_spec.js +++ b/core/test/integration/model/model_permissions_spec.js @@ -86,7 +86,6 @@ describe('Permission Model', function () { }).catch(done); }); - // it('can add user to role', function (done) { // var existingUserRoles; // diff --git a/core/test/integration/model/model_posts_spec.js b/core/test/integration/model/model_posts_spec.js index 89a159eaaa..efef4b00c9 100644 --- a/core/test/integration/model/model_posts_spec.js +++ b/core/test/integration/model/model_posts_spec.js @@ -14,7 +14,6 @@ describe('Post Model', function () { // Keep the DB clean describe('Single author posts', function () { - before(testUtils.teardown); afterEach(testUtils.teardown); beforeEach(testUtils.setup('owner', 'posts', 'apps')); @@ -24,7 +23,7 @@ describe('Post Model', function () { }); function extractFirstPost(posts) { - return _.filter(posts, { id: 1 })[0]; + return _.filter(posts, {id: 1})[0]; } function checkFirstPostData(firstPost) { @@ -201,7 +200,6 @@ describe('Post Model', function () { done(); }).catch(done); - }); it('can add, with previous published_at date', function (done) { @@ -213,12 +211,10 @@ describe('Post Model', function () { title: 'published_at test', markdown: 'This is some content' }, context).then(function (newPost) { - should.exist(newPost); new Date(newPost.get('published_at')).getTime().should.equal(previousPublishedAtDate.getTime()); done(); - }).catch(done); }); @@ -231,12 +227,12 @@ describe('Post Model', function () { }; PostModel.add(newPost, context).then(function (createdPost) { - return new PostModel({ id: createdPost.id }).fetch(); + return new PostModel({id: createdPost.id}).fetch(); }).then(function (createdPost) { should.exist(createdPost); createdPost.get('title').should.equal(untrimmedCreateTitle.trim()); - return createdPost.save({ title: untrimmedUpdateTitle }, context); + return createdPost.save({title: untrimmedUpdateTitle}, context); }).then(function (updatedPost) { updatedPost.get('title').should.equal(untrimmedUpdateTitle.trim()); @@ -282,7 +278,6 @@ describe('Post Model', function () { }; PostModel.add(newPost, context).then(function (createdPost) { - createdPost.get('slug').should.equal('apprehensive-titles-have-too-many-spaces-and-m-dashes-and-also-n-dashes'); done(); @@ -340,7 +335,6 @@ describe('Post Model', function () { slug: firstPost.slug }, context); }).then(function (updatedSecondPost) { - // Should have updated from original updatedSecondPost.get('slug').should.not.equal(secondPost.slug); // Should not have a conflicted slug from the first @@ -351,7 +345,6 @@ describe('Post Model', function () { status: 'all' }); }).then(function (foundPost) { - // Should have updated from original foundPost.get('slug').should.not.equal(secondPost.slug); // Should not have a conflicted slug from the first @@ -393,7 +386,6 @@ describe('Post Model', function () { it('can findPage, with various options', function (done) { testUtils.fixtures.insertMorePosts().then(function () { - return testUtils.fixtures.insertMorePostsTags(); }).then(function () { return PostModel.findPage({page: 2}); @@ -443,7 +435,6 @@ describe('Post Model', function () { it('can findPage for tag, with various options', function (done) { testUtils.fixtures.insertMorePosts().then(function () { - return testUtils.fixtures.insertMorePostsTags(); }).then(function () { // Test tag filter @@ -488,7 +479,7 @@ describe('Post Model', function () { }); it('can NOT findPage for a page that overflows the datatype', function (done) { - PostModel.findPage({ page: 5700000000055345439587894375457849375284932759842375894372589243758947325894375894275894275894725897432859724309 }) + PostModel.findPage({page: 5700000000055345439587894375457849375284932759842375894372589243758947325894375894275894275894725897432859724309}) .then(function (paginationResult) { should.exist(paginationResult.meta); @@ -499,7 +490,6 @@ describe('Post Model', function () { }); }); - describe('Multiauthor Posts', function () { before(testUtils.teardown); afterEach(testUtils.teardown); @@ -510,7 +500,6 @@ describe('Post Model', function () { }); it('can destroy multiple posts by author', function (done) { - // We're going to delete all posts by user 1 var authorData = {id: 1}; diff --git a/core/test/integration/model/model_roles_spec.js b/core/test/integration/model/model_roles_spec.js index 4b54f12027..58dd9f73c9 100644 --- a/core/test/integration/model/model_roles_spec.js +++ b/core/test/integration/model/model_roles_spec.js @@ -79,7 +79,7 @@ describe('Role Model', function () { return RoleModel.destroy(firstRole); }).then(function (response) { response.toJSON().should.be.empty; - return RoleModel.findOne(firstRole); + return RoleModel.findOne(firstRole); }).then(function (newResults) { should.equal(newResults, null); diff --git a/core/test/integration/model/model_settings_spec.js b/core/test/integration/model/model_settings_spec.js index 917630160c..3932969f35 100644 --- a/core/test/integration/model/model_settings_spec.js +++ b/core/test/integration/model/model_settings_spec.js @@ -19,10 +19,8 @@ describe('Settings Model', function () { }); describe('API', function () { - it('can findAll', function (done) { SettingsModel.findAll().then(function (results) { - should.exist(results); results.length.should.be.above(0); @@ -35,7 +33,6 @@ describe('Settings Model', function () { var firstSetting; SettingsModel.findAll().then(function (results) { - should.exist(results); results.length.should.be.above(0); @@ -43,31 +40,24 @@ describe('Settings Model', function () { firstSetting = results.models[0]; return SettingsModel.findOne(firstSetting.attributes.key); - }).then(function (found) { - should.exist(found); found.get('value').should.equal(firstSetting.attributes.value); found.get('created_at').should.be.an.instanceof(Date); done(); - }).catch(done); }); it('can edit single', function (done) { - SettingsModel.findAll().then(function (results) { - should.exist(results); results.length.should.be.above(0); return SettingsModel.edit({key: 'description', value: 'new value'}, context); - }).then(function (edited) { - should.exist(edited); edited.length.should.equal(1); @@ -78,7 +68,6 @@ describe('Settings Model', function () { edited.attributes.value.should.equal('new value'); done(); - }).catch(done); }); @@ -88,7 +77,6 @@ describe('Settings Model', function () { editedModel; SettingsModel.findAll().then(function (results) { - should.exist(results); results.length.should.be.above(0); @@ -97,9 +85,7 @@ describe('Settings Model', function () { model2 = {key: 'title', value: 'new title'}; return SettingsModel.edit([model1, model2], context); - }).then(function (edited) { - should.exist(edited); edited.length.should.equal(2); @@ -115,7 +101,6 @@ describe('Settings Model', function () { editedModel.attributes.value.should.equal(model2.value); done(); - }).catch(done); }); @@ -126,7 +111,6 @@ describe('Settings Model', function () { }; SettingsModel.add(newSetting, context).then(function (createdSetting) { - should.exist(createdSetting); createdSetting.has('uuid').should.equal(true); createdSetting.attributes.key.should.equal(newSetting.key, 'key is correct'); @@ -159,7 +143,6 @@ describe('Settings Model', function () { }); describe('populating defaults from settings.json', function () { - beforeEach(function (done) { config.database.knex('settings').truncate().then(function () { done(); diff --git a/core/test/integration/model/model_tags_spec.js b/core/test/integration/model/model_tags_spec.js index 494f1d881f..08f36492c4 100644 --- a/core/test/integration/model/model_tags_spec.js +++ b/core/test/integration/model/model_tags_spec.js @@ -28,7 +28,7 @@ describe('Tag Model', function () { it('uses Date objects for dateTime fields', function (done) { TagModel.add(testUtils.DataGenerator.forModel.tags[0], context).then(function (tag) { - return TagModel.findOne({ id: tag.id }); + return TagModel.findOne({id: tag.id}); }).then(function (tag) { should.exist(tag); tag.get('created_at').should.be.an.instanceof(Date); @@ -38,7 +38,6 @@ describe('Tag Model', function () { }); describe('a Post', function () { - it('can add a tag', function (done) { var newPost = testUtils.DataGenerator.forModel.posts[0], newTag = testUtils.DataGenerator.forModel.tags[0], @@ -54,12 +53,11 @@ describe('Tag Model', function () { createdPostID = createdPost.id; return createdPost.tags().attach(createdTag); }).then(function () { - return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: createdPostID, status: 'all'}, {withRelated: ['tags']}); }).then(function (postWithTag) { postWithTag.related('tags').length.should.equal(1); done(); }).catch(done); - }); it('can remove a tag', function (done) { @@ -82,11 +80,11 @@ describe('Tag Model', function () { createdTagID = createdTag.id; return createdPost.tags().attach(createdTag); }).then(function () { - return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: createdPostID, status: 'all'}, {withRelated: ['tags']}); }).then(function (postWithTag) { return postWithTag.tags().detach(createdTagID); }).then(function () { - return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: createdPostID, status: 'all'}, {withRelated: ['tags']}); }).then(function (postWithoutTag) { postWithoutTag.related('tags').length.should.equal(0); done(); @@ -120,7 +118,7 @@ describe('Tag Model', function () { return postModel; }); }).then(function (postModel) { - return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, {withRelated: ['tags']}); }); } @@ -136,7 +134,7 @@ describe('Tag Model', function () { postModel = postModel.toJSON(); postModel.tags = existingTagData; - return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']})); + return PostModel.edit(postModel, _.extend(context, {id: postModel.id, withRelated: ['tags']})); }).then(function (postModel) { var tagNames = postModel.related('tags').models.map(function (t) { return t.attributes.name; }); tagNames.sort().should.eql(seededTagNames); @@ -162,9 +160,9 @@ describe('Tag Model', function () { postModel = postModel.toJSON(); postModel.tags = tagData; - return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']})); + return PostModel.edit(postModel, _.extend(context, {id: postModel.id, withRelated: ['tags']})); }).then(function (postModel) { - return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, {withRelated: ['tags']}); }).then(function (reloadedPost) { var tagNames = reloadedPost.related('tags').models.map(function (t) { return t.attributes.name; }); tagNames.sort().should.eql(['tag1', 'tag3']); @@ -189,9 +187,9 @@ describe('Tag Model', function () { postModel = postModel.toJSON(); postModel.tags = tagData; - return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']})); + return PostModel.edit(postModel, _.extend(context, {id: postModel.id, withRelated: ['tags']})); }).then(function () { - return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, {withRelated: ['tags']}); }).then(function (reloadedPost) { var tagModels = reloadedPost.related('tags').models, tagNames = tagModels.map(function (t) { return t.attributes.name; }), @@ -218,9 +216,9 @@ describe('Tag Model', function () { postModel = postModel.toJSON(); postModel.tags = tagData; - return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']})); + return PostModel.edit(postModel, _.extend(context, {id: postModel.id, withRelated: ['tags']})); }).then(function (postModel) { - return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, {withRelated: ['tags']}); }).then(function (reloadedPost) { var tagNames = reloadedPost.related('tags').models.map(function (t) { return t.attributes.name; }); tagNames.sort().should.eql(['tag1', 'tag2', 'tag3']); @@ -243,9 +241,9 @@ describe('Tag Model', function () { postModel = postModel.toJSON(); postModel.tags = tagData; - return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']})); + return PostModel.edit(postModel, _.extend(context, {id: postModel.id, withRelated: ['tags']})); }).then(function (postModel) { - return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, {withRelated: ['tags']}); }).then(function (reloadedPost) { var tagNames = reloadedPost.related('tags').models.map(function (t) { return t.attributes.name; }); tagNames.sort().should.eql(['tag1', 'tag2', 'tag3']); @@ -274,9 +272,9 @@ describe('Tag Model', function () { postModel = postModel.toJSON(); postModel.tags = tagData; - return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']})); + return PostModel.edit(postModel, _.extend(context, {id: postModel.id, withRelated: ['tags']})); }).then(function () { - return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, {withRelated: ['tags']}); }).then(function (reloadedPost) { var tagModels = reloadedPost.related('tags').models, tagNames = tagModels.map(function (t) { return t.attributes.name; }), @@ -313,9 +311,9 @@ describe('Tag Model', function () { postModel = postModel.toJSON(); postModel.tags = tagData; - return PostModel.edit(postModel, _.extend(context, { id: postModel.id, withRelated: ['tags']})); + return PostModel.edit(postModel, _.extend(context, {id: postModel.id, withRelated: ['tags']})); }).then(function () { - return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, {withRelated: ['tags']}); }).then(function (reloadedPost) { var tagModels = reloadedPost.related('tags').models, tagNames = tagModels.map(function (t) { return t.get('name'); }), @@ -335,7 +333,7 @@ describe('Tag Model', function () { var newPost = _.extend(testUtils.DataGenerator.forModel.posts[0], {tags: [{name: 'test_tag_1'}]}); PostModel.add(newPost, context).then(function (createdPost) { - return PostModel.findOne({id: createdPost.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: createdPost.id, status: 'all'}, {withRelated: ['tags']}); }).then(function (postWithTag) { postWithTag.related('tags').length.should.equal(1); done(); diff --git a/core/test/integration/model/model_users_spec.js b/core/test/integration/model/model_users_spec.js index 5438181649..7191c7057b 100644 --- a/core/test/integration/model/model_users_spec.js +++ b/core/test/integration/model/model_users_spec.js @@ -13,7 +13,6 @@ var testUtils = require('../../utils'), context = testUtils.context.admin, sandbox = sinon.sandbox.create(); - describe('User Model', function run() { // Keep the DB clean before(testUtils.teardown); @@ -143,22 +142,22 @@ describe('User Model', function run() { it('converts fetched dateTime fields to Date objects', function (done) { var userData = testUtils.DataGenerator.forModel.users[0]; - UserModel.check({ email: userData.email, password: userData.password }).then(function (user) { - return UserModel.findOne({ id: user.id }); + UserModel.check({email: userData.email, password: userData.password}).then(function (user) { + return UserModel.findOne({id: user.id}); }).then(function (user) { - var last_login, - created_at, - updated_at; + var lastLogin, + createdAt, + updatedAt; should.exist(user); - last_login = user.get('last_login'); - created_at = user.get('created_at'); - updated_at = user.get('updated_at'); + lastLogin = user.get('last_login'); + createdAt = user.get('created_at'); + updatedAt = user.get('updated_at'); - last_login.should.be.an.instanceof(Date); - created_at.should.be.an.instanceof(Date); - updated_at.should.be.an.instanceof(Date); + lastLogin.should.be.an.instanceof(Date); + createdAt.should.be.an.instanceof(Date); + updatedAt.should.be.an.instanceof(Date); done(); }).catch(done); @@ -170,7 +169,6 @@ describe('User Model', function run() { results.length.should.equal(4); done(); - }).catch(done); }); @@ -218,12 +216,12 @@ describe('User Model', function run() { }); it('can NOT findPage for a page that overflows the datatype', function (done) { - UserModel.findPage({ page: 5700000000055345439587894375457849375284932759842375894372589243758947325894375894275894275894725897432859724309 }) + UserModel.findPage({page: 5700000000055345439587894375457849375284932759842375894372589243758947325894375894275894275894725897432859724309}) .then(function (paginationResult) { should.exist(paginationResult.meta); paginationResult.meta.pagination.page.should.be.a.Number; - + done(); }).catch(done); }); @@ -242,9 +240,7 @@ describe('User Model', function run() { found.attributes.name.should.equal(firstUser.attributes.name); done(); - }).catch(done); - }); it('can edit', function (done) { @@ -263,7 +259,6 @@ describe('User Model', function run() { edited.attributes.website.should.equal('http://some.newurl.com'); done(); - }).catch(done); }); @@ -277,7 +272,7 @@ describe('User Model', function run() { RoleModel.findOne().then(function (role) { userData.roles = [role.toJSON()]; - return UserModel.add(userData, _.extend({}, context)); + return UserModel.add(userData, _.extend({}, context)); }).then(function (createdUser) { should.exist(createdUser); createdUser.has('uuid').should.equal(true); @@ -294,7 +289,6 @@ describe('User Model', function run() { // Test that we have the user we expect UserModel.findOne(firstUser).then(function (results) { - var user; should.exist(results); user = results.toJSON(); @@ -324,9 +318,7 @@ describe('User Model', function run() { dbHash = uuid.v4(); UserModel.findAll().then(function (results) { - return UserModel.generateResetToken(results.models[0].attributes.email, expires, dbHash); - }).then(function (token) { should.exist(token); @@ -342,17 +334,11 @@ describe('User Model', function run() { dbHash = uuid.v4(); UserModel.findAll().then(function (results) { - return UserModel.generateResetToken(results.models[0].attributes.email, expires, dbHash); - }).then(function (token) { - return UserModel.validateToken(token, dbHash); - }).then(function () { - done(); - }).catch(done); }); @@ -363,18 +349,14 @@ describe('User Model', function run() { dbHash = uuid.v4(); UserModel.findAll().then(function (results) { - var firstUser = results.models[0], origPassword = firstUser.attributes.password; should.exist(origPassword); return UserModel.generateResetToken(firstUser.attributes.email, expires, dbHash); - }).then(function (token) { - return UserModel.resetPassword(token, 'newpassword', 'newpassword', dbHash); - }).then(function (resetUser) { var resetPassword = resetUser.get('password'); @@ -393,18 +375,15 @@ describe('User Model', function run() { dbHash = uuid.v4(); UserModel.findAll().then(function (results) { - // Store email for later email = results.models[0].attributes.email; return UserModel.generateResetToken(email, expires, dbHash); - }).then(function (token) { return UserModel.validateToken(token, dbHash); }).then(function () { throw new Error('Allowed expired token'); }).catch(function (err) { - should.exist(err); err.message.should.equal('Expired token'); @@ -419,11 +398,8 @@ describe('User Model', function run() { dbHash = uuid.v4(); UserModel.findAll().then(function (results) { - return UserModel.generateResetToken(results.models[0].attributes.email, expires, dbHash); - }).then(function (token) { - var tokenText = new Buffer(token, 'base64').toString('ascii'), parts = tokenText.split('|'), fakeExpires, @@ -435,11 +411,9 @@ describe('User Model', function run() { fakeToken = new Buffer(fakeToken).toString('base64'); return UserModel.validateToken(fakeToken, dbHash); - }).then(function () { throw new Error('allowed invalid token'); }).catch(function (err) { - should.exist(err); err.message.should.equal('Invalid token'); diff --git a/core/test/unit/apps_spec.js b/core/test/unit/apps_spec.js index f51901c0ed..b7e286d770 100644 --- a/core/test/unit/apps_spec.js +++ b/core/test/unit/apps_spec.js @@ -16,7 +16,6 @@ var path = require('path'), AppPermissions = require('../../server/apps/permissions'); describe('Apps', function () { - var sandbox, fakeApi; @@ -127,7 +126,7 @@ describe('Apps', function () { posts: ['browse', 'read', 'edit', 'add', 'delete'] } }), - fakePosts = [{ id: 0 }, { id: 1 }], + fakePosts = [{id: 0}, {id: 1}], filterStub = sandbox.spy(function (val) { return val; }); @@ -179,7 +178,7 @@ describe('Apps', function () { posts: ['browse', 'read', 'edit', 'add', 'delete'] } }), - fakePosts = [{ id: 0 }, { id: 1 }], + fakePosts = [{id: 0}, {id: 1}], filterStub = sandbox.stub().returns(fakePosts); appProxy.filters.deregister('prePostsRender', 5, filterStub); @@ -368,39 +367,38 @@ describe('Apps', function () { }); describe('Permissions', function () { - /*jshint quotmark:false*/ var noGhostPackageJson = { - "name": "myapp", - "version": "0.0.1", - "description": "My example app", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + name: 'myapp', + version: '0.0.1', + description: 'My example app', + main: 'index.js', + scripts: { + test: 'echo \'Error: no test specified\' && exit 1' }, - "author": "Ghost", - "license": "MIT", - "dependencies": { - "ghost-app": "0.0.1" + author: 'Ghost', + license: 'MIT', + dependencies: { + 'ghost-app': '0.0.1' } }, validGhostPackageJson = { - "name": "myapp", - "version": "0.0.1", - "description": "My example app", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + name: 'myapp', + version: '0.0.1', + description: 'My example app', + main: 'index.js', + scripts: { + test: 'echo \'Error: no test specified\' && exit 1' }, - "author": "Ghost", - "license": "MIT", - "dependencies": { - "ghost-app": "0.0.1" + author: 'Ghost', + license: 'MIT', + dependencies: { + 'ghost-app': '0.0.1' }, - "ghost": { - "permissions": { - "posts": ["browse", "read", "edit", "add", "delete"], - "users": ["browse", "read", "edit", "add", "delete"], - "settings": ["browse", "read", "edit", "add", "delete"] + ghost: { + permissions: { + posts: ['browse', 'read', 'edit', 'add', 'delete'], + users: ['browse', 'read', 'edit', 'add', 'delete'], + settings: ['browse', 'read', 'edit', 'add', 'delete'] } } }; @@ -417,10 +415,10 @@ describe('Apps', function () { _.keys(AppPermissions.DefaultPermissions).length.should.equal(1); }); it('uses default permissions if no package.json', function (done) { - var perms = new AppPermissions("test"); + var perms = new AppPermissions('test'); // No package.json in this directory - sandbox.stub(perms, "checkPackageContentsExists").returns(Promise.resolve(false)); + sandbox.stub(perms, 'checkPackageContentsExists').returns(Promise.resolve(false)); perms.read().then(function (readPerms) { should.exist(readPerms); @@ -431,13 +429,13 @@ describe('Apps', function () { }).catch(done); }); it('uses default permissions if no ghost object in package.json', function (done) { - var perms = new AppPermissions("test"), + var perms = new AppPermissions('test'), noGhostPackageJsonContents = JSON.stringify(noGhostPackageJson, null, 2); // package.json IS in this directory - sandbox.stub(perms, "checkPackageContentsExists").returns(Promise.resolve(true)); + sandbox.stub(perms, 'checkPackageContentsExists').returns(Promise.resolve(true)); // no ghost property on package - sandbox.stub(perms, "getPackageContents").returns(Promise.resolve(noGhostPackageJsonContents)); + sandbox.stub(perms, 'getPackageContents').returns(Promise.resolve(noGhostPackageJsonContents)); perms.read().then(function (readPerms) { should.exist(readPerms); @@ -448,12 +446,12 @@ describe('Apps', function () { }).catch(done); }); it('rejects when reading malformed package.json', function (done) { - var perms = new AppPermissions("test"); + var perms = new AppPermissions('test'); // package.json IS in this directory - sandbox.stub(perms, "checkPackageContentsExists").returns(Promise.resolve(true)); + sandbox.stub(perms, 'checkPackageContentsExists').returns(Promise.resolve(true)); // malformed JSON on package - sandbox.stub(perms, "getPackageContents").returns(Promise.reject(new Error('package.json file is malformed'))); + sandbox.stub(perms, 'getPackageContents').returns(Promise.reject(new Error('package.json file is malformed'))); perms.read().then(function (readPerms) { /*jshint unused:false*/ @@ -464,13 +462,13 @@ describe('Apps', function () { }); }); it('reads from package.json in root of app directory', function (done) { - var perms = new AppPermissions("test"), + var perms = new AppPermissions('test'), validGhostPackageJsonContents = validGhostPackageJson; // package.json IS in this directory - sandbox.stub(perms, "checkPackageContentsExists").returns(Promise.resolve(true)); + sandbox.stub(perms, 'checkPackageContentsExists').returns(Promise.resolve(true)); // valid ghost property on package - sandbox.stub(perms, "getPackageContents").returns(Promise.resolve(validGhostPackageJsonContents)); + sandbox.stub(perms, 'getPackageContents').returns(Promise.resolve(validGhostPackageJsonContents)); perms.read().then(function (readPerms) { should.exist(readPerms); diff --git a/core/test/unit/config_spec.js b/core/test/unit/config_spec.js index e6e8aa71ee..64389c7058 100644 --- a/core/test/unit/config_spec.js +++ b/core/test/unit/config_spec.js @@ -18,9 +18,7 @@ var should = require('should'), should.equal(true, true); describe('Config', function () { - describe('Theme', function () { - beforeEach(function () { config.set({ url: 'http://my-ghost-blog.com', @@ -57,7 +55,6 @@ describe('Config', function () { }); describe('Index', function () { - afterEach(function () { // Make a copy of the default config file // so we can restore it after every test. @@ -141,7 +138,6 @@ describe('Config', function () { }); describe('urlFor', function () { - before(function () { config.set(_.merge({}, defaultConfig)); }); @@ -238,7 +234,6 @@ describe('Config', function () { config.urlFor(testContext, testData).should.equal('/blog/tag/kitchen-sink/'); config.urlFor(testContext, testData, true).should.equal('http://my-ghost-blog.com/blog/tag/kitchen-sink/'); }); - }); describe('urlForPost', function () { @@ -254,9 +249,9 @@ describe('Config', function () { }); it('should output correct url for post', function (done) { - var settings = {'read': function read() {}}, + var settings = {read: function read() {}}, settingsStub = sandbox.stub(settings, 'read', function () { - return Promise.resolve({ settings: [{value: '/:slug/'}] }); + return Promise.resolve({settings: [{value: '/:slug/'}]}); }), /*jshint unused:false*/ testData = testUtils.DataGenerator.Content.posts[2], @@ -275,7 +270,6 @@ describe('Config', function () { return config.set({url: 'http://my-ghost-blog.com/blog'}); }).then(function () { - // next test return config.urlForPost(settings, testData); }).then(function (url) { @@ -288,13 +282,12 @@ describe('Config', function () { done(); }).catch(done); - }); it('should output correct url for post with date permalink', function (done) { - var settings = {'read': function read() {}}, + var settings = {read: function read() {}}, settingsStub = sandbox.stub(settings, 'read', function () { - return Promise.resolve({ settings: [{value: '/:year/:month/:day/:slug/'}] }); + return Promise.resolve({settings: [{value: '/:year/:month/:day/:slug/'}]}); }), /*jshint unused:false*/ testData = testUtils.DataGenerator.Content.posts[2], @@ -317,7 +310,6 @@ describe('Config', function () { return config.set({url: 'http://my-ghost-blog.com/blog'}); }).then(function () { - // next test return config.urlForPost(settings, testData); }).then(function (url) { @@ -333,9 +325,9 @@ describe('Config', function () { }); it('should output correct url for page with date permalink', function (done) { - var settings = {'read': function read() {}}, + var settings = {read: function read() {}}, settingsStub = sandbox.stub(settings, 'read', function () { - return Promise.resolve({ settings: [{value: '/:year/:month/:day/:slug/'}] }); + return Promise.resolve({settings: [{value: '/:year/:month/:day/:slug/'}]}); }), /*jshint unused:false*/ testData = testUtils.DataGenerator.Content.posts[5], @@ -354,7 +346,6 @@ describe('Config', function () { return config.set({url: 'http://my-ghost-blog.com/blog'}); }).then(function () { - // next test return config.urlForPost(settings, testData); }).then(function (url) { @@ -479,8 +470,7 @@ describe('Config', function () { }); it('rejects a fqdn without a scheme', function (done) { - - overrideConfig({ url: 'example.com' }); + overrideConfig({url: 'example.com'}); config.load().then(function () { done(expectedError); @@ -493,8 +483,7 @@ describe('Config', function () { }); it('rejects a hostname without a scheme', function (done) { - - overrideConfig({ url: 'example' }); + overrideConfig({url: 'example'}); config.load().then(function () { done(expectedError); @@ -507,8 +496,7 @@ describe('Config', function () { }); it('rejects a hostname with a scheme', function (done) { - - overrideConfig({ url: 'https://example' }); + overrideConfig({url: 'https://example'}); config.load().then(function () { done(expectedError); @@ -521,8 +509,7 @@ describe('Config', function () { }); it('rejects a url with an unsupported scheme', function (done) { - - overrideConfig({ url: 'ftp://example.com' }); + overrideConfig({url: 'ftp://example.com'}); config.load().then(function () { done(expectedError); @@ -535,8 +522,7 @@ describe('Config', function () { }); it('rejects a url with a protocol relative scheme', function (done) { - - overrideConfig({ url: '//example.com' }); + overrideConfig({url: '//example.com'}); config.load().then(function () { done(expectedError); @@ -549,7 +535,7 @@ describe('Config', function () { }); it('does not permit the word ghost as a url path', function (done) { - overrideConfig({ url: 'http://example.com/ghost/' }); + overrideConfig({url: 'http://example.com/ghost/'}); config.load().then(function () { done(expectedError); @@ -562,7 +548,7 @@ describe('Config', function () { }); it('does not permit the word ghost to be a component in a url path', function (done) { - overrideConfig({ url: 'http://example.com/blog/ghost/' }); + overrideConfig({url: 'http://example.com/blog/ghost/'}); config.load().then(function () { done(expectedError); @@ -575,7 +561,7 @@ describe('Config', function () { }); it('does not permit the word ghost to be a component in a url path', function (done) { - overrideConfig({ url: 'http://example.com/ghost/blog/' }); + overrideConfig({url: 'http://example.com/ghost/blog/'}); config.load().then(function () { done(expectedError); @@ -589,7 +575,7 @@ describe('Config', function () { it('does not permit database config to be falsy', function (done) { // replace the config file with invalid data - overrideConfig({ database: false }); + overrideConfig({database: false}); config.load().then(function () { done(expectedError); @@ -603,7 +589,7 @@ describe('Config', function () { it('does not permit database config to be empty', function (done) { // replace the config file with invalid data - overrideConfig({ database: {} }); + overrideConfig({database: {}}); config.load().then(function () { done(expectedError); @@ -615,9 +601,8 @@ describe('Config', function () { }).catch(done); }); - it('requires server to be present', function (done) { - overrideConfig({ server: false }); + overrideConfig({server: false}); config.load().then(function (localConfig) { /*jshint unused:false*/ @@ -631,7 +616,7 @@ describe('Config', function () { }); it('allows server to use a socket', function (done) { - overrideConfig({ server: { socket: 'test' } }); + overrideConfig({server: {socket: 'test'}}); config.load().then(function (localConfig) { should.exist(localConfig); @@ -642,7 +627,7 @@ describe('Config', function () { }); it('allows server to have a host and a port', function (done) { - overrideConfig({ server: { host: '127.0.0.1', port: '2368' } }); + overrideConfig({server: {host: '127.0.0.1', port: '2368'}}); config.load().then(function (localConfig) { should.exist(localConfig); @@ -654,7 +639,7 @@ describe('Config', function () { }); it('rejects server if there is a host but no port', function (done) { - overrideConfig({ server: { host: '127.0.0.1' } }); + overrideConfig({server: {host: '127.0.0.1'}}); config.load().then(function () { done(expectedError); @@ -667,7 +652,7 @@ describe('Config', function () { }); it('rejects server if there is a port but no host', function (done) { - overrideConfig({ server: { port: '2368' } }); + overrideConfig({server: {port: '2368'}}); config.load().then(function () { done(expectedError); @@ -680,7 +665,7 @@ describe('Config', function () { }); it('rejects server if configuration is empty', function (done) { - overrideConfig({ server: {} }); + overrideConfig({server: {}}); config.load().then(function () { done(expectedError); @@ -692,4 +677,4 @@ describe('Config', function () { }).catch(done); }); }); -}); \ No newline at end of file +}); diff --git a/core/test/unit/errorHandling_spec.js b/core/test/unit/errorHandling_spec.js index 80c14260aa..4497e3bdac 100644 --- a/core/test/unit/errorHandling_spec.js +++ b/core/test/unit/errorHandling_spec.js @@ -19,7 +19,6 @@ var should = require('should'), colors.setTheme({silly: 'rainbow'}); describe('Error handling', function () { - // Just getting rid of jslint unused error should.exist(errors); @@ -179,7 +178,6 @@ describe('Error handling', function () { logStub.calledOnce.should.be.true; logStub.firstCall.calledWith('\nERROR:'.red, message.red, '\n', message.white, '\n').should.be.true; - }); it('logs promise errors and redirects', function (done) { @@ -215,11 +213,11 @@ describe('Error handling', function () { before(function () { originalConfig = _.cloneDeep(config._config); errors.__set__('getConfigModule', sinon.stub().returns(_.merge({}, originalConfig, { - 'paths': { - 'themePath': '/content/themes', - 'availableThemes': { - 'casper': { - 'assets': null, + paths: { + themePath: '/content/themes', + availableThemes: { + casper: { + assets: null, 'default.hbs': '/content/themes/casper/default.hbs', 'index.hbs': '/content/themes/casper/index.hbs', 'page.hbs': '/content/themes/casper/page.hbs', @@ -298,7 +296,6 @@ describe('Error handling', function () { return res; }); - err.status = 404; errors.error500(err, req, res, null); }); diff --git a/core/test/unit/filters_spec.js b/core/test/unit/filters_spec.js index c9ec45492a..520b0b62e5 100644 --- a/core/test/unit/filters_spec.js +++ b/core/test/unit/filters_spec.js @@ -9,7 +9,6 @@ var should = require('should'), Filters = require('../../server/filters').Filters; describe('Filters', function () { - var filters, sandbox; beforeEach(function () { @@ -72,7 +71,6 @@ describe('Filters', function () { filters.registerFilter(filterName, 9, testFilterHandler3); filters.doFilter(filterName, null).then(function () { - testFilterHandler1.calledBefore(testFilterHandler2).should.equal(true); testFilterHandler2.calledBefore(testFilterHandler3).should.equal(true); @@ -112,8 +110,7 @@ describe('Filters', function () { filters.registerFilter(filterName, 2, testFilterHandler2); filters.registerFilter(filterName, 9, testFilterHandler3); - filters.doFilter(filterName, { test: true }).then(function (newArgs) { - + filters.doFilter(filterName, {test: true}).then(function (newArgs) { testFilterHandler1.calledBefore(testFilterHandler2).should.equal(true); testFilterHandler2.calledBefore(testFilterHandler3).should.equal(true); @@ -141,12 +138,10 @@ describe('Filters', function () { filters.registerFilter(filterName, 0, testFilterHandler1); filters.registerFilter(filterName, 1, testFilterHandler2); - filters.doFilter(filterName, { test: true }, { context: true }).then(function (newArgs) { - + filters.doFilter(filterName, {test: true}, {context: true}).then(function (newArgs) { newArgs.context1.should.equal(true); newArgs.context2.should.equal(true); done(); }).catch(done); }); - -}); \ No newline at end of file +}); diff --git a/core/test/unit/frontend_spec.js b/core/test/unit/frontend_spec.js index 5f959b8a9f..403daf12ee 100644 --- a/core/test/unit/frontend_spec.js +++ b/core/test/unit/frontend_spec.js @@ -17,7 +17,6 @@ var assert = require('assert'), should.equal(true, true); describe('Frontend Controller', function () { - var sandbox, apiSettingsStub, adminEditPagePath = '/ghost/editor/'; @@ -42,7 +41,6 @@ describe('Frontend Controller', function () { }; } - describe('homepage redirects', function () { var res; @@ -53,14 +51,14 @@ describe('Frontend Controller', function () { }; sandbox.stub(api.posts, 'browse', function () { - return Promise.resolve({posts: {}, meta: {pagination: { pages: 3}}}); + return Promise.resolve({posts: {}, meta: {pagination: {pages: 3}}}); }); apiSettingsStub = sandbox.stub(api.settings, 'read'); apiSettingsStub.withArgs('postsPerPage').returns(Promise.resolve({ settings: [{ - 'key': 'postsPerPage', - 'value': 5 + key: 'postsPerPage', + value: 5 }] })); }); @@ -73,7 +71,6 @@ describe('Frontend Controller', function () { res.redirect.called.should.be.true; res.redirect.calledWith('/').should.be.true; res.render.called.should.be.false; - }); it('Redirects to home if page number is 0', function () { @@ -84,7 +81,6 @@ describe('Frontend Controller', function () { res.redirect.called.should.be.true; res.redirect.calledWith('/').should.be.true; res.render.called.should.be.false; - }); it('Redirects to home if page number is 1', function () { @@ -153,7 +149,6 @@ describe('Frontend Controller', function () { }); describe('homepage', function () { - beforeEach(function () { sandbox.stub(api.posts, 'browse', function () { return Promise.resolve({ @@ -171,24 +166,24 @@ describe('Frontend Controller', function () { apiSettingsStub.withArgs(sinon.match.has('key', 'activeTheme')).returns(Promise.resolve({ settings: [{ - 'key': 'activeTheme', - 'value': 'casper' + key: 'activeTheme', + value: 'casper' }] })); apiSettingsStub.withArgs('postsPerPage').returns(Promise.resolve({ settings: [{ - 'key': 'postsPerPage', - 'value': '10' + key: 'postsPerPage', + value: '10' }] })); frontend.__set__('config', { - 'paths': { - 'subdir': '', - 'availableThemes': { - 'casper': { - 'assets': null, + paths: { + subdir: '', + availableThemes: { + casper: { + assets: null, 'default.hbs': '/content/themes/casper/default.hbs', 'index.hbs': '/content/themes/casper/index.hbs', 'home.hbs': '/content/themes/casper/home.hbs', @@ -236,11 +231,11 @@ describe('Frontend Controller', function () { it('Renders index.hbs template when home.hbs doesn\'t exist', function (done) { frontend.__set__('config', { - 'paths': { - 'subdir': '', - 'availableThemes': { - 'casper': { - 'assets': null, + paths: { + subdir: '', + availableThemes: { + casper: { + assets: null, 'default.hbs': '/content/themes/casper/default.hbs', 'index.hbs': '/content/themes/casper/index.hbs', 'page.hbs': '/content/themes/casper/page.hbs', @@ -268,40 +263,40 @@ describe('Frontend Controller', function () { describe('tag', function () { var mockPosts = [{ - 'status': 'published', - 'id': 1, - 'title': 'Test static page', - 'slug': 'test-static-page', - 'markdown': 'Test static page content', - 'page': 1, - 'published_at': new Date('2013/12/30').getTime(), - 'author': { - 'id': 1, - 'name': 'Test User', - 'email': 'test@ghost.org' + status: 'published', + id: 1, + title: 'Test static page', + slug: 'test-static-page', + markdown: 'Test static page content', + page: 1, + published_at: new Date('2013/12/30').getTime(), + author: { + id: 1, + name: 'Test User', + email: 'test@ghost.org' } }, { - 'status': 'published', - 'id': 2, - 'title': 'Test normal post', - 'slug': 'test-normal-post', - 'markdown': 'The test normal post content', - 'page': 0, - 'published_at': new Date('2014/1/2').getTime(), - 'author': { - 'id': 1, - 'name': 'Test User', - 'email': 'test@ghost.org' + status: 'published', + id: 2, + title: 'Test normal post', + slug: 'test-normal-post', + markdown: 'The test normal post content', + page: 0, + published_at: new Date('2014/1/2').getTime(), + author: { + id: 1, + name: 'Test User', + email: 'test@ghost.org' } }], mockTags = [{ - 'name': 'video', - 'slug': 'video', - 'id': 1 + name: 'video', + slug: 'video', + id: 1 }, { - 'name': 'audio', - 'slug': 'audio', - 'id': 2 + name: 'audio', + slug: 'audio', + id: 2 }]; beforeEach(function () { @@ -324,24 +319,24 @@ describe('Frontend Controller', function () { apiSettingsStub.withArgs(sinon.match.has('key', 'activeTheme')).returns(Promise.resolve({ settings: [{ - 'key': 'activeTheme', - 'value': 'casper' + key: 'activeTheme', + value: 'casper' }] })); apiSettingsStub.withArgs('postsPerPage').returns(Promise.resolve({ settings: [{ - 'key': 'postsPerPage', - 'value': '10' + key: 'postsPerPage', + value: '10' }] })); frontend.__set__('config', { - 'paths': { - 'subdir': '', - 'availableThemes': { - 'casper': { - 'assets': null, + paths: { + subdir: '', + availableThemes: { + casper: { + assets: null, 'default.hbs': '/content/themes/casper/default.hbs', 'index.hbs': '/content/themes/casper/index.hbs', 'page.hbs': '/content/themes/casper/page.hbs', @@ -353,7 +348,6 @@ describe('Frontend Controller', function () { }); describe('custom tag template', function () { - beforeEach(function () { apiSettingsStub.withArgs('permalinks').returns(Promise.resolve({ settings: [{ @@ -392,14 +386,14 @@ describe('Frontend Controller', function () { }; sandbox.stub(api.posts, 'browse', function () { - return Promise.resolve({posts: {}, meta: {pagination: { pages: 3}}}); + return Promise.resolve({posts: {}, meta: {pagination: {pages: 3}}}); }); apiSettingsStub = sandbox.stub(api.settings, 'read'); apiSettingsStub.withArgs('postsPerPage').returns(Promise.resolve({ settings: [{ - 'key': 'postsPerPage', - 'value': 5 + key: 'postsPerPage', + value: 5 }] })); }); @@ -412,7 +406,6 @@ describe('Frontend Controller', function () { res.redirect.called.should.be.true; res.redirect.calledWith('/tag/pumpkin/').should.be.true; res.render.called.should.be.false; - }); it('Redirects to base tag page if page number is 0', function () { @@ -423,7 +416,6 @@ describe('Frontend Controller', function () { res.redirect.called.should.be.true; res.redirect.calledWith('/tag/pumpkin/').should.be.true; res.render.called.should.be.false; - }); it('Redirects to base tag page if page number is 1', function () { @@ -488,54 +480,53 @@ describe('Frontend Controller', function () { res.render.called.should.be.false; done(); }).catch(done); - }); }); describe('single', function () { var mockPosts = [{ - 'posts': [{ - 'status': 'published', - 'id': 1, - 'title': 'Test static page', - 'slug': 'test-static-page', - 'markdown': 'Test static page content', - 'page': 1, - 'published_at': new Date('2013/12/30').getTime(), - 'author': { - 'id': 1, - 'name': 'Test User', - 'email': 'test@ghost.org' + posts: [{ + status: 'published', + id: 1, + title: 'Test static page', + slug: 'test-static-page', + markdown: 'Test static page content', + page: 1, + published_at: new Date('2013/12/30').getTime(), + author: { + id: 1, + name: 'Test User', + email: 'test@ghost.org' } }] }, { - 'posts': [{ - 'status': 'published', - 'id': 2, - 'title': 'Test normal post', - 'slug': 'test-normal-post', - 'markdown': 'The test normal post content', - 'page': 0, - 'published_at': new Date('2014/1/2').getTime(), - 'author': { - 'id': 1, - 'name': 'Test User', - 'email': 'test@ghost.org' + posts: [{ + status: 'published', + id: 2, + title: 'Test normal post', + slug: 'test-normal-post', + markdown: 'The test normal post content', + page: 0, + published_at: new Date('2014/1/2').getTime(), + author: { + id: 1, + name: 'Test User', + email: 'test@ghost.org' } }] }, { - 'posts': [{ - 'status': 'published', - 'id': 3, - 'title': 'About', - 'slug': 'about', - 'markdown': 'This is the about page content', - 'page': 1, - 'published_at': new Date('2014/1/30').getTime(), - 'author': { - 'id': 1, - 'name': 'Test User', - 'email': 'test@ghost.org' + posts: [{ + status: 'published', + id: 3, + title: 'About', + slug: 'about', + markdown: 'This is the about page content', + page: 1, + published_at: new Date('2014/1/30').getTime(), + author: { + id: 1, + name: 'Test User', + email: 'test@ghost.org' } }] }]; @@ -551,17 +542,17 @@ describe('Frontend Controller', function () { apiSettingsStub.withArgs(sinon.match.has('key', 'activeTheme')).returns(Promise.resolve({ settings: [{ - 'key': 'activeTheme', - 'value': 'casper' + key: 'activeTheme', + value: 'casper' }] })); frontend.__set__('config', { - 'paths': { - 'subdir': '', - 'availableThemes': { - 'casper': { - 'assets': null, + paths: { + subdir: '', + availableThemes: { + casper: { + assets: null, 'default.hbs': '/content/themes/casper/default.hbs', 'index.hbs': '/content/themes/casper/index.hbs', 'page.hbs': '/content/themes/casper/page.hbs', @@ -574,7 +565,6 @@ describe('Frontend Controller', function () { }); describe('static pages', function () { - describe('custom page templates', function () { beforeEach(function () { apiSettingsStub.withArgs('permalinks').returns(Promise.resolve({ @@ -1028,13 +1018,13 @@ describe('Frontend Controller', function () { beforeEach(function () { res = { - locals: { version: '' }, + locals: {version: ''}, redirect: sandbox.spy(), render: sandbox.spy() }; sandbox.stub(api.posts, 'browse', function () { - return Promise.resolve({posts: {}, meta: {pagination: { pages: 3}}}); + return Promise.resolve({posts: {}, meta: {pagination: {pages: 3}}}); }); apiUsersStub = sandbox.stub(api.users, 'read').returns(Promise.resolve({})); @@ -1042,20 +1032,20 @@ describe('Frontend Controller', function () { apiSettingsStub = sandbox.stub(api.settings, 'read'); apiSettingsStub.withArgs('title').returns(Promise.resolve({ settings: [{ - 'key': 'title', - 'value': 'Test' + key: 'title', + value: 'Test' }] })); apiSettingsStub.withArgs('description').returns(Promise.resolve({ settings: [{ - 'key': 'description', - 'value': 'Some Text' + key: 'description', + value: 'Some Text' }] })); apiSettingsStub.withArgs('permalinks').returns(Promise.resolve({ settings: [{ - 'key': 'permalinks', - 'value': '/:slug/' + key: 'permalinks', + value: '/:slug/' }] })); }); @@ -1068,7 +1058,6 @@ describe('Frontend Controller', function () { res.redirect.called.should.be.true; res.redirect.calledWith('/rss/').should.be.true; res.render.called.should.be.false; - }); it('Redirects to rss if page number is 0', function () { @@ -1079,7 +1068,6 @@ describe('Frontend Controller', function () { res.redirect.called.should.be.true; res.redirect.calledWith('/rss/').should.be.true; res.render.called.should.be.false; - }); it('Redirects to home if page number is 1', function () { @@ -1140,7 +1128,6 @@ describe('Frontend Controller', function () { res.render.called.should.be.false; done(); }).catch(done); - }); }); -}); \ No newline at end of file +}); diff --git a/core/test/unit/mail_spec.js b/core/test/unit/mail_spec.js index c4177396c3..41c3d89c28 100644 --- a/core/test/unit/mail_spec.js +++ b/core/test/unit/mail_spec.js @@ -26,7 +26,6 @@ SMTP = { } }; - describe('Mail', function () { var overrideConfig = function (newConfig) { var config = rewire('../../server/config'), @@ -43,7 +42,6 @@ describe('Mail', function () { email: 'ghost-test@localhost' }; - overrideConfig(fakeConfig); }); @@ -82,8 +80,8 @@ describe('Mail', function () { Promise.settle([ mailer.send(), mailer.send({}), - mailer.send({ subject: '123' }), - mailer.send({ subject: '', html: '123' }) + mailer.send({subject: '123'}), + mailer.send({subject: '', html: '123'}) ]).then(function (descriptors) { descriptors.forEach(function (d) { d.isRejected().should.be.true; diff --git a/core/test/unit/middleware_spec.js b/core/test/unit/middleware_spec.js index 12c5f50b2d..1dd7ac6012 100644 --- a/core/test/unit/middleware_spec.js +++ b/core/test/unit/middleware_spec.js @@ -6,7 +6,6 @@ var assert = require('assert'), middleware = require('../../server/middleware').middleware; describe('Middleware', function () { - // TODO: needs new test for ember admin // describe('redirectToDashboard', function () { // var req, res; @@ -172,4 +171,3 @@ describe('Middleware', function () { }); }); }); - diff --git a/core/test/unit/permissions_spec.js b/core/test/unit/permissions_spec.js index 44067e261c..e5b4b05713 100644 --- a/core/test/unit/permissions_spec.js +++ b/core/test/unit/permissions_spec.js @@ -33,10 +33,8 @@ describe('Permissions', function () { sandbox.stub(Models.Permission, 'findAll', function () { return Promise.resolve(Models.Permissions.forge(permissions)); }); - }); - it('can load an actions map from existing permissions', function (done) { permissions.init().then(function (actionsMap) { should.exist(actionsMap); @@ -49,9 +47,6 @@ describe('Permissions', function () { }).catch(done); }); - - - // it('does not allow edit post without permission', function (done) { // var fakePage = { // id: 1 @@ -70,7 +65,7 @@ describe('Permissions', function () { // done(new Error('was able to edit post without permission')); // }).catch(done); // }); -////// +// //// // it('allows edit post with permission', function (done) { // var fakePost = { // id: '1' @@ -284,4 +279,4 @@ describe('Permissions', function () { // done(new Error('Should allow editing post with { internal: true }')); // }); // }); -}); \ No newline at end of file +}); diff --git a/core/test/unit/server_helpers_index_spec.js b/core/test/unit/server_helpers_index_spec.js index 07c7719559..321f41c84d 100644 --- a/core/test/unit/server_helpers_index_spec.js +++ b/core/test/unit/server_helpers_index_spec.js @@ -15,7 +15,6 @@ var should = require('should'), config = rewire('../../server/config'); describe('Core Helpers', function () { - var sandbox, apiStub, overrideConfig = function (newConfig) { @@ -34,11 +33,11 @@ describe('Core Helpers', function () { }); overrideConfig({ - 'paths': { - 'subdir': '', - 'availableThemes': { - 'casper': { - 'assets': null, + paths: { + subdir: '', + availableThemes: { + casper: { + assets: null, 'default.hbs': '/content/themes/casper/default.hbs', 'index.hbs': '/content/themes/casper/index.hbs', 'page.hbs': '/content/themes/casper/page.hbs', @@ -56,7 +55,7 @@ describe('Core Helpers', function () { helpers.loadCoreHelpers(adminHbs); // Load template helpers in handlebars - hbs.express3({ partialsDir: [config.paths.helperTemplates] }); + hbs.express3({partialsDir: [config.paths.helperTemplates]}); hbs.cachePartials(function () { done(); }); @@ -85,7 +84,7 @@ describe('Core Helpers', function () { helpers.content .call( {html: html}, - {'hash': {'words': 2}} + {hash: {words: 2}} ) ); @@ -99,7 +98,7 @@ describe('Core Helpers', function () { helpers.content .call( {html: html}, - {'hash': {'words': '0'}} + {hash: {words: '0'}} ) ); @@ -113,7 +112,7 @@ describe('Core Helpers', function () { helpers.content .call( {html: html}, - {'hash': {'words': '0'}} + {hash: {words: '0'}} ) ); @@ -127,7 +126,7 @@ describe('Core Helpers', function () { helpers.content .call( {html: html}, - {'hash': {'words': '0'}} + {hash: {words: '0'}} ) ); @@ -141,7 +140,7 @@ describe('Core Helpers', function () { helpers.content .call( {html: html}, - {'hash': { 'words': '0' } } + {hash: {words: '0'}} ) ); @@ -155,8 +154,8 @@ describe('Core Helpers', function () { rendered = ( helpers.content .call( - {html: html }, - {'hash': { 'words': '0' } } + {html: html}, + {hash: {words: '0'}} ) ); @@ -169,8 +168,8 @@ describe('Core Helpers', function () { rendered = ( helpers.content .call( - {html: html }, - {'hash': { 'words': '0' } } + {html: html}, + {hash: {words: '0'}} ) ); @@ -183,8 +182,8 @@ describe('Core Helpers', function () { rendered = ( helpers.content .call( - {html: html }, - {'hash': { 'words': '0' } } + {html: html}, + {hash: {words: '0'}} ) ); @@ -197,8 +196,8 @@ describe('Core Helpers', function () { rendered = ( helpers.content .call( - {html: html }, - {'hash': { 'words': '0' } } + {html: html}, + {hash: {words: '0'}} ) ); @@ -211,8 +210,8 @@ describe('Core Helpers', function () { rendered = ( helpers.content .call( - {html: html }, - {'hash': { 'words': '0' } } + {html: html}, + {hash: {words: '0'}} ) ); @@ -226,7 +225,7 @@ describe('Core Helpers', function () { helpers.content .call( {html: html}, - {'hash': {'characters': 8}} + {hash: {characters: 8}} ) ); @@ -249,13 +248,13 @@ describe('Core Helpers', function () { }); it('escapes correctly', function () { - var rendered = helpers.title.call({'title': '