diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000000..69bd6355e5 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,76 @@ +module.exports = { + extends: [ + 'airbnb/legacy' + ], + rules: { + camelcase: 0, + 'comma-dangle': [2, 'never'], + 'comma-spacing': [2, { before: false, after: true }], + 'consistent-return': 0, + curly: 0, + 'default-case': 0, + eqeqeq: [2, 'smart'], + 'func-names': 0, + 'guard-for-in': 2, + indent: [2, 2, { SwitchCase: 1, VariableDeclarator: { var: 2, let: 2, const: 3 } }], + 'key-spacing': [2, { beforeColon: false, afterColon: true }], + 'keyword-spacing': [2, { before: true, after: true }], + 'max-len': 0, + 'new-cap': [2, { newIsCapExceptions: ['acl.memoryBackend', 'acl'] }], + 'no-bitwise': 0, + 'no-caller': 2, + 'no-console': 0, + 'no-else-return': 0, + 'no-empty-class': 0, + 'no-multi-spaces': 2, + 'no-param-reassign': 0, + 'no-shadow': 0, + 'no-spaced-func': 2, + 'no-throw-literal': 2, + 'no-trailing-spaces': 2, + 'no-undef': 2, + 'no-unneeded-ternary': 2, + 'no-unreachable': 2, + 'no-underscore-dangle': 0, + 'no-unused-expressions': 0, + 'no-unused-vars': 0, + 'no-use-before-define': [1, 'nofunc'], + 'no-var': 0, + 'object-curly-spacing': [2, 'always'], + 'one-var': [0, 'never'], + 'one-var-declaration-per-line': [2, 'always'], + 'padded-blocks': 0, + 'space-before-function-paren': 0, + 'space-in-parens': [2, 'never'], + 'spaced-comment': [2, 'always'], + strict: 0, + 'quote-props': 0, + quotes: [1, 'single'], + 'wrap-iife': [2, 'outside'], + 'vars-on-top': 0 + }, + env: { + node: true, + browser: true, + jasmine: true, + mocha: true, + jquery: true + }, + globals: { + angular: true, + PruneCluster: true, + PruneClusterForLeaflet: true, + PhusionPassenger: true, + L: true, + by: true, + browser: true, + element: true, + inject: true, + io: true, + moment: true, + Promise: true, + __TESTING__: true, + _: false, + AppConfig: true + } +}; diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 9e2a51568f..0000000000 --- a/.jshintrc +++ /dev/null @@ -1,43 +0,0 @@ -{ - "node": true, // Enable globals available when code is running inside of the NodeJS runtime environment. - "mocha": true, // Enable globals available when code is running inside of the Mocha tests. - "jasmine": true, // Enable globals available when code is running inside of the Jasmine tests. - "browser": true, // Standard browser globals e.g. `window`, `document`. - "esnext": true, // Allow ES.next specific features such as `const` and `let`. - "bitwise": false, // Prohibit bitwise operators (&, |, ^, etc.). - "camelcase": false, // Permit only camelcase for `var` and `object indexes`. - "curly": false, // Require {} for every new block or scope. - "eqeqeq": true, // Require triple equals i.e. `===`. - "immed": true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );` - "latedef": false, // Prohibit variable use before definition. - "noarg": true, // Prohibit use of `arguments.caller` and `arguments.callee`. - "quotmark": "single", // Define quotes to string values. - "regexp": true, // Prohibit `.` and `[^...]` in regular expressions. - "undef": true, // Require all non-global variables be declared before they are used. - "unused": false, // Warn unused variables. - "strict": true, // Require `use strict` pragma in every file. - "trailing": true, // Prohibit trailing whitespaces. - "smarttabs": false, // Suppresses warnings about mixed tabs and spaces - "globals": { // Globals variables. - "jQuery": true, - "angular": true, - "io": true, - "PruneCluster": true, - "PruneClusterForLeaflet": true, - "L": true, // Leaflet - "moment": true, - "AppConfig": true, - "ga": true, // Google Analytics - "PhusionPassenger": true, - "FastClick": true - }, - "predef": [ // Extra globals. - "inject", - "by", - "browser", - "element" - ], - "indent": 2, // Specify indentation spacing - "devel": true, // Allow development statements e.g. `console.log();` and `alert`. - "noempty": true // Prohibit use of empty blocks. -} diff --git a/.travis.yml b/.travis.yml index 48be5ac9c9..db60f71a18 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,11 +1,7 @@ language: node_js node_js: - - 4 - 5 - 6 -matrix: - allow_failures: - - node_js: 4 # NodeJS v4 requires gcc 4.8 env: - NODE_ENV=travis CXX="g++-4.8" CC="gcc-4.8" diff --git a/config/assets/default.js b/config/assets/default.js index 1fcb399821..05ca681c1f 100644 --- a/config/assets/default.js +++ b/config/assets/default.js @@ -18,7 +18,7 @@ module.exports = { 'modules/core/client/fonts/fontello/css/tricons-codes.css', 'public/lib/angular-ui-bootstrap/src/position/position.css', 'public/lib/angular-ui-bootstrap/src/typeahead/typeahead.css', - 'public/lib/angular-ui-bootstrap/src/tooltip/tooltip.css', + 'public/lib/angular-ui-bootstrap/src/tooltip/tooltip.css' ], js: [ // Non minified versions @@ -115,12 +115,12 @@ module.exports = { // Reset and dependencies 'public/lib/bootstrap/less/normalize.less', 'public/lib/bootstrap/less/print.less', - //'public/lib/bootstrap/less/glyphicons.less', + // 'public/lib/bootstrap/less/glyphicons.less', // Core CSS 'public/lib/bootstrap/less/scaffolding.less', 'public/lib/bootstrap/less/type.less', - //'public/lib/bootstrap/less/code.less', + // 'public/lib/bootstrap/less/code.less', 'public/lib/bootstrap/less/grid.less', 'public/lib/bootstrap/less/tables.less', 'public/lib/bootstrap/less/forms.less', @@ -133,27 +133,27 @@ module.exports = { 'public/lib/bootstrap/less/input-groups.less', 'public/lib/bootstrap/less/navs.less', 'public/lib/bootstrap/less/navbar.less', - //'public/lib/bootstrap/less/breadcrumbs.less', - //'public/lib/bootstrap/less/pagination.less', - //'public/lib/bootstrap/less/pager.less', + // 'public/lib/bootstrap/less/breadcrumbs.less', + // 'public/lib/bootstrap/less/pagination.less', + // 'public/lib/bootstrap/less/pager.less', 'public/lib/bootstrap/less/labels.less', 'public/lib/bootstrap/less/badges.less', - //'public/lib/bootstrap/less/jumbotron.less', - //'public/lib/bootstrap/less/thumbnails.less', + // 'public/lib/bootstrap/less/jumbotron.less', + // 'public/lib/bootstrap/less/thumbnails.less', 'public/lib/bootstrap/less/alerts.less', 'public/lib/bootstrap/less/progress-bars.less', 'public/lib/bootstrap/less/media.less', 'public/lib/bootstrap/less/list-group.less', 'public/lib/bootstrap/less/panels.less', - //'public/lib/bootstrap/less/responsive-embed.less', - //'public/lib/bootstrap/less/wells.less', + // 'public/lib/bootstrap/less/responsive-embed.less', + // 'public/lib/bootstrap/less/wells.less', 'public/lib/bootstrap/less/close.less', // Components w/ JavaScript 'public/lib/bootstrap/less/modals.less', 'public/lib/bootstrap/less/tooltip.less', 'public/lib/bootstrap/less/popovers.less', - //'public/lib/bootstrap/less/carousel.less', + // 'public/lib/bootstrap/less/carousel.less', // Utility classes 'public/lib/bootstrap/less/utilities.less', diff --git a/config/assets/development.js b/config/assets/development.js index 5f64512693..602a3add26 100644 --- a/config/assets/development.js +++ b/config/assets/development.js @@ -19,5 +19,5 @@ module.exports = { less: defaultAssets.client.less, js: defaultAssets.client.js, views: defaultAssets.client.views - }, + } }; diff --git a/config/assets/production.js b/config/assets/production.js index e6f1fc68c9..c8e3cd2b6c 100644 --- a/config/assets/production.js +++ b/config/assets/production.js @@ -19,8 +19,8 @@ module.exports = { less: defaultAssets.client.less, js: _.union(defaultAssets.client.js, [ 'public/dist/uib-templates.js', - 'public/dist/templates.js', + 'public/dist/templates.js' ]), views: defaultAssets.client.views - }, + } }; diff --git a/config/config.js b/config/config.js index 0b6b117f7c..157ad3c0f8 100644 --- a/config/config.js +++ b/config/config.js @@ -33,7 +33,9 @@ var getGlobbedPaths = function(globPatterns, excludes) { files = files.map(function(file) { if (_.isArray(excludes)) { for (var i in excludes) { - file = file.replace(excludes[i], ''); + if (excludes.hasOwnProperty(i)) { + file = file.replace(excludes[i], ''); + } } } else { file = file.replace(excludes, ''); @@ -80,7 +82,7 @@ var initGlobalConfigFolders = function(config, assets) { }; // Setting globbed client paths - config.folders.client = getGlobbedPaths(path.join(process.cwd(), 'modules/*/client/'), process.cwd().replace(new RegExp(/\\/g),'/')); + config.folders.client = getGlobbedPaths(path.join(process.cwd(), 'modules/*/client/'), process.cwd().replace(new RegExp(/\\/g), '/')); }; /** @@ -108,7 +110,7 @@ var initGlobalConfigFiles = function(config, assets) { config.files.server.policies = getGlobbedPaths(assets.server.policies); // Setting Globbed js files - if(process.env.NODE_ENV === 'production') { + if (process.env.NODE_ENV === 'production') { // In production mode assets.client.lib.js are combined into client.js already config.files.client.js = getGlobbedPaths(assets.client.js, ['client/', 'public/']); config.files.client.lib.js = getGlobbedPaths(assets.client.lib.js, 'public/'); @@ -117,7 +119,7 @@ var initGlobalConfigFiles = function(config, assets) { } // Setting Globbed css files - if(process.env.NODE_ENV === 'production') { + if (process.env.NODE_ENV === 'production') { // In production mode assets.client.lib.css are combined into client.css already config.files.client.css = getGlobbedPaths(assets.client.css, ['client/', 'public/']); } else { diff --git a/config/env/default.js b/config/env/default.js index c3146fa767..f961f3f290 100644 --- a/config/env/default.js +++ b/config/env/default.js @@ -15,7 +15,7 @@ module.exports = { title: 'Trustroots', description: 'Travellers community for sharing, hosting and getting people together. We want a world that encourages trust and adventure.' }, - maxUploadSize: process.env.MAX_UPLOAD_SIZE || 10*1024*1024, // 10MB. Remember to change this to Nginx configs as well + maxUploadSize: process.env.MAX_UPLOAD_SIZE || 10 * 1024 * 1024, // 10MB. Remember to change this to Nginx configs as well imageProcessor: 'graphicsmagick', // graphicsmagick|imagemagick uploadTmpDir: './tmp/', uploadDir: './modules/users/client/img/profile/uploads/', @@ -59,7 +59,7 @@ module.exports = { map: 'outdoors-v9', user: 'mapbox', legacy: false - }, + } }, user: process.env.MAPBOX_USERNAME || false, publicKey: process.env.MAPBOX_ACCESS_TOKEN || false @@ -77,7 +77,7 @@ module.exports = { callbackURL: '/api/auth/twitter/callback' }, google: { - page: process.env.GOOGLE_PAGE || '', + page: process.env.GOOGLE_PAGE || '' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', diff --git a/config/env/development.js b/config/env/development.js index 9a1d097e88..257b7e1e00 100644 --- a/config/env/development.js +++ b/config/env/development.js @@ -17,8 +17,8 @@ module.exports = { auth: { authMechanism: '' } - //user: '', - //pass: '' + // user: '', + // pass: '' }, // Enable mongoose debug mode debug: process.env.MONGODB_DEBUG || false diff --git a/config/env/production.js b/config/env/production.js index f70e378646..84acb6ab14 100644 --- a/config/env/production.js +++ b/config/env/production.js @@ -17,8 +17,8 @@ module.exports = { auth: { authMechanism: '' } - //user: '', - //pass: '' + // user: '', + // pass: '' }, // Enable mongoose debug mode debug: process.env.MONGODB_DEBUG || false diff --git a/config/env/test.js b/config/env/test.js index a73f9e297f..82c5b07388 100644 --- a/config/env/test.js +++ b/config/env/test.js @@ -17,8 +17,8 @@ module.exports = { auth: { authMechanism: '' } - //user: '', - //pass: '' + // user: '', + // pass: '' }, // Enable mongoose debug mode debug: process.env.MONGODB_DEBUG || false diff --git a/config/lib/express.js b/config/lib/express.js index 5407ab0d9d..b9d47dc11f 100644 --- a/config/lib/express.js +++ b/config/lib/express.js @@ -23,7 +23,6 @@ var _ = require('lodash'), path = require('path'), paginate = require('express-paginate'), seo = require('mean-seo'), - path = require('path'), Agenda = require('agenda'); /** @@ -146,7 +145,7 @@ module.exports.initSession = function (app, db) { secret: config.sessionSecret, cookie: { // If secure is true, and you access your site over HTTP, the cookie will not be set. - secure: false,//config.https, + secure: false, // ...or you could use `config.https`, but it screws things up with Nginx proxy. // By default cookie.maxAge is null, meaning no "expires" parameter is // set so the cookie becomes a browser-session cookie. When the user @@ -205,7 +204,7 @@ module.exports.initHelmetHeaders = function (app) { module.exports.initSEO = function (app) { app.use(seo({ cacheClient: 'disk', // Can be 'disk' or 'redis' - cacheDuration: 2 * 60 * 60 * 24 * 1000, // In milliseconds for disk cache + cacheDuration: 2 * 60 * 60 * 24 * 1000 // In milliseconds for disk cache })); }; @@ -218,7 +217,7 @@ module.exports.initAgenda = function (app, db) { // Don't launch Agenda on test environment // @todo: make it possible to launch this manually with very small interwalls for testing // @todo: similarly for testing purposes, write a stopAgenda() method - if(process.env.NODE_ENV === 'test') { + if (process.env.NODE_ENV === 'test') { return; } @@ -290,19 +289,6 @@ module.exports.initErrorRoutes = function (app) { app.use(errorHandler.errorResponse); }; -/** - * Configure Socket.io - */ -/* -module.exports.configureSocketIO = function (app, db) { - // Load the Socket.io configuration - var server = require('./socket.io')(app, db); - - // Return server object - return server; -}; -*/ - /** * Initialize the Express application */ @@ -346,8 +332,5 @@ module.exports.init = function (db) { // Initialize Agenda ("cron" jobs) this.initAgenda(app, db); - // Configure Socket.io - //app = this.configureSocketIO(app, db); - return app; }; diff --git a/gulpfile.js b/gulpfile.js index 749e8854bb..f9c7d52e1c 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -29,7 +29,7 @@ var changedTestFiles = []; var environmentAssets, assets, config; gulp.task('bower', function(done) { - if(argv.skipBower) { + if (argv.skipBower) { plugins.util.log('Bower task skipped.'); return done(); } @@ -53,7 +53,7 @@ gulp.task('env:prod', function() { // Make sure local config file exists gulp.task('copyConfig', function(done) { - if(!fs.existsSync('config/env/local.js') ) { + if (!fs.existsSync('config/env/local.js') ) { gulp .src('config/env/local.sample.js') .pipe(plugins.rename('local.js')) @@ -68,13 +68,13 @@ gulp.task('copyConfig', function(done) { // Load config + assets // Loading config before `env:*` and `copyConfig` tasks would load configs with wrong environment gulp.task('loadConfig', function(done) { - if(!config) { + if (!config) { config = require('./config/config'); } - if(!environmentAssets) { + if (!environmentAssets) { environmentAssets = require('./config/assets/' + process.env.NODE_ENV || 'development') || {}; } - if(!assets) { + if (!assets) { assets = _.extend(defaultAssets, environmentAssets); } done(); @@ -104,17 +104,17 @@ gulp.task('watch', function() { // Add watch rules gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed); - gulp.watch(defaultAssets.server.allJS, ['jshint']).on('change', plugins.livereload.changed); + gulp.watch(defaultAssets.server.allJS, ['eslint']).on('change', plugins.livereload.changed); gulp.watch(defaultAssets.server.fontelloConfig, ['fontello']); gulp.watch(defaultAssets.client.less, ['clean:css', 'styles']); if (process.env.NODE_ENV === 'production') { - gulp.watch(defaultAssets.client.js, ['jshint', 'clean:js', 'scripts']); - gulp.watch(defaultAssets.server.gulpConfig, ['jshint']); + gulp.watch(defaultAssets.client.js, ['eslint', 'clean:js', 'scripts']); + gulp.watch(defaultAssets.server.gulpConfig, ['eslint']); gulp.watch(defaultAssets.client.views, ['clean:js', 'scripts']).on('change', plugins.livereload.changed); } else { - gulp.watch(defaultAssets.client.js, ['jshint']).on('change', plugins.livereload.changed); - gulp.watch(defaultAssets.server.gulpConfig, ['jshint']); + gulp.watch(defaultAssets.client.js, ['eslint']).on('change', plugins.livereload.changed); + gulp.watch(defaultAssets.server.gulpConfig, ['eslint']); gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed); } }); @@ -144,8 +144,8 @@ gulp.task('watch:server:run-tests', function () { }); }); -// JS linting task -gulp.task('jshint', function() { +// ESLint JS linting task +gulp.task('eslint', function() { var assets = _.union( defaultAssets.server.gulpConfig, defaultAssets.server.allJS, @@ -156,9 +156,11 @@ gulp.task('jshint', function() { ); return gulp.src(assets) - .pipe(plugins.jshint()) - .pipe(plugins.jshint.reporter('default')) - .pipe(plugins.jshint.reporter('fail')); + .pipe(plugins.eslint()) + .pipe(plugins.eslint.format()) + // To have the process exit with an error code (1) on + // lint error, return the stream and pipe to failAfterError last. + .pipe(plugins.eslint.failAfterError()); }); // JavaScript task @@ -233,7 +235,7 @@ gulp.task('uibTemplatecache', function() { .pipe(plugins.templateCache('uib-templates-' + uibModule + '.js', { root: 'uib/template/' + uibModule + '/', module: 'core', - templateHeader: '(function(){ \'use strict\'; angular.module(\'<%= module %>\'<%= standalone %>).run(templates); templates.$inject = [\'$templateCache\']; function templates($templateCache) {', + templateHeader: '(function() { \'use strict\'; angular.module(\'<%= module %>\'<%= standalone %>).run(templates); templates.$inject = [\'$templateCache\']; function templates($templateCache) {', templateBody: '$templateCache.put(\'<%= url %>\', \'<%= contents %>\');', templateFooter: '} })();' })); @@ -259,7 +261,7 @@ gulp.task('templatecache', function() { return url.replace('/client', ''); }, module: 'core', - templateHeader: '(function(){ \'use strict\'; angular.module(\'<%= module %>\'<%= standalone %>).run(templates); templates.$inject = [\'$templateCache\']; function templates($templateCache) {', + templateHeader: '(function() { \'use strict\'; angular.module(\'<%= module %>\'<%= standalone %>).run(templates); templates.$inject = [\'$templateCache\']; function templates($templateCache) {', templateBody: '$templateCache.put(\'<%= url %>\', \'<%= contents %>\');', templateFooter: '} })();' })) @@ -343,12 +345,12 @@ gulp.task('karma:watch', function(done) { // Build assets for development mode gulp.task('build:dev', function(done) { - runSequence('env:dev', 'bower', 'jshint', 'clean', ['uibTemplatecache', 'styles'], done); + runSequence('env:dev', 'bower', 'eslint', 'clean', ['uibTemplatecache', 'styles'], done); }); // Build assets for production mode gulp.task('build:prod', function(done) { - runSequence('env:prod', 'bower', 'jshint', 'clean', ['styles', 'scripts'], done); + runSequence('env:prod', 'bower', 'eslint', 'clean', ['styles', 'scripts'], done); }); // Clean dist css and js files @@ -358,11 +360,11 @@ gulp.task('clean', function(done) { // Run the project tests gulp.task('test', function(done) { - runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'jshint', ['karma', 'mocha'], done); + runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'eslint', ['karma', 'mocha'], done); }); gulp.task('test:server', function(done) { - runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'jshint', 'mocha', done); + runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'eslint', 'mocha', done); }); // Watch all server files for changes & run server tests (test:server) task on changes @@ -371,11 +373,11 @@ gulp.task('test:server:watch', function(done) { }); gulp.task('test:client', function(done) { - runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'jshint', 'karma', done); + runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'eslint', 'karma', done); }); gulp.task('test:client:watch', function(done) { - runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'jshint', 'karma:watch', done); + runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'eslint', 'karma:watch', done); }); // Run the project in development mode diff --git a/modules/contacts/client/config/contacts.client.routes.js b/modules/contacts/client/config/contacts.client.routes.js index 23fb54478c..778c657553 100644 --- a/modules/contacts/client/config/contacts.client.routes.js +++ b/modules/contacts/client/config/contacts.client.routes.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; angular @@ -54,4 +54,4 @@ } -})(); +}()); diff --git a/modules/contacts/client/controllers/add-contact.client.controller.js b/modules/contacts/client/controllers/add-contact.client.controller.js index 3b4bdf9d2b..eb9a47d5ae 100644 --- a/modules/contacts/client/controllers/add-contact.client.controller.js +++ b/modules/contacts/client/controllers/add-contact.client.controller.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; angular @@ -32,7 +32,7 @@ function init() { // Prevent connecting with yourself - if($stateParams.userId === Authentication.user._id) { + if ($stateParams.userId === Authentication.user._id) { vm.isConnected = true; vm.error = 'You cannot connect with yourself. That is just silly!'; } @@ -50,7 +50,7 @@ // If contact already exists, stop here existingContact.$promise.then(function(response) { - if(response) { + if (response) { vm.isConnected = true; vm.success = (response.confirmed) ? 'You two are already connected. Great!' : 'Connection already initiated; now it has to be confirmed.'; } @@ -80,4 +80,4 @@ } -})(); +}()); diff --git a/modules/contacts/client/controllers/confirm-contact.client.controller.js b/modules/contacts/client/controllers/confirm-contact.client.controller.js index 2641276928..76017480aa 100644 --- a/modules/contacts/client/controllers/confirm-contact.client.controller.js +++ b/modules/contacts/client/controllers/confirm-contact.client.controller.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; angular @@ -26,12 +26,10 @@ // Got contact function(contact) { vm.isLoading = false; - if(vm.contact.confirmed === true) { + if (vm.contact.confirmed === true) { vm.isConnected = true; vm.success = 'You two are already connected. Great!'; - } - // [0] contains contact requester's id, [1] is the receiver - else if (vm.contact.users[0]._id !== Authentication.user._id) { + } else if (vm.contact.users[0]._id !== Authentication.user._id) { // [0] contains contact requester's id, [1] is the receiver vm.error = 'You must wait until he/she confirms your connection.'; } }, @@ -57,4 +55,4 @@ } -})(); +}()); diff --git a/modules/contacts/client/controllers/list-contacts.client.controller.js b/modules/contacts/client/controllers/list-contacts.client.controller.js index d86b60051b..53dce0d885 100644 --- a/modules/contacts/client/controllers/list-contacts.client.controller.js +++ b/modules/contacts/client/controllers/list-contacts.client.controller.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; angular @@ -41,11 +41,9 @@ if (value === 'displayName') { return other.displayName; - } - else if (value === 'username') { + } else if (value === 'username') { return other.username; - } - else { + } else { // User object return other; } @@ -53,4 +51,4 @@ } -})(); +}()); diff --git a/modules/contacts/client/controllers/remove-contact.client.controller.js b/modules/contacts/client/controllers/remove-contact.client.controller.js index aa75a6bd72..d8737dca59 100644 --- a/modules/contacts/client/controllers/remove-contact.client.controller.js +++ b/modules/contacts/client/controllers/remove-contact.client.controller.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; angular @@ -10,7 +10,10 @@ var contactToRemove = $scope.contactToRemove; + // ViewModel var vm = this; + + // Exposed to the view vm.isLoading = false; vm.contact = contactToRemove; vm.removeContact = removeContact; @@ -18,20 +21,18 @@ // Different confirm button label and modal title depending on situation - // User is cancelling a request - if(angular.isDefined(contactToRemove.confirmed) && contactToRemove.confirmed === false && Authentication.user._id === contactToRemove.users[1]._id) { + if (angular.isDefined(contactToRemove.confirmed) && contactToRemove.confirmed === false && Authentication.user._id === contactToRemove.users[1]._id) { + // User is cancelling a request vm.labelConfirm = 'Yes, revoke request'; vm.labelTitle = 'Revoke contact request?'; vm.labelTime = 'Requested'; - } - // Decline received request - else if(angular.isDefined(contactToRemove.confirmed) && contactToRemove.confirmed === false) { + } else if (angular.isDefined(contactToRemove.confirmed) && contactToRemove.confirmed === false) { + // Decline received request vm.labelConfirm = 'Yes, decline request'; vm.labelTitle = 'Decline contact request?'; vm.labelTime = 'Requested'; - } - // Removing confirmed contact - else { + } else { + // Removing confirmed contact vm.labelConfirm = 'Yes, remove contact'; vm.labelTitle = 'Remove contact?'; vm.labelTime = 'Connected since'; @@ -41,7 +42,7 @@ vm.isLoading = true; // contact comes from the parent link() - Contact.delete({contactId: contactToRemove._id}, + Contact.delete({ contactId: contactToRemove._id }, // Success function() { @@ -66,4 +67,4 @@ } -})(); +}()); diff --git a/modules/contacts/client/directives/tr-contact-remove.client.directive.js b/modules/contacts/client/directives/tr-contact-remove.client.directive.js index a01f3fb04c..cf1241ad50 100644 --- a/modules/contacts/client/directives/tr-contact-remove.client.directive.js +++ b/modules/contacts/client/directives/tr-contact-remove.client.directive.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; /** @@ -32,4 +32,5 @@ } }; } -})(); + +}()); diff --git a/modules/contacts/client/services/contact-by.client.service.js b/modules/contacts/client/services/contact-by.client.service.js index 7590ff9439..db8bc4c111 100644 --- a/modules/contacts/client/services/contact-by.client.service.js +++ b/modules/contacts/client/services/contact-by.client.service.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; // ContactBy factory used for communicating with the contacts REST endpoints @@ -18,4 +18,4 @@ }); } -})(); +}()); diff --git a/modules/contacts/client/services/contact.client.service.js b/modules/contacts/client/services/contact.client.service.js index e6e10c8634..4bcc198ff2 100644 --- a/modules/contacts/client/services/contact.client.service.js +++ b/modules/contacts/client/services/contact.client.service.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; // Contact factory used for communicating with the contacts REST endpoints @@ -24,4 +24,4 @@ }); } -})(); +}()); diff --git a/modules/contacts/client/services/contacts-list.client.service.js b/modules/contacts/client/services/contacts-list.client.service.js index 9e5f74d6a4..021b45b995 100644 --- a/modules/contacts/client/services/contacts-list.client.service.js +++ b/modules/contacts/client/services/contacts-list.client.service.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; // ContactsList factory used for communicating with the contacts REST endpoints @@ -14,4 +14,4 @@ }); } -})(); +}()); diff --git a/modules/contacts/server/controllers/contacts.server.controller.js b/modules/contacts/server/controllers/contacts.server.controller.js index 87428e5f1c..9e5da8fe1f 100644 --- a/modules/contacts/server/controllers/contacts.server.controller.js +++ b/modules/contacts/server/controllers/contacts.server.controller.js @@ -42,7 +42,7 @@ exports.add = function(req, res) { function(done) { // Not a valid ObjectId - if(!mongoose.Types.ObjectId.isValid(req.body.friendUserId)) { + if (!mongoose.Types.ObjectId.isValid(req.body.friendUserId)) { return res.status(400).json({ message: errorHandler.getErrorMessageByKey('invalid-id') }); @@ -51,8 +51,8 @@ exports.add = function(req, res) { // Check if contact already exists Contact.findOne({ $or: [ - { users: [ req.body.friendUserId, req.user._id ] }, - { users: [ req.user._id, req.body.friendUserId ] } + { users: [req.body.friendUserId, req.user._id] }, + { users: [req.user._id, req.body.friendUserId] } ] }).exec(function(err, existingContact) { if (err) return done(err); @@ -75,9 +75,9 @@ exports.add = function(req, res) { // Catch message separately var messageHTML = false; var messagePlain = false; - if(req.body.message && req.body.message !== '') { + if (req.body.message && req.body.message !== '') { messageHTML = sanitizeHtml(req.body.message, textProcessor.sanitizeOptions); - messagePlain = htmlToText.fromString(req.body.message, {wordwrap: 80}); + messagePlain = htmlToText.fromString(req.body.message, { wordwrap: 80 }); } delete req.body.message; @@ -123,28 +123,28 @@ exports.add = function(req, res) { urlConfirm = url + '/contact-confirm/' + contact._id; var renderVars = emailsHandler.addEmailBaseTemplateParams( - req.headers.host, - { - name: friend.displayName, - message: messageHTML, - meName: req.user.displayName, - meURLPlainText: meURL, - meURL: analyticsHandler.appendUTMParams(meURL, { - source: 'transactional-email', - medium: 'email', - campaign: 'confirm-contact', - content: 'profile' - }), - urlConfirmPlainText: urlConfirm, - urlConfirm: analyticsHandler.appendUTMParams(urlConfirm, { - source: 'transactional-email', - medium: 'email', - campaign: 'confirm-contact', - content: 'confirm-contact' - }) - }, - 'confirm-contact' - ); + req.headers.host, + { + name: friend.displayName, + message: messageHTML, + meName: req.user.displayName, + meURLPlainText: meURL, + meURL: analyticsHandler.appendUTMParams(meURL, { + source: 'transactional-email', + medium: 'email', + campaign: 'confirm-contact', + content: 'profile' + }), + urlConfirmPlainText: urlConfirm, + urlConfirm: analyticsHandler.appendUTMParams(urlConfirm, { + source: 'transactional-email', + medium: 'email', + campaign: 'confirm-contact', + content: 'confirm-contact' + }) + }, + 'confirm-contact' + ); res.render(path.resolve('./modules/core/server/views/email-templates/confirm-contact'), renderVars, function(err, emailHTML) { done(err, emailHTML, messagePlain, friend, renderVars); @@ -189,7 +189,7 @@ exports.add = function(req, res) { ], function(err) { if (err) { if (contact) { - contact.remove(function(){ + contact.remove(function() { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); @@ -209,17 +209,17 @@ exports.add = function(req, res) { * Disconnect contact */ exports.remove = function(req, res) { - var contact = req.contact; - - contact.remove(function(err) { - if (err) { - return res.status(400).send({ - message: errorHandler.getErrorMessage(err) - }); - } else { - res.json(contact); - } - }); + var contact = req.contact; + + contact.remove(function(err) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.json(contact); + } + }); }; @@ -229,7 +229,7 @@ exports.remove = function(req, res) { exports.confirm = function(req, res) { // Only receiving user can confirm user connections - if(!req.contact || !req.contact.users[0]._id.equals(req.user._id.valueOf())) { + if (!req.contact || !req.contact.users[0]._id.equals(req.user._id.valueOf())) { return res.status(403).json({ message: errorHandler.getErrorMessageByKey('forbidden') }); @@ -237,17 +237,17 @@ exports.confirm = function(req, res) { // Ta'da! var contact = req.contact; - contact.confirmed = true; - - contact.save(function(err) { - if(err) { - return res.status(400).send({ - message: errorHandler.getErrorMessage(err) - }); - } else { - res.json(contact); - } - }); + contact.confirmed = true; + + contact.save(function(err) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.json(contact); + } + }); }; /** @@ -261,7 +261,7 @@ exports.list = function(req, res) { * Single contact */ exports.get = function(req, res) { - res.json(req.contact || {}); + res.json(req.contact || {}); }; /** @@ -272,31 +272,31 @@ exports.get = function(req, res) { exports.contactByUserId = function(req, res, next, userId) { // Not a valid ObjectId - if(!mongoose.Types.ObjectId.isValid(userId)) { + if (!mongoose.Types.ObjectId.isValid(userId)) { return res.status(400).json({ message: errorHandler.getErrorMessageByKey('invalid-id') }); } // User's own profile, don't bother hitting the DB - if(req.user && req.user._id === userId) { + if (req.user && req.user._id === userId) { return res.status(400).json({ message: errorHandler.getErrorMessageByKey('invalid-id') }); } - if(req.user && req.user.public) { + if (req.user && req.user.public) { Contact.findOne({ $or: [ - { users: [ userId, req.user._id ] }, - { users: [ req.user._id, userId ] } + { users: [userId, req.user._id] }, + { users: [req.user._id, userId] } ] }) .populate('users', userHandler.userMiniProfileFields) .exec(function(err, contact) { - if(err) return next(err); - if(!contact) { + if (err) return next(err); + if (!contact) { return res.status(404).json({ message: errorHandler.getErrorMessageByKey('not-found') }); @@ -305,8 +305,7 @@ exports.contactByUserId = function(req, res, next, userId) { req.contact = contact; next(); }); - } - else { + } else { next(); } }; @@ -318,7 +317,7 @@ exports.contactByUserId = function(req, res, next, userId) { exports.contactById = function(req, res, next, contactId) { // Not a valid ObjectId - if(!mongoose.Types.ObjectId.isValid(contactId)) { + if (!mongoose.Types.ObjectId.isValid(contactId)) { return res.status(400).json({ message: errorHandler.getErrorMessageByKey('invalid-id') }); @@ -331,7 +330,7 @@ exports.contactById = function(req, res, next, contactId) { if (err) return next(err); // If nothing was found or neither of the user ID's match currently authenticated user's id, return 404 - if(!contact || !req.user || ( + if (!contact || !req.user || ( !contact.users[0]._id.equals(req.user._id.valueOf()) && !contact.users[1]._id.equals(req.user._id.valueOf()) )) { @@ -354,7 +353,7 @@ exports.contactById = function(req, res, next, contactId) { exports.contactListByUser = function(req, res, next, listUserId) { // Not a valid ObjectId - if(!mongoose.Types.ObjectId.isValid(listUserId)) { + if (!mongoose.Types.ObjectId.isValid(listUserId)) { return res.status(400).json({ message: errorHandler.getErrorMessageByKey('invalid-id') }); @@ -363,7 +362,7 @@ exports.contactListByUser = function(req, res, next, listUserId) { var contactQuery = { users: listUserId, confirmed: true }; // Remove 'confirmed=true' from queries if showing currently logged in user's listing - if(req.user && req.user._id.equals(listUserId)) { + if (req.user && req.user._id.equals(listUserId)) { delete contactQuery.confirmed; } @@ -373,12 +372,12 @@ exports.contactListByUser = function(req, res, next, listUserId) { .populate({ path: 'users', // ...except don't populate user's own info for confirmed contacts. We don't need it dozen times there: - //match: { _id: { $ne: listUserId } }, + // match: { _id: { $ne: listUserId } }, select: userHandler.userMiniProfileFields }) .exec(function(err, contacts) { - if(err) return next(err); - if(!contacts) return next(new Error('Failed to load contacts.')); + if (err) return next(err); + if (!contacts) return next(new Error('Failed to load contacts.')); req.contacts = contacts; next(); diff --git a/modules/contacts/server/policies/contacts.server.policy.js b/modules/contacts/server/policies/contacts.server.policy.js index 2113b41f7e..486bf25f9d 100644 --- a/modules/contacts/server/policies/contacts.server.policy.js +++ b/modules/contacts/server/policies/contacts.server.policy.js @@ -54,7 +54,7 @@ exports.invokeRolesPolicies = function() { exports.isAllowed = function(req, res, next) { // No contacts for un-published users - if(req.user && req.user.public !== true) { + if (req.user && req.user.public !== true) { return res.status(403).json({ message: errorHandler.getErrorMessageByKey('forbidden') }); @@ -62,7 +62,7 @@ exports.isAllowed = function(req, res, next) { // If an contact is being processed and the current user owns it, then allow any manipulation // 'Delete' gets allowed here - if(req.contact && req.user && + if (req.contact && req.user && ( req.contact.users[0]._id.equals(req.user._id.valueOf()) || req.contact.users[1]._id.equals(req.user._id.valueOf()) diff --git a/modules/contacts/server/routes/contacts.server.routes.js b/modules/contacts/server/routes/contacts.server.routes.js index 240d9a4be3..fe1c8b68cc 100644 --- a/modules/contacts/server/routes/contacts.server.routes.js +++ b/modules/contacts/server/routes/contacts.server.routes.js @@ -12,12 +12,12 @@ module.exports = function(app) { .post(contacts.add); app.route('/api/contact-by/:contactUserId').all(contactsPolicy.isAllowed) - .get(contacts.get); //contacts.hasAuthorization, + .get(contacts.get); app.route('/api/contact/:contactId').all(contactsPolicy.isAllowed) - .get(contacts.get) //contacts.hasAuthorization, - .put(contacts.confirm) //contacts.receiverHasAuthorization, - .delete(contacts.remove); //contacts.hasAuthorization, + .get(contacts.get) + .put(contacts.confirm) + .delete(contacts.remove); // Contact list app.route('/api/contacts/:listUserId').all(contactsPolicy.isAllowed) diff --git a/modules/contacts/tests/client/add-contact.client.controller.tests.js b/modules/contacts/tests/client/add-contact.client.controller.tests.js index b0cda8f7c3..a4ddc3f593 100644 --- a/modules/contacts/tests/client/add-contact.client.controller.tests.js +++ b/modules/contacts/tests/client/add-contact.client.controller.tests.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; describe('ContactAddController', function() { @@ -28,7 +28,7 @@ // Load the main application module beforeEach(module(AppConfig.appModuleName)); - beforeEach(inject(function($templateCache, _$httpBackend_, _Authentication_, _UsersMini_, _ContactByService_){ + beforeEach(inject(function($templateCache, _$httpBackend_, _Authentication_, _UsersMini_, _ContactByService_) { $httpBackend = _$httpBackend_; Authentication = _Authentication_; UsersMini = _UsersMini_; @@ -37,15 +37,15 @@ $templateCache.put('/modules/core/views/404.client.view.html', ''); })); - afterEach(function(){ + afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); - describe('logged in', function(){ + describe('logged in', function() { - beforeEach(function(done){ - inject(function($controller){ + beforeEach(function(done) { + inject(function($controller) { Authentication.user = user1; @@ -60,66 +60,66 @@ }); }); - describe('when user does not exist', function(){ + describe('when user does not exist', function() { - beforeEach(function(){ + beforeEach(function() { $httpBackend.expect('GET', '/api/users/mini/user2').respond(404); $httpBackend.expect('GET', '/api/contact-by/user2').respond(404); }); - it('displays an error message', function(){ + it('displays an error message', function() { $httpBackend.flush(); expect(ContactAddController.error).toBe('User does not exist.'); }); }); - describe('when user exists', function(){ + describe('when user exists', function() { - beforeEach(function(){ + beforeEach(function() { $httpBackend.expect('GET', '/api/users/mini/user2').respond(200, user2); }); - describe('when unconfirmed contact exists', function(){ + describe('when unconfirmed contact exists', function() { - beforeEach(function(){ + beforeEach(function() { $httpBackend.expect('GET', '/api/contact-by/user2').respond(200, { confirmed: false }); }); - it('displays a success message', function(){ + it('displays a success message', function() { $httpBackend.flush(); expect(ContactAddController.success).toBe('Connection already initiated; now it has to be confirmed.'); }); }); - describe('when confirmed contact exists', function(){ + describe('when confirmed contact exists', function() { - beforeEach(function(){ + beforeEach(function() { $httpBackend.expect('GET', '/api/contact-by/user2').respond(200, { confirmed: true }); }); - it('Shows a nice message when the contact is confirmed', function(){ + it('Shows a nice message when the contact is confirmed', function() { $httpBackend.flush(); expect(ContactAddController.success).toBe('You two are already connected. Great!'); }); }); - describe('when no contact exists', function(){ + describe('when no contact exists', function() { - beforeEach(function(){ + beforeEach(function() { $httpBackend.expect('GET', '/api/contact-by/user2').respond(404); }); - it('will make contact request', function(){ + it('will make contact request', function() { $httpBackend.expect('POST', '/api/contact', contactRequest).respond(200); ContactAddController.add(); $httpBackend.flush(); expect(ContactAddController.success).toBe('Done! We sent an email to your contact and he/she still needs to confirm it.'); }); - it('will make contact request with custom message', function(){ + it('will make contact request with custom message', function() { var customMessage = 'my custom message'; ContactAddController.contact.message = customMessage; $httpBackend.expect('POST', '/api/contact', { friendUserId: user2._id, message: customMessage }).respond(200); @@ -129,13 +129,13 @@ }); - describe('when unconfirmed contact conflict', function(){ + describe('when unconfirmed contact conflict', function() { - beforeEach(function(){ + beforeEach(function() { $httpBackend.expect('POST', '/api/contact', contactRequest).respond(409, { confirmed: false }); }); - it('displays a confirmation waiting success message', function(){ + it('displays a confirmation waiting success message', function() { ContactAddController.add(); $httpBackend.flush(); expect(ContactAddController.success).toBe('Connection already initiated; now it has to be confirmed.'); @@ -143,13 +143,13 @@ }); - describe('with confirmed contact conflict', function(){ + describe('with confirmed contact conflict', function() { - beforeEach(function(){ + beforeEach(function() { $httpBackend.expect('POST', '/api/contact', contactRequest).respond(409, { confirmed: true }); }); - it('displays an already connected success message', function(){ + it('displays an already connected success message', function() { ContactAddController.add(); $httpBackend.flush(); expect(ContactAddController.success).toBe('You two are already connected. Great!'); @@ -164,4 +164,5 @@ }); }); + }()); diff --git a/modules/contacts/tests/client/contacts.client.routes.tests.js b/modules/contacts/tests/client/contacts.client.routes.tests.js index 851fd7b864..d340c181ca 100644 --- a/modules/contacts/tests/client/contacts.client.routes.tests.js +++ b/modules/contacts/tests/client/contacts.client.routes.tests.js @@ -52,7 +52,7 @@ $httpBackend.when('GET', '/api/users/mini/123').respond(200, ''); $httpBackend.expectGET('/api/users/mini/123'); - $state.go('contactAdd', { userId: '123'}); + $state.go('contactAdd', { userId: '123' }); $rootScope.$digest(); })); @@ -96,7 +96,7 @@ $httpBackend.when('GET', '/api/contact/123').respond(200, ''); $httpBackend.expectGET('/api/contact/123'); - $state.go('contactConfirm', { contactId: '123'}); + $state.go('contactConfirm', { contactId: '123' }); $rootScope.$digest(); })); @@ -112,4 +112,5 @@ }); -})(); + +}()); diff --git a/modules/contacts/tests/client/remove-contact.client.controller.tests.js b/modules/contacts/tests/client/remove-contact.client.controller.tests.js index 5d54556b55..82341f9d5b 100644 --- a/modules/contacts/tests/client/remove-contact.client.controller.tests.js +++ b/modules/contacts/tests/client/remove-contact.client.controller.tests.js @@ -24,7 +24,7 @@ // Load the main application module beforeEach(module(AppConfig.appModuleName)); - beforeEach(inject(function($templateCache, _$httpBackend_, _Authentication_, _$rootScope_, _messageCenterService_){ + beforeEach(inject(function($templateCache, _$httpBackend_, _Authentication_, _$rootScope_, _messageCenterService_) { $httpBackend = _$httpBackend_; Authentication = _Authentication_; @@ -42,15 +42,15 @@ $templateCache.put('/modules/pages/views/home.client.view.html', ''); })); - afterEach(function(){ + afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); - describe('logged in', function(){ + describe('logged in', function() { - beforeEach(function(done){ - inject(function($controller){ + beforeEach(function(done) { + inject(function($controller) { Authentication.user = user1; ContactRemoveController = $controller('ContactRemoveController', { $scope: $scope, diff --git a/modules/contacts/tests/server/contact.server.model.tests.js b/modules/contacts/tests/server/contact.server.model.tests.js index 4488e07716..0c68ddeaf4 100644 --- a/modules/contacts/tests/server/contact.server.model.tests.js +++ b/modules/contacts/tests/server/contact.server.model.tests.js @@ -11,7 +11,11 @@ var should = require('should'), /** * Globals */ -var user1, user2, user1Id, user2Id, contact; +var user1, + user2, + user1Id, + user2Id, + contact; /** * Unit tests diff --git a/modules/contacts/tests/server/contact.server.routes.tests.js b/modules/contacts/tests/server/contact.server.routes.tests.js index b6d6eef768..ad27618e85 100644 --- a/modules/contacts/tests/server/contact.server.routes.tests.js +++ b/modules/contacts/tests/server/contact.server.routes.tests.js @@ -14,11 +14,23 @@ var should = require('should'), /** * Globals */ -var app, agent, credentials, - user1, user2, user3, user4, - user1Id, user2Id, user3Id, user4Id, - contact1, contact2, contact3, - contact1Id, contact2Id, contact3Id; +var app, + agent, + credentials, + user1, + user2, + user3, + user4, + user1Id, + user2Id, + user3Id, + user4Id, + contact1, + contact2, + contact3, + contact1Id, + contact2Id, + contact3Id; /** * Contact routes tests @@ -178,9 +190,9 @@ describe('Contact CRUD tests', function() { }); }); - context('logged in', function(){ + context('logged in', function() { - beforeEach(function(done){ + beforeEach(function(done) { agent.post('/api/auth/signin') .send(credentials) // = user 1 @@ -191,11 +203,11 @@ describe('Contact CRUD tests', function() { }); - it('should be able to get a contact by user id', function(done){ + it('should be able to get a contact by user id', function(done) { // Get the contact for User1 -> User2 : Contact1 agent.get('/api/contact-by/' + user2Id) .expect(200) - .end(function(contactByErr, contactByRes){ + .end(function(contactByErr, contactByRes) { // Handle contact by error if (contactByErr) return done(contactByErr); @@ -270,12 +282,12 @@ describe('Contact CRUD tests', function() { }); }); - it('should be able to create a new unconfirmed contact', function(done){ + it('should be able to create a new unconfirmed contact', function(done) { // Create a contact User1 -> User4 agent.post('/api/contact') .send({ friendUserId: user4Id }) .expect(200) - .end(function(contactAddErr, contactAddRes){ + .end(function(contactAddErr, contactAddRes) { // Handle contact add error if (contactAddErr) return done(contactAddErr); @@ -284,7 +296,7 @@ describe('Contact CRUD tests', function() { // Get the contact for User4 that we just created agent.get('/api/contact-by/' + user4Id) .expect(200) - .end(function(contactByErr, contactByRes){ + .end(function(contactByErr, contactByRes) { // Handle contact by error if (contactByErr) return done(contactByErr); @@ -304,23 +316,23 @@ describe('Contact CRUD tests', function() { }); }); - it('should not be able to create a duplicate contact', function(done){ + it('should not be able to create a duplicate contact', function(done) { // Try and create a contact User1 -> User2 agent.post('/api/contact') .send({ friendUserId: user2Id }) .expect(409) - .end(function(contactAddErr, contactAddRes){ + .end(function(contactAddErr, contactAddRes) { // Handle contact add error if (contactAddErr) return done(contactAddErr); return done(); }); }); - it('should be able to confirm a contact', function(done){ + it('should be able to confirm a contact', function(done) { // Confirm the un-confirmed Contact1 between User1 -> User2 agent.put('/api/contact/' + contact1Id) .expect(200) - .end(function(contactConfirmErr, contactConfirmRes){ + .end(function(contactConfirmErr, contactConfirmRes) { // Handle contact confirm error if (contactConfirmErr) return done(contactConfirmErr); @@ -348,7 +360,7 @@ describe('Contact CRUD tests', function() { // The contact should be gone now agent.get('/api/contact-by/' + user2Id) .expect(404) - .end(function(contactByErr, contactByRes){ + .end(function(contactByErr, contactByRes) { // Handle contact by error if (contactByErr) return done(contactByErr); @@ -361,11 +373,11 @@ describe('Contact CRUD tests', function() { }); }); - context('with email sending error', function(){ + context('with email sending error', function() { var originalMailerOptions; - beforeEach(function(){ + beforeEach(function() { // Set the mail sending to fail originalMailerOptions = config.mailer.options; config.mailer.options = stubTransport({ @@ -373,16 +385,16 @@ describe('Contact CRUD tests', function() { }); }); - afterEach(function(){ + afterEach(function() { config.mailer.options = originalMailerOptions; }); - it('should fail to create contact', function(done){ + it('should fail to create contact', function(done) { // Try and create a contact User1 -> User4 agent.post('/api/contact') .send({ friendUserId: user4Id }) .expect(400) - .end(function(contactAddErr, contactAddRes){ + .end(function(contactAddErr, contactAddRes) { // Handle contact add error if (contactAddErr) return done(contactAddErr); diff --git a/modules/core/client/app/config.js b/modules/core/client/app/config.js index 9e2f983e84..133a4043ec 100644 --- a/modules/core/client/app/config.js +++ b/modules/core/client/app/config.js @@ -1,49 +1,50 @@ 'use strict'; // Init the application configuration module for AngularJS application -var AppConfig = (function() { +var AppConfig = (function () { // Init module configuration options var appEnv = window.env || 'production'; var appModuleName = 'trustroots'; var appModuleVendorDependencies = [ - 'ngResource', - 'ngAnimate', - 'ngTouch', - 'ngSanitize', - 'ngMessageFormat', - 'angulartics', - 'ui.router', - 'ui.bootstrap.dateparser', - 'ui.bootstrap.buttons', - 'ui.bootstrap.collapse', - 'ui.bootstrap.dropdown', - 'ui.bootstrap.modal', - 'ui.bootstrap.popover', - 'ui.bootstrap.progressbar', - 'ui.bootstrap.tabs', - 'ui.bootstrap.tooltip', - 'ui.bootstrap.typeahead', - 'angularMoment', - 'nemLogging', - 'ui-leaflet', - 'ngFileUpload', - 'zumba.angular-waypoints', - 'MessageCenterModule', - 'localytics.directives', - 'angular-loading-bar', - 'trTrustpass', - 'angular-mailcheck', - 'angular-locker', - 'angular-confirm', - 'angularGrid' - ]; + 'ngResource', + 'ngAnimate', + 'ngTouch', + 'ngSanitize', + 'ngMessageFormat', + 'angulartics', + 'ui.router', + 'ui.bootstrap.dateparser', + 'ui.bootstrap.buttons', + 'ui.bootstrap.collapse', + 'ui.bootstrap.dropdown', + 'ui.bootstrap.modal', + 'ui.bootstrap.popover', + 'ui.bootstrap.progressbar', + 'ui.bootstrap.tabs', + 'ui.bootstrap.tooltip', + 'ui.bootstrap.typeahead', + 'angularMoment', + 'nemLogging', + 'ui-leaflet', + 'ngFileUpload', + 'zumba.angular-waypoints', + 'MessageCenterModule', + 'localytics.directives', + 'angular-loading-bar', + 'trTrustpass', + 'angular-mailcheck', + 'angular-locker', + 'angular-confirm', + 'angularGrid' + ]; - // Load different service dependency for Angulartics depending on environment - // @link https://github.com/angulartics/angulartics - if(appEnv === 'production') { + /** + * Load different service dependency for Angulartics depending on environment + * @link https://github.com/angulartics/angulartics + */ + if (appEnv === 'production') { appModuleVendorDependencies.push('angulartics.google.analytics'); - } - else { + } else { appModuleVendorDependencies.push('angulartics.debug'); } @@ -62,4 +63,4 @@ var AppConfig = (function() { appModuleVendorDependencies: appModuleVendorDependencies, registerModule: registerModule }; -})(); +}()); diff --git a/modules/core/client/app/init.js b/modules/core/client/app/init.js index b4b819e28e..525fae3d5f 100644 --- a/modules/core/client/app/init.js +++ b/modules/core/client/app/init.js @@ -1,5 +1,5 @@ -(function() { - 'use strict'; +(function () { + 'use strict'; // Start by defining the main module and adding the module dependencies angular @@ -41,11 +41,11 @@ }); // Default timeout for success, error etc messages - $messageCenterServiceProvider.setGlobalOptions({timeout: 6000}); + $messageCenterServiceProvider.setGlobalOptions({ timeout: 6000 }); // Disabling Debug Data for production environment // @link https://docs.angularjs.org/guide/production - if(AppConfig.appEnv === 'production') { + if (AppConfig.appEnv === 'production') { $compileProvider.debugInfoEnabled(false); } @@ -64,4 +64,4 @@ }); }); -})(); +}()); diff --git a/modules/core/client/config/core.client.routes.js b/modules/core/client/config/core.client.routes.js index 8f93639e3b..1e21e9887d 100644 --- a/modules/core/client/config/core.client.routes.js +++ b/modules/core/client/config/core.client.routes.js @@ -1,4 +1,4 @@ -(function() { +(function () { 'use strict'; angular @@ -35,4 +35,4 @@ }); } -})(); +}()); diff --git a/modules/core/client/controllers/app.client.controller.js b/modules/core/client/controllers/app.client.controller.js index b2c2907de5..49f55f4b48 100644 --- a/modules/core/client/controllers/app.client.controller.js +++ b/modules/core/client/controllers/app.client.controller.js @@ -1,4 +1,4 @@ -(function(){ +(function() { 'use strict'; /** @@ -50,24 +50,24 @@ autoLink: false, // automatically turns URLs entered into the text field into HTML anchor tags toolbar: { buttons: [{ - name: 'bold', - contentDefault: '' - }, { - name: 'italic', - contentDefault: '' - }, { - name: 'underline', - contentDefault: '' - }, { - name: 'anchor', - contentDefault: '' - }, { - name: 'quote', - contentDefault: '' - }, { - name: 'unorderedlist', - contentDefault: '' - }] + name: 'bold', + contentDefault: '' + }, { + name: 'italic', + contentDefault: '' + }, { + name: 'underline', + contentDefault: '' + }, { + name: 'anchor', + contentDefault: '' + }, { + name: 'quote', + contentDefault: '' + }, { + name: 'unorderedlist', + contentDefault: '' + }] } }; @@ -91,7 +91,7 @@ $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { // Redirect to login page if no user - if(toState.requiresAuth && !Authentication.user) { + if (toState.requiresAuth && !Authentication.user) { // Cancel stateChange event.preventDefault(); @@ -102,15 +102,13 @@ // Show a special signup ad for certain pages if user isn't authenticated // (Normally we just splash a signup page at this point) - if(toState.name === 'profile') { + if (toState.name === 'profile') { $state.go('profile-signup'); - } - else if(toState.name === 'search') { + } else if (toState.name === 'search') { $state.go('search-signin', toParams || {}); - } - // Or just continue to the signup page - else { - $state.go('signin', {'continue': true}); + } else { + // Or just continue to the signup page... + $state.go('signin', { 'continue': true }); } } @@ -130,7 +128,7 @@ vm.photoCreditsCount = 0; // Reset page scroll on page change - $window.scrollTo(0,0); + $window.scrollTo(0, 0); }); /** @@ -147,10 +145,9 @@ * Determine where to direct user from "home" links */ function goHome() { - if(Authentication.user) { + if (Authentication.user) { $state.go('search'); - } - else { + } else { $state.go('home'); } } @@ -159,7 +156,7 @@ * Sign out authenticated user */ function signout($event) { - if($event) { + if ($event) { $event.preventDefault(); } @@ -173,10 +170,10 @@ locker.clean(); // Do the signout and refresh the page - $window.top.location.href = '/api/auth/signout'; + $window.top.location.href = '/api/auth/signout'; } } -})(); +}()); diff --git a/modules/core/client/controllers/footer.client.controller.js b/modules/core/client/controllers/footer.client.controller.js index ce9afcaf57..d17f7b1fbe 100644 --- a/modules/core/client/controllers/footer.client.controller.js +++ b/modules/core/client/controllers/footer.client.controller.js @@ -1,4 +1,4 @@ -(function(){ +(function () { 'use strict'; angular @@ -19,14 +19,14 @@ $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { // Footer is transparent on these pages - vm.isTransparent = (angular.isDefined(toState.footerTransparent) && toState.footerTransparent === true) ? true : false; + vm.isTransparent = (angular.isDefined(toState.footerTransparent) && toState.footerTransparent === true); // Footer is hidden on these pages - vm.isHidden = (angular.isDefined(toState.footerHidden) && toState.footerHidden === true) ? true : false; + vm.isHidden = (angular.isDefined(toState.footerHidden) && toState.footerHidden === true); }); } -})(); +}()); diff --git a/modules/core/client/controllers/header.client.controller.js b/modules/core/client/controllers/header.client.controller.js index 7de6399d73..6442674826 100644 --- a/modules/core/client/controllers/header.client.controller.js +++ b/modules/core/client/controllers/header.client.controller.js @@ -1,4 +1,4 @@ -(function(){ +(function () { 'use strict'; angular @@ -32,10 +32,10 @@ vm.isCollapsed = false; // Hide header at certain pages - vm.isHidden = (angular.isDefined(toState.headerHidden) && toState.headerHidden === true) ? true : false; + vm.isHidden = (angular.isDefined(toState.headerHidden) && toState.headerHidden === true); }); } } -})(); +}()); diff --git a/modules/core/client/directives/tr-board-credits.client.directive.js b/modules/core/client/directives/tr-board-credits.client.directive.js index 088c04b010..6f5f6d602e 100644 --- a/modules/core/client/directives/tr-board-credits.client.directive.js +++ b/modules/core/client/directives/tr-board-credits.client.directive.js @@ -1,4 +1,4 @@ -(function(){ +(function () { 'use strict'; /** @@ -14,16 +14,16 @@ replace: true, template: '' + - 'Photo by' + - 'Photos by' + - ' ' + - '' + - ' ()' + - ', ' + - '' + + ' Photo by' + + ' Photos by' + + ' ' + + ' ' + + ' ()' + + ' , ' + + ' ' + '', restrict: 'A' }; } -})(); +}()); diff --git a/modules/core/client/directives/tr-boards.client.directive.js b/modules/core/client/directives/tr-boards.client.directive.js index 7aff48ed9b..df231aa6ec 100644 --- a/modules/core/client/directives/tr-boards.client.directive.js +++ b/modules/core/client/directives/tr-boards.client.directive.js @@ -1,4 +1,4 @@ -(function(){ +(function () { 'use strict'; /** @@ -36,14 +36,14 @@ 'file': 'flickr-bokeh.jpg' }, 'forestpath': { - 'name': 'Johnson', //Johnson Cameraface + 'name': 'Johnson', // Johnson Cameraface 'url': 'https://www.flickr.com/photos/54459164@N00/15506455245', 'license': 'CC', 'license_url': 'https://creativecommons.org/licenses/by-nc-sa/2.0/', 'file': 'flickr-forestpath.jpg' }, 'forestpath-toned': { - 'name': 'Johnson', //Johnson Cameraface + 'name': 'Johnson', // Johnson Cameraface 'url': 'https://www.flickr.com/photos/54459164@N00/15506455245', 'license': 'CC', 'license_url': 'https://creativecommons.org/licenses/by-nc-sa/2.0/', @@ -123,7 +123,7 @@ 'url': 'https://unsplash.com/sveninho', 'file': 'ss-mountainforest.jpg', 'license': 'CC', - 'license_url': 'https://creativecommons.org/publicdomain/zero/1.0/', // https://unsplash.com/license + 'license_url': 'https://creativecommons.org/publicdomain/zero/1.0/' // https://unsplash.com/license }, 'tribes-1': { // Permission granted for Trustroots (asked by Mikael Korpela) @@ -152,7 +152,6 @@ elem.addClass('board-' + key); elem.css({ 'background-image': 'url(/modules/core/img/board/' + photo.file + ')' - //'background-position': (photo.position ? photo.position : '50% 50%') }); // To prevent key being literally `key`: `{key: ...}`, we want it to be actual keyname such as `hitchroad`. @@ -166,4 +165,4 @@ }; } -})(); +}()); diff --git a/modules/core/client/directives/tr-editor.client.directive.js b/modules/core/client/directives/tr-editor.client.directive.js index 255258068f..4b143abb96 100644 --- a/modules/core/client/directives/tr-editor.client.directive.js +++ b/modules/core/client/directives/tr-editor.client.directive.js @@ -1,5 +1,5 @@ -/*global MediumEditor */ -(function(){ +/* global MediumEditor */ +(function () { 'use strict'; /** @@ -106,9 +106,9 @@ }); // On ctrl+enter - if(iAttrs.trEditorOnCtrlEnter) { + if (iAttrs.trEditorOnCtrlEnter) { ngModel.editor.subscribe('editableKeydownEnter', function (event, editable) { - if(event.ctrlKey) { + if (event.ctrlKey) { event.preventDefault(); // Apply linked function $parse(iAttrs.trEditorOnCtrlEnter)(scope.$parent); @@ -123,4 +123,4 @@ }; } -})(); +}()); diff --git a/modules/core/client/directives/tr-flashcards.client.directive.js b/modules/core/client/directives/tr-flashcards.client.directive.js index 4f27e87163..185b2378f9 100644 --- a/modules/core/client/directives/tr-flashcards.client.directive.js +++ b/modules/core/client/directives/tr-flashcards.client.directive.js @@ -1,4 +1,4 @@ -(function(){ +(function () { 'use strict'; /** @@ -21,34 +21,28 @@ return { restrict: 'A', template: '' + - 'Tip' + - '' + - '' + + ' Tip' + + ' ' + + ' ' + '', link: function(scope, iElement, iAttrs) { - var flashcards = [ - { - title: 'Make sure your profile is complete', - content: 'You\'re much more likely to get a positive response if you have written a bit about yourself.' - }, - { - title: 'Tell a little bit about yourself', - content: 'You\'re much more likely to get a positive response if you have written a bit about yourself.' - }, - { - title: 'Explain them why you are choosing them', - content: '...explaining that you are interested in meeting them, not just looking for free accommodation.' - }, - { - title: 'Tell your host why you\'re on a trip', - content: 'What are your expectations in regards with going through their town?' - }, - { - title: 'Trustroots is very much about spontaneous travel', - content: 'Don\'t write to people 2 months ahead.' - } - ]; + var flashcards = [{ + title: 'Make sure your profile is complete', + content: 'You\'re much more likely to get a positive response if you have written a bit about yourself.' + }, { + title: 'Tell a little bit about yourself', + content: 'You\'re much more likely to get a positive response if you have written a bit about yourself.' + }, { + title: 'Explain them why you are choosing them', + content: '...explaining that you are interested in meeting them, not just looking for free accommodation.' + }, { + title: 'Tell your host why you\'re on a trip', + content: 'What are your expectations in regards with going through their town?' + }, { + title: 'Trustroots is very much about spontaneous travel', + content: 'Don\'t write to people 2 months ahead.' + }]; var randomFlashcard = flashcards[Math.floor(Math.random() * flashcards.length)]; @@ -59,4 +53,4 @@ }; } -})(); +}()); diff --git a/modules/core/client/directives/tr-focustip.client.directive.js b/modules/core/client/directives/tr-focustip.client.directive.js index 2fe1f012a3..0e65a9257b 100644 --- a/modules/core/client/directives/tr-focustip.client.directive.js +++ b/modules/core/client/directives/tr-focustip.client.directive.js @@ -1,4 +1,4 @@ -(function(){ +(function () { 'use strict'; /** @@ -21,14 +21,15 @@ scope: { trFocustip: '=' }, - link: function(scope, el, attrs, ctrl) { + link: function(scope, element, attrs, ctrl) { // Compiled template // after() requires jQuery var template = $compile('
<\/p>/g, ' ').trim();
@@ -60,33 +60,33 @@ exports.html = function (content) {
// Turn URLs/emails/phonenumbers into links
// @link https://github.com/gregjacobs/Autolinker.js
content = Autolinker.link(content, {
- // Don't auto-link Twitter handles (@username)
- twitter: false,
+ // Don't auto-link Twitter handles (@username)
+ twitter: false,
- // Auto-link emails
- email: true,
+ // Auto-link emails
+ email: true,
- // Auto-link URLs
- urls: true,
+ // Auto-link URLs
+ urls: true,
- // Auto-link phone numbers
- phone: true,
+ // Auto-link phone numbers
+ phone: true,
- // A number for how many characters long URLs/emails/Twitter handles/Twitter hashtags should be truncated to
- // inside the text of a link. If the match is over the number of characters, it will be truncated to this length
- // by replacing the end of the string with a two period ellipsis ('..').
- truncate: {
- length: 150,
- location: 'middle' // end|middle|smart
- },
+ // A number for how many characters long URLs/emails/Twitter handles/Twitter hashtags should be truncated to
+ // inside the text of a link. If the match is over the number of characters, it will be truncated to this length
+ // by replacing the end of the string with a two period ellipsis ('..').
+ truncate: {
+ length: 150,
+ location: 'middle' // end|middle|smart
+ },
- // Strip 'http://' or 'https://' and/or the 'www.' from the beginning of links.
- // I.e.: `https://www.wikipedia.org/` => `wikipedia.org`
- stripPrefix: true,
+ // Strip 'http://' or 'https://' and/or the 'www.' from the beginning of links.
+ // I.e.: `https://www.wikipedia.org/` => `wikipedia.org`
+ stripPrefix: true,
- // Don't add target="_blank" because of https://mathiasbynens.github.io/rel-noopener/ attack.
- newWindow: false
- });
+ // Don't add target="_blank" because of https://mathiasbynens.github.io/rel-noopener/ attack.
+ newWindow: false
+ });
}
@@ -103,7 +103,7 @@ exports.isEmpty = function (content) {
return (
typeof content !== 'string' ||
content.length === 0 ||
- sanitizeHtml(content, {allowedTags: []}).replace(/ /g, ' ').trim() === ''
+ sanitizeHtml(content, { allowedTags: [] }).replace(/ /g, ' ').trim() === ''
);
};
@@ -115,13 +115,13 @@ exports.isEmpty = function (content) {
*/
exports.plainText = function (content, cleanWhitespace) {
- if(typeof content === 'string' && content.length > 0) {
+ if (typeof content === 'string' && content.length > 0) {
// No HTML allowed
- content = sanitizeHtml(content, {allowedTags: []});
+ content = sanitizeHtml(content, { allowedTags: [] });
// Remove white space. Matches a single white space character, including space, tab, form feed, line feed.
- if(cleanWhitespace === true) {
+ if (cleanWhitespace === true) {
content = content.replace(/\s/g, ' ');
}
diff --git a/modules/core/server/views/layout.server.view.html b/modules/core/server/views/layout.server.view.html
index 1cb934de4b..0b5253fb47 100644
--- a/modules/core/server/views/layout.server.view.html
+++ b/modules/core/server/views/layout.server.view.html
@@ -96,7 +96,7 @@
{# Google Analytics #}
{% if googleAnalytics.enabled === true %}
+
diff --git a/modules/tags/server/controllers/tags.server.controller.js b/modules/tags/server/controllers/tags.server.controller.js
index 8d7322061f..c5f03deaf6 100644
--- a/modules/tags/server/controllers/tags.server.controller.js
+++ b/modules/tags/server/controllers/tags.server.controller.js
@@ -10,17 +10,17 @@ var path = require('path'),
// Publicly exposed fields from tags
exports.tagFields = [
- '_id',
- 'slug',
- 'label',
- 'count'
- ].join(' ');
+ '_id',
+ 'slug',
+ 'label',
+ 'count'
+].join(' ');
/**
* Crate a tag
*/
exports.createTag = function(req, res) {
- if(!req.user) {
+ if (!req.user) {
return res.status(403).send({
message: errorHandler.getErrorMessageByKey('forbidden')
});
diff --git a/modules/tags/server/controllers/tribes.server.controller.js b/modules/tags/server/controllers/tribes.server.controller.js
index 0288e20bf9..a6622d81f8 100644
--- a/modules/tags/server/controllers/tribes.server.controller.js
+++ b/modules/tags/server/controllers/tribes.server.controller.js
@@ -12,24 +12,24 @@ var path = require('path'),
// Publicly exposed fields from tribes
exports.tribeFields = [
- '_id',
- 'slug',
- 'label',
- 'count',
- 'color',
- 'image_UUID',
- 'attribution',
- 'attribution_url'
- ].join(' ');
+ '_id',
+ 'slug',
+ 'label',
+ 'count',
+ 'color',
+ 'image_UUID',
+ 'attribution',
+ 'attribution_url'
+].join(' ');
/**
* Constructs link headers for pagination
*/
var setLinkHeader = function(req, res, pageCount) {
- if(paginate.hasNextPages(req)(pageCount)) {
+ if (paginate.hasNextPages(req)(pageCount)) {
var nextPage = { page: req.query.page + 1 };
- var linkHead = '<' + req.protocol + ':' + res.locals.url.slice(0,-1) + res.locals.paginate.href(nextPage) + '>; rel="next"';
- res.set('Link',linkHead);
+ var linkHead = '<' + req.protocol + ':' + res.locals.url.slice(0, -1) + res.locals.paginate.href(nextPage) + '>; rel="next"';
+ res.set('Link', linkHead);
}
};
@@ -44,8 +44,8 @@ exports.listTribes = function(req, res) {
tribe: true
},
{
- page: parseInt(req.query.page) || 1, // Note: `parseInt('0')` will return `NaN`, `page` will be set to `1` in such case.
- limit: parseInt(req.query.limit) || 0, // `0` for infinite
+ page: parseInt(req.query.page, 10) || 1, // Note: `parseInt('0')` will return `NaN`, `page` will be set to `1` in such case.
+ limit: parseInt(req.query.limit, 10) || 0, // `0` for infinite
sort: {
count: 'desc'
},
diff --git a/modules/tags/server/models/tag.server.model.js b/modules/tags/server/models/tag.server.model.js
index 6260670cf9..fa82aea66a 100644
--- a/modules/tags/server/models/tag.server.model.js
+++ b/modules/tags/server/models/tag.server.model.js
@@ -9,7 +9,7 @@ var path = require('path'),
mongoosePaginate = require('mongoose-paginate'),
uniqueValidation = require('mongoose-beautiful-unique-validation'),
integerValidator = require('mongoose-integer'),
- URLSlugs = require('mongoose-url-slugs'),
+ urlslugs = require('mongoose-url-slugs'),
randomColor = require('randomcolor'),
speakingurl = require('speakingurl'),
validator = require('validator'),
@@ -46,7 +46,7 @@ var validateLabel = function(label) {
*/
var validateURL = function(url) {
return !url || validator.isURL(url, {
- protocols: ['http','https'],
+ protocols: ['http', 'https'],
require_tld: true,
require_protocol: true,
require_valid_protocol: true,
@@ -145,13 +145,13 @@ var TagSchema = new Schema({
* @link https://npmjs.org/package/speakingurl
* @link https://github.com/mindblaze/mongoose-url-slugs/issues/17
*/
-TagSchema.plugin(URLSlugs('label', {
+TagSchema.plugin(urlslugs('label', {
field: 'slug',
generator: function(string) {
return speakingurl(string, {
separator: '-', // char that replaces the whitespaces
maintainCase: false, // maintain case (true, convert all chars to lower case (false)
- truncate: 255 // trim to max length ({number}), don't truncate (0)
+ truncate: 255 // trim to max length ({number}), don't truncate (0)
});
}
}));
diff --git a/modules/tags/server/policies/tags.server.policy.js b/modules/tags/server/policies/tags.server.policy.js
index 1fcd23a1f6..78b9bf39b1 100644
--- a/modules/tags/server/policies/tags.server.policy.js
+++ b/modules/tags/server/policies/tags.server.policy.js
@@ -70,7 +70,7 @@ exports.isAllowed = function(req, res, next) {
// No tags/tribes for non-authenticated users
/*
- if(!req.user || (req.user && !req.user.public)) {
+ if (!req.user || (req.user && !req.user.public)) {
return res.status(403).send({
message: errorHandler.getErrorMessageByKey('forbidden')
});
@@ -81,13 +81,13 @@ exports.isAllowed = function(req, res, next) {
var roles = (req.user && req.user.roles) ? req.user.roles : ['guest'];
acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function(err, isAllowed) {
- if(err) {
+ if (err) {
// An authorization error occurred.
return res.status(500).send({
message: 'Unexpected authorization error'
});
} else {
- if(isAllowed) {
+ if (isAllowed) {
// Access granted! Invoke next middleware
return next();
} else {
diff --git a/modules/tags/tests/server/tags.server.model.tests.js b/modules/tags/tests/server/tags.server.model.tests.js
index be4ef18377..23aa50283c 100644
--- a/modules/tags/tests/server/tags.server.model.tests.js
+++ b/modules/tags/tests/server/tags.server.model.tests.js
@@ -13,7 +13,9 @@ var path = require('path'),
/**
* Globals
*/
-var tag, tag2, tag3;
+var tag,
+ tag2,
+ tag3;
/**
* Unit tests
diff --git a/modules/tags/tests/server/tags.server.routes.test.js b/modules/tags/tests/server/tags.server.routes.test.js
index 6e94c1173d..b6bd0225a9 100644
--- a/modules/tags/tests/server/tags.server.routes.test.js
+++ b/modules/tags/tests/server/tags.server.routes.test.js
@@ -12,7 +12,17 @@ var should = require('should'),
/**
* Globals
*/
-var app, agent, credentials, user, _user, tag, _tag, tribe, _tribe, tribeNonPublic, _tribeNonPublic;
+var app,
+ agent,
+ credentials,
+ user,
+ _user,
+ tag,
+ _tag,
+ tribe,
+ _tribe,
+ tribeNonPublic,
+ _tribeNonPublic;
/**
* User routes tests
@@ -59,7 +69,7 @@ describe('Tag CRUD tests', function () {
attribution: 'Photo credits',
attribution_url: 'http://www.trustroots.org/team',
image_UUID: '3c8bb9f1-e313-4baa-bf4c-1d8994fd6c6c',
- tribe: true,
+ tribe: true
};
// Create a new non-public tribe
diff --git a/modules/users/client/config/users.client.config.js b/modules/users/client/config/users.client.config.js
index 4c6755832d..7b033adb1f 100644
--- a/modules/users/client/config/users.client.config.js
+++ b/modules/users/client/config/users.client.config.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -34,4 +34,4 @@
]);
}
-})();
+}());
diff --git a/modules/users/client/config/users.client.routes.js b/modules/users/client/config/users.client.routes.js
index c72a42a574..2e48deb2ea 100644
--- a/modules/users/client/config/users.client.routes.js
+++ b/modules/users/client/config/users.client.routes.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -36,7 +36,7 @@
templateUrl: '/modules/users/views/profile/profile-edit.client.view.html',
abstract: true,
controller: 'ProfileEditController',
- controllerAs : 'profileEdit'
+ controllerAs: 'profileEdit'
}).
state('profile-edit.about', {
url: '',
@@ -105,12 +105,11 @@
// Contact is loaded only after profile is loaded, because we need the profile ID
contact: function(ContactByService, profile, Authentication) {
return profile.$promise.then(function(profile) {
- // No profile found or looking at own profile: no need to load contact
- if(Authentication.user && Authentication.user._id === profile._id) {
+ if (Authentication.user && Authentication.user._id === profile._id) {
+ // No profile found or looking at own profile: no need to load contact
return;
- }
- // Load contact
- else {
+ } else {
+ // Load contact
return ContactByService.get({
userId: profile._id
});
@@ -160,7 +159,7 @@
state('profile-signup', {
url: '/profile-signup',
title: 'Trustroots profile',
- templateUrl: '/modules/users/views/profile/profile-signup.client.view.html',
+ templateUrl: '/modules/users/views/profile/profile-signup.client.view.html'
}).
// Auth routes
@@ -238,4 +237,4 @@
});
}
-})();
+}());
diff --git a/modules/users/client/controllers/authentication.client.controller.js b/modules/users/client/controllers/authentication.client.controller.js
index a967871355..f118f7e994 100644
--- a/modules/users/client/controllers/authentication.client.controller.js
+++ b/modules/users/client/controllers/authentication.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -42,15 +42,14 @@
// Redirect to where we were left off before sign-in page
// See modules/core/client/controllers/main.client.controller.js
- if(vm.continue) {
+ if (vm.continue) {
var stateTo = $rootScope.signinState || 'search',
stateToParams = $rootScope.signinStateParams || {};
delete $rootScope.signinState;
delete $rootScope.signinStateParams;
$state.go(stateTo, stateToParams);
- }
- // Redirect to the search page
- else {
+ } else {
+ // Redirect to the search page
$state.go('search');
}
}).error(function(error) {
@@ -65,4 +64,4 @@
}
-})();
+}());
diff --git a/modules/users/client/controllers/avatar-editor.client.controller.js b/modules/users/client/controllers/avatar-editor.client.controller.js
index e1ddf455f9..fc809c70f4 100644
--- a/modules/users/client/controllers/avatar-editor.client.controller.js
+++ b/modules/users/client/controllers/avatar-editor.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -34,7 +34,7 @@
function saveAvatar() {
// Uploaded new file
- if(vm.user.avatarSource === 'local' && vm.avatarPreview === true) {
+ if (vm.user.avatarSource === 'local' && vm.avatarPreview === true) {
// Upload the new file
vm.avatarUploading = true;
vm.upload = Upload.upload({
@@ -52,27 +52,22 @@
}).error(function(data, status, headers, config) {
messageCenterService.add('danger', 'Oops! Something went wrong. Try again later.');
vm.avatarUploading = false;
- //$uibModalInstance.dismiss('close');
});
- }
-
- // Changed avatar selection (but didn't upload new file)
- else if(lastAvatarSource !== vm.user.avatarSource) {
+ } else if (lastAvatarSource !== vm.user.avatarSource) {
+ // Close modal due user changed avatar selection (but didn't upload a new file)
$uibModalInstance.close(vm.user);
- }
-
- // No changes, just dismiss...
- else {
+ } else {
+ // No changes, just dismiss...
dismissModal();
}
}
/**
- * Process preview after file is selected/dropped/received from camera
+ * Process preview after file is selected via fileinput / dropped to window / received from camera
*/
function fileSelected($files, $event) {
// Too early
- if($files && $files.length === 0) {
+ if ($files && $files.length === 0) {
return;
}
@@ -82,14 +77,11 @@
vm.user.avatarSource = 'local';
// Validate file
- if(file.type.indexOf('jpeg') === -1 && file.type.indexOf('gif') === -1 && file.type.indexOf('png') === -1) {
- messageCenterService.add('danger', 'Please give a jpg, gif, or png image.');
- }
- else if(file.size > appSettings.maxUploadSize) {
- messageCenterService.add('danger', 'Whoops, your file is too big. Please keep it up to ' + bytesToSize(appSettings.maxUploadSize) + '. Sorry!');
- }
- // Upload file
- else {
+ if (file.type.indexOf('jpeg') === -1 && file.type.indexOf('gif') === -1 && file.type.indexOf('png') === -1) {
+ messageCenterService.add('danger', 'Please give a jpg, gif, or png image.');
+ } else if (file.size > appSettings.maxUploadSize) {
+ messageCenterService.add('danger', 'Whoops, your file is too big. Please keep it up to ' + bytesToSize(appSettings.maxUploadSize) + '. Sorry!');
+ } else {
vm.avatarUploading = true;
// Show the local file as a preview
@@ -114,10 +106,10 @@
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Byte';
- var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
+ var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10);
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
}
-})();
+}());
diff --git a/modules/users/client/controllers/confirm-email.client.controller.js b/modules/users/client/controllers/confirm-email.client.controller.js
index 4f6e9b8c8b..a4f4309094 100644
--- a/modules/users/client/controllers/confirm-email.client.controller.js
+++ b/modules/users/client/controllers/confirm-email.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -18,7 +18,7 @@
vm.isLoading = false;
// Is ?signup at the url (set only for first email confirms)
- vm.signup = ($stateParams.signup) ? true : false;
+ vm.signup = angular.isDefined($stateParams.signup);
// Change user password
function confirmEmail() {
@@ -32,12 +32,11 @@
Authentication.user = response.user;
$rootScope.$broadcast('userUpdated');
- // If successful and this was user's first confirm, welcome them to the community
- if(response.profileMadePublic) {
+ if (response.profileMadePublic) {
+ // If successful and this was user's first confirm, welcome them to the community
$state.go('welcome');
- }
- // If succesfull and wasn't first time, say yay!
- else {
+ } else {
+ // If succesfull and wasn't first time, say yay!
vm.success = true;
}
@@ -49,4 +48,4 @@
}
-})();
+}());
diff --git a/modules/users/client/controllers/password-forgot.client.controller.js b/modules/users/client/controllers/password-forgot.client.controller.js
index dacaddca45..d36006f548 100644
--- a/modules/users/client/controllers/password-forgot.client.controller.js
+++ b/modules/users/client/controllers/password-forgot.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -37,4 +37,4 @@
}
}
-})();
+}());
diff --git a/modules/users/client/controllers/password-reset.client.controller.js b/modules/users/client/controllers/password-reset.client.controller.js
index 63a5c76ff0..d0da7833c7 100644
--- a/modules/users/client/controllers/password-reset.client.controller.js
+++ b/modules/users/client/controllers/password-reset.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -43,4 +43,4 @@
}
}
-})();
+}());
diff --git a/modules/users/client/controllers/profile-edit-about.client.controller.js b/modules/users/client/controllers/profile-edit-about.client.controller.js
index 0a45bf502e..3ea249ad1f 100644
--- a/modules/users/client/controllers/profile-edit-about.client.controller.js
+++ b/modules/users/client/controllers/profile-edit-about.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -43,15 +43,15 @@
*/
function decodeUserLanguages() {
var langs_arr = [];
- if(vm.user && vm.user.languages) {
+ if (vm.user && vm.user.languages) {
vm.user.languages.forEach(function(key) {
- langs_arr[langs_arr.length] = {key: key, name: vm.languages[key]};
+ langs_arr[langs_arr.length] = { key: key, name: vm.languages[key] };
});
}
vm.userLanguages = langs_arr;
}
function encodeUserLanguages() {
- if(!vm.user) return;
+ if (!vm.user) return;
var langs_arr = [];
vm.userLanguages.forEach(function(lang) {
@@ -65,21 +65,20 @@
*/
function updateUserProfile(isValid) {
encodeUserLanguages();
- if(isValid) {
+ if (isValid) {
vm.user.$update(function(response) {
Authentication.user = response;
$scope.$emit('userUpdated');
messageCenterService.add('success', 'Profile updated.');
}, function(response) {
- messageCenterService.add('danger', response.data.message || 'Something went wrong. Please try again!' , { timeout: 10000 });
+ messageCenterService.add('danger', response.data.message || 'Something went wrong. Please try again!', { timeout: 10000 });
});
- }
- else {
- messageCenterService.add('danger', 'Please fix errors from your profile and try again.' , { timeout: 10000 });
+ } else {
+ messageCenterService.add('danger', 'Please fix errors from your profile and try again.', { timeout: 10000 });
}
}
}
-})();
+}());
diff --git a/modules/users/client/controllers/profile-edit-account.client.controller.js b/modules/users/client/controllers/profile-edit-account.client.controller.js
index 6a8cbf35d1..0de127c95d 100644
--- a/modules/users/client/controllers/profile-edit-account.client.controller.js
+++ b/modules/users/client/controllers/profile-edit-account.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -48,8 +48,8 @@
* Resend confirmation email for already sent email
*/
function resendUserEmailConfirm($event) {
- if($event) $event.preventDefault();
- if(vm.user.emailTemporary) {
+ if ($event) $event.preventDefault();
+ if (vm.user.emailTemporary) {
vm.user.email = vm.user.emailTemporary;
updateUserEmail();
}
@@ -86,7 +86,7 @@
vm.currentPassword = '';
vm.newPassword = '';
vm.verifyPassword = '';
- angular.element('#newPassword').val(''); //Fix to bypass password verification directive
+ angular.element('#newPassword').val(''); // Fix to bypass password verification directive
vm.changeUserPasswordLoading = false;
vm.user = Authentication.user = response.user;
messageCenterService.add('success', 'Your password is now changed. Have a nice day!');
@@ -99,4 +99,4 @@
}
-})();
+}());
diff --git a/modules/users/client/controllers/profile-edit-networks.client.controller.js b/modules/users/client/controllers/profile-edit-networks.client.controller.js
index c2675e1ae2..9229b981f5 100644
--- a/modules/users/client/controllers/profile-edit-networks.client.controller.js
+++ b/modules/users/client/controllers/profile-edit-networks.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -35,11 +35,8 @@
/**
* Check if there are additional accounts
*/
- function hasConnectedAdditionalSocialAccounts(provider) {
- for (var i in vm.user.additionalProvidersData) {
- return true;
- }
- return false;
+ function hasConnectedAdditionalSocialAccounts() {
+ return (vm.user.additionalProvidersData && Object.keys(vm.user.additionalProvidersData).length);
}
/**
@@ -59,7 +56,7 @@
vm.user = Authentication.user = response;
$scope.$emit('userUpdated');
}).error(function(response) {
- messageCenterService.add('danger', response.message || 'Something went wrong. Try again or contact us to disconnect your profile.' , { timeout: 10000 });
+ messageCenterService.add('danger', response.message || 'Something went wrong. Try again or contact us to disconnect your profile.', { timeout: 10000 });
});
}
@@ -67,20 +64,19 @@
* Update a user profile
*/
function updateUserProfile(isValid) {
- if(isValid) {
+ if (isValid) {
vm.user.$update(function(response) {
Authentication.user = response;
$scope.$emit('userUpdated');
messageCenterService.add('success', 'Hospitality networks updated.');
}, function(response) {
- messageCenterService.add('danger', response.data.message || 'Something went wrong. Please try again!' , { timeout: 10000 });
+ messageCenterService.add('danger', response.data.message || 'Something went wrong. Please try again!', { timeout: 10000 });
});
- }
- else {
- messageCenterService.add('danger', 'Please fix errors from your profile and try again.' , { timeout: 10000 });
+ } else {
+ messageCenterService.add('danger', 'Please fix errors from your profile and try again.', { timeout: 10000 });
}
}
}
-})();
+}());
diff --git a/modules/users/client/controllers/profile-edit-photo.client.controller.js b/modules/users/client/controllers/profile-edit-photo.client.controller.js
index 12880e4f1f..16afa94c46 100644
--- a/modules/users/client/controllers/profile-edit-photo.client.controller.js
+++ b/modules/users/client/controllers/profile-edit-photo.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -54,7 +54,7 @@
*/
function saveAvatar() {
// Uploaded new file
- if(vm.user.avatarSource === 'local' && vm.avatarPreview === true) {
+ if (vm.user.avatarSource === 'local' && vm.avatarPreview === true) {
// Upload the new file
vm.avatarUploading = true;
vm.upload = Upload.upload({
@@ -73,16 +73,14 @@
// Default error
var saveAvatarErr = 'Oops! Something went wrong. Try again later.';
- // Could not process file
- if(status === 422) {
+ if (status === 422) {
+ // Could not process file
saveAvatarErr = 'Sorry, we could not process this file.';
- }
- // File too large
- else if(status === 413) {
+ } else if (status === 413) {
+ // File too large
saveAvatarErr = 'Whoops, your file is too big. Please keep it up to ' + bytesToSize(appSettings.maxUploadSize) + '.';
- }
- // Unsupported media type
- else if(status === 415) {
+ } else if (status === 415) {
+ // Unsupported media type
saveAvatarErr = 'Sorry, we do not support this type of file.';
}
@@ -95,11 +93,11 @@
}
/**
- * Process preview after file is selected/dropped/received from camera
+ * Process preview after file is selected via fileinput / dropped to window / received from camera
*/
function fileSelected($files, $event) {
// Too early
- if($files && $files.length === 0) {
+ if ($files && $files.length === 0) {
return;
}
@@ -109,15 +107,14 @@
vm.user.avatarSource = 'local';
vm.user.avatarUploaded = true;
- // Validate file
- if(file.type.indexOf('jpeg') === -1 && file.type.indexOf('gif') === -1 && file.type.indexOf('png') === -1) {
- messageCenterService.add('danger', 'Please give a jpg, gif, or png image.');
- }
- else if(file.size > appSettings.maxUploadSize) {
- messageCenterService.add('danger', 'Whoops, your file is too big. Please keep it up to ' + bytesToSize(appSettings.maxUploadSize) + '.');
- }
- // Upload file
- else {
+ // Validate filetype
+ if (file.type.indexOf('jpeg') === -1 && file.type.indexOf('gif') === -1 && file.type.indexOf('png') === -1) {
+ messageCenterService.add('danger', 'Please give a jpg, gif, or png image.');
+ // Validate filesize
+ } else if (file.size > appSettings.maxUploadSize) {
+ messageCenterService.add('danger', 'Whoops, your file is too big. Please keep it up to ' + bytesToSize(appSettings.maxUploadSize) + '.');
+ // All good, uploading file...
+ } else {
vm.avatarUploading = true;
// Show the local file as a preview
@@ -161,11 +158,11 @@
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Byte';
- var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
+ var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10);
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
}
-})();
+}());
diff --git a/modules/users/client/controllers/profile-edit-tags.client.controller.js b/modules/users/client/controllers/profile-edit-tags.client.controller.js
index 38e05e318a..2fb9ac87f8 100644
--- a/modules/users/client/controllers/profile-edit-tags.client.controller.js
+++ b/modules/users/client/controllers/profile-edit-tags.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -22,20 +22,19 @@
* Update a user profile
*/
function updateUserProfile(isValid) {
- if(isValid) {
+ if (isValid) {
vm.user.$update(function(response) {
Authentication.user = response;
$scope.$emit('userUpdated');
messageCenterService.add('success', 'Hospitality networks updated.');
}, function(response) {
- messageCenterService.add('danger', response.data.message || 'Something went wrong. Please try again!' , { timeout: 10000 });
+ messageCenterService.add('danger', response.data.message || 'Something went wrong. Please try again!', { timeout: 10000 });
});
- }
- else {
- messageCenterService.add('danger', 'Please fix errors from your profile and try again.' , { timeout: 10000 });
+ } else {
+ messageCenterService.add('danger', 'Please fix errors from your profile and try again.', { timeout: 10000 });
}
}
}
-})();
+}());
diff --git a/modules/users/client/controllers/profile-edit.client.controller.js b/modules/users/client/controllers/profile-edit.client.controller.js
index a3debd22f7..b7eeb7956e 100644
--- a/modules/users/client/controllers/profile-edit.client.controller.js
+++ b/modules/users/client/controllers/profile-edit.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -21,7 +21,7 @@
// React when state changes and there are unsaved modifications
$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options) {
- if(vm.unsavedModifications) {
+ if (vm.unsavedModifications) {
// Cancel original $state transition
// transitionTo() promise will be rejected with
// a 'transition prevented' error
@@ -29,19 +29,19 @@
// Ask for confirmation
$confirm({
- title: 'Are you sure?',
- text: 'Your changes would be lost. Return and press "Save" to keep the changes, or press "Continue" to discard them.',
- ok: 'Continue',
- cancel: 'Cancel'
- })
- // If user pressed "continue", create another state go
- .then(function() {
- vm.unsavedModifications = false;
- $state.go(toState.name, toParams);
- });
+ title: 'Are you sure?',
+ text: 'Your changes would be lost. Return and press "Save" to keep the changes, or press "Continue" to discard them.',
+ ok: 'Continue',
+ cancel: 'Cancel'
+ })
+ // If user pressed "continue", create another state go
+ .then(function() {
+ vm.unsavedModifications = false;
+ $state.go(toState.name, toParams);
+ });
}
});
}
-})();
+}());
diff --git a/modules/users/client/controllers/profile.client.controller.js b/modules/users/client/controllers/profile.client.controller.js
index e24ac8c6f0..2f371629f8 100644
--- a/modules/users/client/controllers/profile.client.controller.js
+++ b/modules/users/client/controllers/profile.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -9,8 +9,8 @@
function ProfileController($scope, $stateParams, $state, $location, $uibModal, $filter, $window, Languages, Users, Contact, Authentication, $timeout, messageCenterService, profile, contact, appSettings) {
// No user defined at URL, just redirect to user's own profile
- if(!$stateParams.username) {
- $state.go('profile.about', {username: Authentication.user.username});
+ if (!$stateParams.username) {
+ $state.go('profile.about', { username: Authentication.user.username });
}
// ViewModel
@@ -40,24 +40,23 @@
initMemberships();
// When on small screen...
- if(angular.element('body').width() <= 480) {
+ if (angular.element('body').width() <= 480) {
// By default we land to `about` tab of this controller
// If we're on small screens, direct to `overview` tab instead
- if($state.current.name === 'profile.about') {
+ if ($state.current.name === 'profile.about') {
// Timeout ensures `ui-sref-active=""` gets updated at the templates
$timeout(function() {
$state.go('profile.overview', { username: profile.username });
});
}
- }
// When on bigger screen...
// Redirect "mobile only" tabs to about tab
- else if(['profile.overview', 'profile.accommodation'].indexOf($state.current.name) > -1) {
+ } else if (['profile.overview', 'profile.accommodation'].indexOf($state.current.name) > -1) {
$state.go('profile.about', { username: profile.username });
}
// If this is authenticated user's own profile, measure profile description length
- if(Authentication.user._id === profile._id) {
+ if (Authentication.user._id === profile._id) {
vm.profileDescriptionLength = Authentication.user.description ? $filter('plainTextLength')(Authentication.user.description) : 0;
}
@@ -84,20 +83,22 @@
*/
function initMemberships() {
var memberships = {
- 'tribes': {
- 'is': [],
- 'likes': []
- },
- 'tags': {
- 'is': [],
- 'likes': []
- }
- };
+ 'tribes': {
+ 'is': [],
+ 'likes': []
+ },
+ 'tags': {
+ 'is': [],
+ 'likes': []
+ }
+ };
// Construct tribes & tags
- if(profile && profile.member && profile.member.length > 0) {
+ if (profile && profile.member && profile.member.length > 0) {
for (var i = 0, len = profile.member.length; i < len; i++) {
- // Sort to right category...
- memberships[ (profile.member[i].tag.tribe ? 'tribes' : 'tags') ][ profile.member[i].relation ].push(profile.member[i].tag);
+ // Sort to the right category...
+ var tribeOrTag = (profile.member[i].tag.tribe ? 'tribes' : 'tags'),
+ relation = profile.member[i].relation;
+ memberships[tribeOrTag][relation].push(profile.member[i].tag);
}
}
vm.memberships = memberships;
@@ -130,11 +131,8 @@
/**
* Check if there are additional accounts
*/
- function hasConnectedAdditionalSocialAccounts(provider) {
- for (var i in vm.profile.additionalProvidersData) {
- return true;
- }
- return false;
+ function hasConnectedAdditionalSocialAccounts() {
+ return (vm.profile.additionalProvidersData && Object.keys(vm.profile.additionalProvidersData).length);
}
/**
@@ -149,18 +147,17 @@
* Ensure these values are published at users.profile.server.controller.js
*/
function socialAccountLink(providerName, providerData) {
- if(providerName === 'facebook' && providerData.id) {
+ if (providerName === 'facebook' && providerData.id) {
return 'https://www.facebook.com/app_scoped_user_id/' + providerData.id;
- }
- else if(providerName === 'twitter' && providerData.screen_name) {
+ } else if (providerName === 'twitter' && providerData.screen_name) {
return 'https://twitter.com/' + providerData.screen_name;
- }
- else if(providerName === 'github' && providerData.login) {
+ } else if (providerName === 'github' && providerData.login) {
return 'https://github.com/' + providerData.login;
+ } else {
+ return '#';
}
- else return '#';
}
}
-})();
+}());
diff --git a/modules/users/client/controllers/signup.client.controller.js b/modules/users/client/controllers/signup.client.controller.js
index 22e564daa2..2a6a4c2d70 100644
--- a/modules/users/client/controllers/signup.client.controller.js
+++ b/modules/users/client/controllers/signup.client.controller.js
@@ -1,4 +1,4 @@
-(function() {
+(function () {
'use strict';
angular
@@ -30,20 +30,20 @@
function activate() {
// If user is already signed in then redirect to search page
- if(Authentication.user) {
+ if (Authentication.user) {
$state.go('search');
return;
}
// Fetch information about referred tribe
- if($stateParams.tribe && $stateParams.tribe !== '') {
+ if ($stateParams.tribe && $stateParams.tribe !== '') {
TribeService.get({
tribeSlug: $stateParams.tribe
})
.then(function(tribe) {
// Got it
- if(tribe._id) {
+ if (tribe._id) {
vm.tribe = tribe;
// Show one less suggestion since we have referred tribe
vm.suggestionsLimit--;
@@ -53,8 +53,7 @@
getSuggestedTribes(tribe._id || null);
});
- }
- else {
+ } else {
getSuggestedTribes();
}
}
@@ -67,22 +66,21 @@
function getSuggestedTribes(withoutTribeId) {
TribesService.query({
// If we have referred tribe, load one extra suggestion in case we load referred tribe among suggestions
- limit: (vm.tribe ? (parseInt(vm.suggestionsLimit + 1)) : vm.suggestionsLimit)
+ limit: (vm.tribe ? (parseInt(vm.suggestionsLimit + 1, 10)) : vm.suggestionsLimit)
},
function(tribes) {
var suggestedTribes = [];
// Make sure to remove referred tribe from suggested tribes so that we won't have dublicates
// We'll always show 2 or 3 of these at the frontend depending on if referred tribe is shown.
- if(withoutTribeId) {
+ if (withoutTribeId) {
angular.forEach(tribes, function(suggestedTribe) {
- if(suggestedTribe._id !== withoutTribeId) {
+ if (suggestedTribe._id !== withoutTribeId) {
this.push(suggestedTribe);
}
}, suggestedTribes);
vm.suggestedTribes = suggestedTribes;
- }
- else {
+ } else {
vm.suggestedTribes = tribes;
}
});
@@ -99,7 +97,7 @@
.success(function(newUser) {
// If there is referred tribe, add user to that next up
- if(vm.tribe && vm.tribe._id) {
+ if (vm.tribe && vm.tribe._id) {
UserTagsService.post({
id: vm.tribe._id,
relation: 'is'
@@ -109,9 +107,8 @@
vm.isLoading = false;
vm.step = 2;
});
- }
- // No tribe to join, just continue
- else {
+ } else {
+ // No tribe to join, just continue
updateUser(newUser);
vm.isLoading = false;
vm.step = 2;
@@ -138,7 +135,7 @@
* Open rules modal
*/
function openRules($event) {
- if($event) {
+ if ($event) {
$event.preventDefault();
}
$uibModal.open({
@@ -153,4 +150,4 @@
}
-})();
+}());
diff --git a/modules/users/client/directives/tr-avatar.client.directive.js b/modules/users/client/directives/tr-avatar.client.directive.js
index 0fc0ccc544..996630b8ad 100644
--- a/modules/users/client/directives/tr-avatar.client.directive.js
+++ b/modules/users/client/directives/tr-avatar.client.directive.js
@@ -1,41 +1,42 @@
-'use strict';
-
-/**
- * @ngdoc directive
- *
- * @name trustroots:trAvatar
- *
- * @param {object} user User object
- * @param {int} size Size of the image . Supported values are 2048, 1024, 512, 256, 128, 64, 36, 32, 24 and 16. See avatar.less for details. Defaults to 256.
- * @param {string} source Leave empty to use user's selected source. Values "none", "facebook", "local", "gravatar".
- * @param {boolean} link Link to user's profile. Defaults to true.
- *
- * @description
- *
- * Use this directive to produce user's avatar
- *
- * @example
- *
- *
- * Basic:
- *
- *
- * Advanced:
- *
- *
- */
-angular.module('users').directive('trAvatar', ['$location',
- function($location) {
-
- // Options
- var defaultSize = 256,
- defaultAvatar = '/modules/users/img/avatar.png';
-
- return {
+(function () {
+ 'use strict';
+
+ /**
+ * @ngdoc directive
+ *
+ * @name trustroots:trAvatar
+ *
+ * @param {object} user User object
+ * @param {int} size Size of the image . Supported values are 2048, 1024, 512, 256, 128, 64, 36, 32, 24 and 16. See avatar.less for details. Defaults to 256.
+ * @param {string} source Leave empty to use user's selected source. Values "none", "facebook", "local", "gravatar".
+ * @param {boolean} link Link to user's profile. Defaults to true.
+ *
+ * @description
+ *
+ * Use this directive to produce user's avatar
+ *
+ * @example
+ *
+ *
+ * Basic:
+ *
+ *
+ * Advanced:
+ *
+ *
+ */
+ angular.module('users').directive('trAvatar', ['$location',
+ function($location) {
+
+ // Options
+ var defaultSize = 256,
+ defaultAvatar = '/modules/users/img/avatar.png';
+
+ return {
template:
'',
restrict: 'A',
scope: {
@@ -48,80 +49,61 @@ angular.module('users').directive('trAvatar', ['$location',
function determineSource() {
- // Determine source for avatar
- if($scope.fixedSource) {
- $scope.source = $scope.fixedSource;
+ // Determine source for avatar
+ if ($scope.fixedSource) {
+ $scope.source = $scope.fixedSource;
+ } else if ($scope.user && $scope.user.avatarSource) {
+ $scope.source = $scope.user.avatarSource;
+ } else {
+ $scope.source = 'none';
+ }
+
+ // Avatar via FB
+ // @link https://developers.facebook.com/docs/graph-api/reference/user/picture/
+ if ($scope.source === 'facebook') {
+ if ($scope.user &&
+ $scope.user.additionalProvidersData &&
+ $scope.user.additionalProvidersData.facebook &&
+ $scope.user.additionalProvidersData.facebook.id) {
+ $scope.avatar = $location.protocol() + '://graph.facebook.com/' + $scope.user.additionalProvidersData.facebook.id + '/picture/?width=' + ($scope.size || defaultSize) + '&height=' + ($scope.size || defaultSize);
+ } else {
+ $scope.avatar = defaultAvatar;
}
- else if($scope.user && $scope.user.avatarSource) {
- $scope.source = $scope.user.avatarSource;
+ // Avatar via Gravatar
+ // @link https://en.gravatar.com/site/implement/images/
+ } else if ($scope.source === 'gravatar') {
+ if ($scope.user.emailHash) {
+ $scope.avatar = $location.protocol() + '://gravatar.com/avatar/' + $scope.user.emailHash + '?s=' + ($scope.size || defaultSize);
+
+ // This fallback image won't work via localhost since Gravatar fallback is required to be online.
+ $scope.avatar += '&d=' + encodeURIComponent($location.protocol() + '://' + $location.host() + ':' + $location.port() + defaultAvatar);
+ } else {
+ $scope.avatar = defaultAvatar;
}
- else {
- $scope.source = 'none';
+ // Locally uploaded avatar
+ } else if ($scope.source === 'local') {
+ if ($scope.user.avatarUploaded) {
+ // Cache buster
+ var timestamp = new Date($scope.user.updated).getTime();
+
+ // 32 is the smallest and 2048 biggest file size we're generating.
+ var fileSize = ($scope.size < 32) ? 32 : $scope.size;
+
+ $scope.avatar = '/modules/users/img/profile/uploads/' + $scope.user._id + '/avatar/' + fileSize + '.jpg?' + timestamp;
+ } else {
+ $scope.avatar = defaultAvatar;
}
+ // Dummy avatar
+ } else {
+ $scope.avatar = defaultAvatar + '?none';
+ }
+ } // determineSource()
- /**
- * Avatar via FB
- * @link https://developers.facebook.com/docs/graph-api/reference/user/picture/
- */
- if($scope.source === 'facebook' ) {
- if($scope.user &&
- $scope.user.additionalProvidersData &&
- $scope.user.additionalProvidersData.facebook &&
- $scope.user.additionalProvidersData.facebook.id) {
- $scope.avatar = $location.protocol() + '://graph.facebook.com/' + $scope.user.additionalProvidersData.facebook.id + '/picture/?width=' + ($scope.size || defaultSize) + '&height=' + ($scope.size || defaultSize);
- }
- else {
- $scope.avatar = defaultAvatar;
- }
- }
-
- /**
- * Avatar via Gravatar
- * @link https://en.gravatar.com/site/implement/images/
- */
- else if($scope.source === 'gravatar') {
- if($scope.user.emailHash) {
- $scope.avatar = $location.protocol() + '://gravatar.com/avatar/' + $scope.user.emailHash + '?s=' + ($scope.size || defaultSize);
-
- // This fallback image won't work via localhost since Gravatar fallback is required to be online.
- $scope.avatar += '&d=' + encodeURIComponent( $location.protocol() + '://' + $location.host() + ':' + $location.port() + defaultAvatar );
- }
- else {
- $scope.avatar = defaultAvatar;
- }
- }
-
- /**
- * Locally uploaded image
- * @todo: implement this, duhh
- */
- else if($scope.source === 'local') {
- if($scope.user.avatarUploaded) {
-
- // Cache buster
- var timestamp = new Date($scope.user.updated).getTime();
-
- // 32 is the smallest and 2048 biggest file size we're generating.
- var fileSize = ($scope.size < 32) ? 32 : $scope.size;
-
- $scope.avatar = '/modules/users/img/profile/uploads/' + $scope.user._id + '/avatar/' + fileSize + '.jpg?' + timestamp;
- }
- else {
- $scope.avatar = defaultAvatar;
- }
- }
-
- // Dummy
- else {
- $scope.avatar = defaultAvatar + '?none';
- }
- }// determineSource()
-
- $scope.$watch('user.avatarSource',function() {
+ $scope.$watch('user.avatarSource', function() {
determineSource();
});
- $scope.$watch('user.updated',function() {
+ $scope.$watch('user.updated', function() {
determineSource();
});
@@ -129,7 +111,7 @@ angular.module('users').directive('trAvatar', ['$location',
link: function (scope, element, attr, ctrl) {
// Make sure source won't change dynamicly when user changes
- if(attr.source) {
+ if (attr.source) {
scope.source = attr.source;
scope.fixedSource = attr.source;
}
@@ -138,9 +120,11 @@ angular.module('users').directive('trAvatar', ['$location',
scope.size = attr.size || defaultSize;
// By default show the link
- scope.link = (attr.link !== 'false') ? true : false;
+ scope.link = attr.link !== 'false';
}
- };
- }
-]);
+ };
+ }
+ ]);
+
+}());
diff --git a/modules/users/client/directives/tr-date-select.client.directive.js b/modules/users/client/directives/tr-date-select.client.directive.js
index 04803a1f28..1d731ef424 100644
--- a/modules/users/client/directives/tr-date-select.client.directive.js
+++ b/modules/users/client/directives/tr-date-select.client.directive.js
@@ -1,142 +1,149 @@
-'use strict';
-
-/**
- * @ngdoc directive
- *
- * @name trustroots:trDateSelect
- *
- * Fork of https://github.com/sambs/angular-sb-date-select with additional features:
- * - allows choosing empty values
- * - allows passing our own templates
- *
- * Relies on MomentJS
- * @link http://momentjs.com/
- *
- */
-angular.module('users')
-
- .run(['$templateCache', function ($templateCache) {
-
- var template = [
- '