diff --git a/.travis.yml b/.travis.yml index a106aa64..e7f4764b 100755 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,5 @@ language: node_js +dist: trusty sudo: false node_js: - "5.0.0" @@ -11,11 +12,5 @@ services: addons: code_climate: repo_token: 6c3a1b81a09b2338d6f30913c1bcad115026689752cbb499a0a25061cda6fbcf - apt: - sources: - - ubuntu-toolchain-r-test - packages: - - gcc-4.8 - - g++-4.8 after_script: - grunt coverage diff --git a/README.md b/README.md index f3b5100e..b14c6dbe 100755 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ TellForm 2.0.0 - Add Custom Background and Dropdown Field Images - Add File Upload Form Field -### How to Contribute +## How to Contribute Please checkout our CONTRIBUTING.md on ways to contribute to TellForm. @@ -198,9 +198,13 @@ Does your company use TellForm? Help keep the project bug-free and feature rich Love our work and community? [Become a backer](https://opencollective.com/tellform). - + + + - + + + ## Contributors diff --git a/app/controllers/forms.server.controller.js b/app/controllers/forms.server.controller.js index 2fdd8fca..14db9f8f 100644 --- a/app/controllers/forms.server.controller.js +++ b/app/controllers/forms.server.controller.js @@ -50,7 +50,7 @@ exports.createSubmission = function(req, res) { var timeElapsed = 0; - if(typeof req.body.timeElapsed == "number"){ + if(typeof req.body.timeElapsed === "number"){ timeElapsed = req.body.timeElapsed; } var submission = new FormSubmission({ @@ -209,7 +209,7 @@ exports.update = function(req, res) { delete req.body.form.admin; } - if(form.analytics == null){ + if(form.analytics === null){ form.analytics.visitors = []; form.analytics.gaCode = ''; } diff --git a/app/controllers/users/users.authentication.server.controller.js b/app/controllers/users/users.authentication.server.controller.js index a1784b42..f944e544 100755 --- a/app/controllers/users/users.authentication.server.controller.js +++ b/app/controllers/users/users.authentication.server.controller.js @@ -3,14 +3,10 @@ /** * Module dependencies. */ -var _ = require('lodash'), - errorHandler = require('../errors.server.controller'), +var errorHandler = require('../errors.server.controller'), mongoose = require('mongoose'), passport = require('passport'), - async = require('async'), config = require('../../../config/config'), - nodemailer = require('nodemailer'), - crypto = require('crypto'), User = mongoose.model('User'), tokgen = require("../../libs/tokenGenerator"); @@ -20,9 +16,6 @@ var nev = require('email-verification')(mongoose); // NEV setup and configuration ================ var config_nev = function () { - var User = require('../../models/user.server.model'); - - nev.configure({ persistentUserModel: User, tempUserCollection: config.tempUserCollection, @@ -47,37 +40,35 @@ var config_nev = function () { verifySendMailCallback: function(err, info) { if (err) { throw err; - } else { - console.log(info); } } }, function(err, options){ - if(err) throw err; + if(err) { + throw err; + } }); nev.generateTempUserModel(User, function(err){ - if(err) throw err; + if(err) { + throw err; + } }); }; config_nev(); -var smtpTransport = nodemailer.createTransport(config.mailer.options); - exports.validateVerificationToken = function(req, res){ nev.confirmTempUser(req.params.token, function(err, user) { if(err) { - console.log(errorHandler.getErrorMessage(err)); return res.status(500).send( {message: errorHandler.getErrorMessage(err) } ); } else if (user){ return res.status(200).send('User successfully verified'); - }else { - // redirect to resend verification email - return res.status(400).send( {message: 'Verification token is invalid or has expired'} ); } + // redirect to resend verification email + return res.status(400).send( {message: 'Verification token is invalid or has expired'} ); }); }; @@ -114,8 +105,6 @@ exports.signup = function(req, res) { // Then save the temporary user nev.createTempUser(user, function (err, existingPersistentUser, newTempUser) { if (err) { - console.log('Error: '); - console.log(err); return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); @@ -124,20 +113,17 @@ exports.signup = function(req, res) { // new user created if (newTempUser) { var URL = newTempUser[nev.options.URLFieldName]; - nev.sendVerificationEmail(user.email, URL, function (err, info) { - if (err) { + nev.sendVerificationEmail(user.email, URL, function (sendEmailErr, info) { + if (sendEmailErr) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); - } else { - return res.status(200).send('An email has been sent to you. Please check it to verify your account.'); } + return res.status(200).send('An email has been sent to you. Please check it to verify your account.'); }); - } else { - console.log('Error: User already exists!'); - return res.status(400).send({message: 'Error: User already exists!'}); - } + } + return res.status(400).send({message: 'Error: User already exists!'}); }); }; @@ -150,18 +136,17 @@ exports.signin = function(req, res, next) { res.status(400).send(info); } else { // Remove sensitive data before login - user.password = undefined; - user.salt = undefined; - user.provider = undefined; + user.password = null; + user.salt = null; + user.provider = null; - req.login(user, function(err) { - if (err) { + req.login(user, function(loginErr) { + if (loginErr) { return res.status(400).send({ - message: errorHandler.getErrorMessage(err) + message: errorHandler.getErrorMessage(loginErr) }); - } else { - return res.json(user); } + return res.json(user); }); } })(req, res, next); @@ -227,7 +212,7 @@ exports.saveOAuthUserProfile = function(req, providerUserProfile, done) { var possibleUsername = providerUserProfile.username || ((providerUserProfile.email) ? providerUserProfile.email.split('@')[0] : ''); User.findUniqueUsername(possibleUsername, null, function(availableUsername) { - user = new User({ + var newUser = new User({ firstName: providerUserProfile.firstName, lastName: providerUserProfile.lastName, username: availableUsername, @@ -238,13 +223,12 @@ exports.saveOAuthUserProfile = function(req, providerUserProfile, done) { }); // And save the user - user.save(function(err) { - return done(err, user); + newUser.save(function(userSaveErr) { + return done(userSaveErr, user); }); }); - } else { - return done(err, user); } + return done(err, user); } }); } else { @@ -254,7 +238,9 @@ exports.saveOAuthUserProfile = function(req, providerUserProfile, done) { // Check if user exists, is not signed in using this provider, and doesn't have that provider data already configured if (user.provider !== providerUserProfile.provider && (!user.additionalProvidersData || !user.additionalProvidersData[providerUserProfile.provider])) { // Add the provider data to the additional provider data field - if (!user.additionalProvidersData) user.additionalProvidersData = {}; + if (!user.additionalProvidersData) { + user.additionalProvidersData = {}; + } user.additionalProvidersData[providerUserProfile.provider] = providerUserProfile.providerData; // Then tell mongoose that we've updated the additionalProvidersData field @@ -314,8 +300,10 @@ exports.generateAPIKey = function(req, res) { User.findById(req.user.id) .exec( function(err, user) { - if (err) return res.status(400).send(err); - + if (err) { + return res.status(400).send(err); + } + if (!user) { return res.status(400).send({ message: 'User does not Exist' @@ -324,10 +312,10 @@ exports.generateAPIKey = function(req, res) { user.apiKey = tokgen(); - user.save(function(err, _user) { - if (err) { + user.save(function(userSaveErr, _user) { + if (userSaveErr) { return res.status(400).send({ - message: errorHandler.getErrorMessage(err) + message: errorHandler.getErrorMessage(userSaveErr) }); } @@ -337,7 +325,6 @@ exports.generateAPIKey = function(req, res) { delete newUser.passwordHash; delete newUser.provider; - console.log(newUser); return res.json(newUser); }); diff --git a/app/controllers/users/users.password.server.controller.js b/app/controllers/users/users.password.server.controller.js index 0180c59d..f09c42a5 100755 --- a/app/controllers/users/users.password.server.controller.js +++ b/app/controllers/users/users.password.server.controller.js @@ -180,7 +180,6 @@ exports.reset = function(req, res, next) { }); } ], function(err) { - debugger; if (err) { res.status(500).send({ message: err.message || err diff --git a/app/controllers/users/users.profile.server.controller.js b/app/controllers/users/users.profile.server.controller.js index 8c9f238b..71a9dad5 100755 --- a/app/controllers/users/users.profile.server.controller.js +++ b/app/controllers/users/users.profile.server.controller.js @@ -5,9 +5,7 @@ */ var _ = require('lodash'), errorHandler = require('../errors.server.controller.js'), - mongoose = require('mongoose'), - passport = require('passport'), - User = mongoose.model('User'); + mongoose = require('mongoose'); /** * Update user details @@ -15,7 +13,6 @@ var _ = require('lodash'), exports.update = function(req, res) { // Init Variables var user = req.user; - var message = null; // For security measurement we remove the roles from the req.body object delete req.body.roles; @@ -30,15 +27,15 @@ exports.update = function(req, res) { return res.status(500).send({ message: errorHandler.getErrorMessage(err) }); - } else { - req.login(user, function(err) { - if (err) { - res.status(500).send(err); - } else { - res.json(user); - } - }); - } + } + req.login(user, function(loginErr) { + if (err) { + res.status(500).send(loginErr); + } else { + res.json(user); + } + }); + }); } else { res.status(401).send({ diff --git a/app/models/form.server.model.js b/app/models/form.server.model.js index 52d8abb1..52051da8 100644 --- a/app/models/form.server.model.js +++ b/app/models/form.server.model.js @@ -6,21 +6,15 @@ var mongoose = require('mongoose'), Schema = mongoose.Schema, _ = require('lodash'), - config = require('../../config/config'), - path = require('path'), mUtilities = require('mongoose-utilities'), - fs = require('fs-extra'), async = require('async'), - mkdirp = require('mkdirp'), Random = require('random-js'), - mt = Random.engines.mt19937(), - util = require('util'); + mt = Random.engines.mt19937(); mt.autoSeed(); //Mongoose Models var FieldSchema = require('./form_field.server.model.js'); -var Field = mongoose.model('Field'); var FormSubmissionSchema = require('./form_submission.server.model.js'), FormSubmission = mongoose.model('FormSubmission', FormSubmissionSchema); @@ -221,7 +215,10 @@ FormSchema.virtual('analytics.fields').get(function () { var visitors = this.analytics.visitors; var that = this; - if(this.form_fields.length == 0) return null; + if(this.form_fields.length == 0) { + return null; + } + for(var i=0; i should not be able to create a Form if not logged in', function(done) { + it(' > should not be able to create a Form if not logged in', function(done) { userSession.post('/forms') .send({form: myForm}) .expect(401) @@ -285,10 +285,10 @@ describe('Form Routes Unit tests', function() { afterEach(function(done) { Form.remove({}).exec(function() { - User.remove({}).exec(function() { - userSession.destroy(); - done(); - }); + User.remove({}).exec(function() { + userSession.destroy(); + done(); + }); }); }); }); diff --git a/app/tests/user.server.routes.test.js b/app/tests/user.server.routes.test.js index 3b7f6621..7948ed25 100644 --- a/app/tests/user.server.routes.test.js +++ b/app/tests/user.server.routes.test.js @@ -1,9 +1,7 @@ 'use strict'; var should = require('should'), - _ = require('lodash'), app = require('../../server'), - request = require('supertest'), Session = require('supertest-session'), mongoose = require('mongoose'), User = mongoose.model('User'), @@ -13,11 +11,7 @@ var should = require('should'), /** * Globals */ -var credentials, _User; -var _tmpUser, activateToken; -var username, userSession; - -username = 'testActiveAccount1.be1e58fb@mailosaur.in'; +var credentials, _User, activateToken, userSession; /** * Form routes tests @@ -50,7 +44,7 @@ describe('User CRUD tests', function() { userSession.post('/auth/signup') .send(_User) .expect(200) - .end(function(FormSaveErr, FormSaveRes) { + .end(function(FormSaveErr) { console.log('CREATING USER'); // Handle error should.not.exist(FormSaveErr); @@ -58,7 +52,6 @@ describe('User CRUD tests', function() { tmpUser.findOne({username: _User.username}, function (err, user) { should.not.exist(err); should.exist(user); - _tmpUser = user; _User.username.should.equal(user.username); _User.firstName.should.equal(user.firstName); @@ -69,7 +62,10 @@ describe('User CRUD tests', function() { .expect(200) .end(function(VerifyErr, VerifyRes) { // Handle error - if (VerifyErr) return done(VerifyErr); + if (VerifyErr) { + return done(VerifyErr); + } + (VerifyRes.text).should.equal('User successfully verified'); userSession.post('/auth/signin') @@ -78,7 +74,9 @@ describe('User CRUD tests', function() { .expect(200) .end(function(signinErr, signinRes) { // Handle signin error - if (signinErr) return done(signinErr); + if (signinErr) { + return done(signinErr); + } var user = signinRes.body; (user.username).should.equal(credentials.username); @@ -88,7 +86,9 @@ describe('User CRUD tests', function() { .end(function(signoutErr, signoutRes) { // Handle signout error - if (signoutErr) return done(signoutErr); + if (signoutErr) { + return done(signoutErr); + } (signoutRes.text).should.equal('You have successfully logged out.'); @@ -101,12 +101,12 @@ describe('User CRUD tests', function() { }); }); - + afterEach(function(done) { User.remove().exec(function () { tmpUser.remove().exec(function(){ - userSession.destroy(); - done(); + userSession.destroy(); + done(); }); }); }); diff --git a/config/config.js b/config/config.js index 69daa792..e085589c 100755 --- a/config/config.js +++ b/config/config.js @@ -73,17 +73,41 @@ module.exports.getBowerOtherAssets = function() { }; /** - * Get the modules JavaScript files + * Helper Function for getJavascriptAssets and getFormJavaScriptAssets */ -module.exports.getJavaScriptAssets = function(includeTests) { - var output = this.getGlobbedFiles(this.assets.js, 'public/', 'static/'); +module.exports._getAssets = function(includeTests, isFormJS){ + var unit_tests, js_assets; + + if(isFormJS) { + js_assets = this.assets.form_js; + unit_tests = this.assets.form_unit_tests; + } else { + js_assets = this.assets.js; + unit_tests = this.assets.unit_tests; + } + + var output = this.getGlobbedFiles(js_assets, 'public/', 'static/'); // To include tests if (includeTests) { - output = _.union(output, this.getGlobbedFiles(this.assets.unit_tests)); + output = _.union(output, this.getGlobbedFiles(unit_tests)); } return output; +} + +/** + * Get the modules JavaScript files + */ +module.exports.getJavaScriptAssets = function(includeTests) { + return this._getAssets(includeTests, false); +}; + +/** + * Get the modules Form JavaScript files + */ +module.exports.getFormJavaScriptAssets = function(includeTests) { + return this._getAssets(includeTests, true); }; /** @@ -93,17 +117,3 @@ module.exports.getCSSAssets = function() { var output = this.getGlobbedFiles(this.assets.css, 'public/', 'static/'); return output; }; - -/** - * Get the modules Form JavaScript files - */ -module.exports.getFormJavaScriptAssets = function(includeTests) { - var output = this.getGlobbedFiles(this.assets.form_js, 'public/', 'static/'); - - // To include tests - if (includeTests) { - output = _.union(output, this.getGlobbedFiles(this.assets.form_unit_tests)); - } - - return output; -}; diff --git a/config/express.js b/config/express.js index e9cffe7a..2719f01d 100755 --- a/config/express.js +++ b/config/express.js @@ -4,7 +4,6 @@ * Module dependencies. */ var fs = require('fs-extra'), - http = require('http'), https = require('https'), express = require('express'), morgan = require('morgan'), @@ -15,7 +14,6 @@ var fs = require('fs-extra'), methodOverride = require('method-override'), cookieParser = require('cookie-parser'), helmet = require('helmet'), - multer = require('multer'), passport = require('passport'), raven = require('raven'), MongoStore = require('connect-mongo')(session), @@ -24,8 +22,7 @@ var fs = require('fs-extra'), consolidate = require('consolidate'), path = require('path'), device = require('express-device'), - client = new raven.Client(config.DSN), - connect = require('connect'); + client = new raven.Client(config.DSN); var mongoose = require('mongoose'); @@ -79,24 +76,25 @@ module.exports = function(db) { app.locals.cssFiles = config.getCSSAssets(); app.use(function (req, res, next) { - + var urlPath; if(!config.subdomainsDisabled) { var User = mongoose.model('User'); - var path = '/' + 'subdomain' + '/'; + var subdomainPath = '/subdomain/'; var subdomains = req.subdomains; - var host = req.hostname; if (subdomains.slice(0, 4).join('.') + '' === '1.0.0.127') { subdomains = subdomains.slice(4); } // continue if no subdomains - if (!subdomains.length) return next(); - - var urlPath = url.parse(req.url).path.split('/'); + if (!subdomains.length) { + return next(); + } + + urlPath = url.parse(req.url).path.split('/'); if (urlPath.indexOf('static') > -1) { urlPath.splice(1, 1); - if(process.env.NODE_ENV == 'development'){ + if(process.env.NODE_ENV === 'development'){ req.root = req.protocol + '://' + config.baseUrl + ':' + config.port + urlPath.join('/'); } else { req.root = req.protocol + '://' + config.baseUrl + urlPath.join('/'); @@ -114,17 +112,16 @@ module.exports = function(db) { if (subdomains.indexOf('api') > -1) { // rebuild url - path += 'api' + req.url; + subdomainPath += 'api' + req.url; // TODO: check path and query strings are preserved // reassign url - req.url = path; + req.url = subdomainPath; return next(); } User.findOne({username: req.subdomains.reverse()[0]}).exec(function (err, user) { if (err) { - console.log(err); req.subdomains = null; // Error page return res.status(404).render('404', { @@ -139,26 +136,23 @@ module.exports = function(db) { } // rebuild url - path += subdomains.join('/') + req.url; + subdomainPath += subdomains.join('/') + req.url; // TODO: check path and query strings are preserved // reassign url - req.url = path; + req.url = subdomainPath; req.userId = user._id; // Q.E.D. - next(); + return next(); }); } else { - var urlPath = url.parse(req.url).path.split('/'); + urlPath = url.parse(req.url).path.split('/'); if (urlPath.indexOf('static') > -1 && urlPath.indexOf('view') === urlPath.indexOf('static')-1) { urlPath.splice(1, 1); req.url = urlPath.join('/'); - - console.log('\n\n\nreq.url: ' + req.url); - return next(); } return next(); @@ -293,10 +287,11 @@ module.exports = function(db) { // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use(function(err, req, res, next) { // If the error object doesn't exists - if (!err) return next(); - + if (!err) { + return next(); + } + // Log it - console.error(err.stack); client.captureError(err); // Error page diff --git a/config/socket.io.js b/config/socket.io.js index 5b92a353..4725b3c6 100644 --- a/config/socket.io.js +++ b/config/socket.io.js @@ -12,7 +12,6 @@ module.exports = function (app, db) { var io = socketio({ transports: ['websocket', 'polling'] }); if(config.socketPort){ - console.log("creating websocket server on port: "+config.socketPort); io = socketio(config.socketPort, { transports: ['websocket', 'polling'] }); } diff --git a/gruntfile.js b/gruntfile.js index 7d1c71f5..405e1262 100755 --- a/gruntfile.js +++ b/gruntfile.js @@ -1,73 +1,5 @@ 'use strict'; -var spawn = require('child_process').spawn; -var bowerFiles = require('main-bower-files'); -var path = require('path'); -var minBowerFiles = function(type){ - return bowerFiles(type).map( function(path, index, arr) { - var newPath = path.replace(/.([^.]+)$/g, '.min.$1'); - return exists( newPath ) ? newPath : path; - }); -}; - -var removeRootDir = function(files, removeRoot, addRoot) { - return files.map(function(file) { - if (addRoot) return file.replace(path.join(process.cwd(), removeRoot), addRoot); - return file.replace(path.join(process.cwd(), removeRoot), ''); - }); -}; - -var allBowerFiles = bowerFiles({ - filter: function(filePath){ - return (filePath.indexOf('js') > 0 && filePath.indexOf('angular-ui-utils') === -1); - } -}); - -var bowerAllArray = ['public/lib/angular/angular.js', - 'public/lib/angular-ui-select/dist/select.js', - 'public/lib/v-button/dist/v-button.js', - 'public/lib/angular-ui-scroll/dist/ui-scroll.js', - 'public/lib/angular-resource/angular-resource.js', - 'public/lib/angular-ui-router/release/angular-ui-router.js', - 'public/lib/angular-sanitize/angular-sanitize.js', - 'public/lib/angular-input-stars/angular-input-stars.js', - 'public/lib/ng-file-upload/ng-file-upload.js', - 'public/lib/angular-mocks/angular-mocks.js', - 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', - 'public/lib/angular-ui-scrollpoint/dist/scrollpoint.js', - 'public/lib/angular-ui-event/dist/event.js', - 'public/lib/angular-ui-mask/dist/mask.js', - 'public/lib/angular-ui-validate/dist/validate.js', - 'public/lib/angular-ui-indeterminate/dist/indeterminate.js', - 'public/lib/angular-ui-uploader/dist/uploader.js', - 'public/lib/raven-js/dist/raven.js', - 'public/lib/jquery-ui/jquery-ui.js', - 'public/lib/lodash/lodash.js', - 'public/lib/angular-ui-sortable/sortable.js', - 'public/lib/angular-permission/dist/angular-permission.js', - 'public/lib/file-saver.js/FileSaver.js', - 'public/lib/angular-bootstrap-colorpicker/js/bootstrap-colorpicker-module.js', - 'public/lib/angular-ui-router-tabs/src/ui-router-tabs.js', - 'public/lib/angular-scroll/angular-scroll.js', - 'public/lib/angular-animate/angular-animate.js', - 'public/lib/file-saver/FileSaver.js', - 'public/lib/html2canvas/build/html2canvas.js', - 'public/lib/jspdf/dist/jspdf.min.js', - 'public/lib/jspdf-autotable/dist/jspdf.plugin.autotable.js', - 'public/lib/angular-translate/angular-translate.js', - 'public/lib/deep-diff/index.js', - 'public/lib/jsep/build/jsep.js', - 'public/lib/clipboard/dist/clipboard.js', - 'public/lib/mobile-detect/mobile-detect.js', - 'public/lib/angular-strap/dist/angular-strap.js', - 'public/lib/angular-strap/dist/angular-strap.tpl.js', - 'public/lib/bootstrap/dist/js/bootstrap.js', - 'public/lib/angular-ui-utils/index.js', - 'public/lib/angular-raven/angular-raven.js', - 'public/lib/angular-ui-date/src/date.js', - 'public/lib/angular-busy/dist/angular-busy.js', - 'public/lib/tableExport.jquery.plugin/tableExport.min.js', - 'public/lib/ngclipboard/dist/ngclipboard.js' ]; var bowerArray = ['public/lib/angular/angular.min.js', 'public/lib/angular-scroll/angular-scroll.min.js', 'public/lib/angular-ui-select/dist/select.min.js', @@ -85,16 +17,6 @@ var bowerArray = ['public/lib/angular/angular.min.js', 'public/lib/mobile-detect/mobile-detect.js', 'public/lib/js-yaml/dist/js-yaml.js', 'public/lib/angular-sanitize/angular-sanitize.min.js']; -/* - - - - - - 'public/lib/bootstrap/dist/js/bootstrap.js', - 'public/lib/angular-raven/angular-raven.js', - 'public/lib/angular-busy/dist/angular-busy.js']; -*/ module.exports = function(grunt) { require('jit-grunt')(grunt); @@ -407,20 +329,21 @@ module.exports = function(grunt) { grunt.option('force', true); // A Task for loading the configuration object - grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() { - var init = require('./config/init')(); + /*grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() { + require('./config/init')(); var config = require('./config/config'); + console.log(config); grunt.config.set('applicationJavaScriptFiles', config.assets.js); grunt.config.set('formApplicationJavaScriptFiles', config.assets.form_js); grunt.config.set('applicationCSSFiles', config.assets.css); - }); + });*/ // Code coverage tasks. grunt.registerTask('coveralls', ['env:test','mocha_istanbul:coveralls']); - grunt.registerTask('coverage', ['env:test', 'mocha_istanbul:coverage']); - grunt.registerTask('coverage:client', ['env:test', 'mocha_istanbul:coverageClient']); - grunt.registerTask('coverage:server', ['env:test', 'mocha_istanbul:coverageServer']); + grunt.registerTask('coverage', ['env:test', 'mocha_istanbul:coverage']); + grunt.registerTask('coverage:client', ['env:test', 'mocha_istanbul:coverageClient']); + grunt.registerTask('coverage:server', ['env:test', 'mocha_istanbul:coverageServer']); // Default task(s). grunt.registerTask('default', ['lint', 'html2js:main', 'html2js:forms', 'env', 'concurrent:default']); diff --git a/public/config.js b/public/config.js index de3e7f7a..bc0a2fee 100755 --- a/public/config.js +++ b/public/config.js @@ -1,7 +1,7 @@ 'use strict'; // Init the application configuration module for AngularJS application -var ApplicationConfiguration = (function() { +(function() { // Init module configuration options var applicationModuleName = 'NodeForm'; var applicationModuleVendorDependencies = ['duScroll', 'ui.select', 'cgBusy', 'ngSanitize', 'vButton', 'ngResource', 'TellForm.templates', 'ui.router', 'ui.bootstrap', 'ui.utils', 'pascalprecht.translate']; diff --git a/public/form_modules/forms/base/directives/submit-form.client.directive.js b/public/form_modules/forms/base/directives/submit-form.client.directive.js index e1989df6..d1c043c1 100644 --- a/public/form_modules/forms/base/directives/submit-form.client.directive.js +++ b/public/form_modules/forms/base/directives/submit-form.client.directive.js @@ -9,33 +9,6 @@ jsep.addBinaryOp("!begins", 10); jsep.addBinaryOp("ends", 10); jsep.addBinaryOp("!ends", 10); -/** - * Calculate a 32 bit FNV-1a hash - * Found here: https://gist.github.com/vaiorabbit/5657561 - * Ref.: http://isthe.com/chongo/tech/comp/fnv/ - * - * @param {string} str the input value - * @param {boolean} [asString=false] set to true to return the hash value as - * 8-digit hex string instead of an integer - * @param {integer} [seed] optionally pass the hash of the previous chunk - * @returns {integer | string} - */ -function hashFnv32a(str, asString, seed) { - /*jshint bitwise:false */ - var i, l, - hval = (seed === undefined) ? 0x811c9dc5 : seed; - - for (i = 0, l = str.length; i < l; i++) { - hval ^= str.charCodeAt(i); - hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); - } - if( asString ){ - // Convert to 8 digit hex string - return ("0000000" + (hval >>> 0).toString(16)).substr(-8); - } - return hval >>> 0; -} - angular.module('view-form').directive('submitFormDirective', ['$http', 'TimeCounter', '$filter', '$rootScope', 'SendVisitorData', function ($http, TimeCounter, $filter, $rootScope, SendVisitorData) { return { @@ -136,7 +109,7 @@ angular.module('view-form').directive('submitFormDirective', ['$http', 'TimeCoun if(parse_tree.left.name === 'field'){ left = field.fieldValue; - right = logicJump.valueB + right = logicJump.valueB; } else { left = logicJump.valueB; right = field.fieldValue; @@ -192,9 +165,9 @@ angular.module('view-form').directive('submitFormDirective', ['$http', 'TimeCoun if($scope.selected._id === 'submit_field') { return $scope.myform.form_fields.length - 1; - } else { - return $scope.selected.index; } + return $scope.selected.index; + }; $scope.setActiveField = $rootScope.setActiveField = function(field_id, field_index, animateScroll) { @@ -212,7 +185,7 @@ angular.module('view-form').directive('submitFormDirective', ['$http', 'TimeCoun if(!field_index){ for(var i=0; i<$scope.myform.visible_form_fields.length; i++){ var currField = $scope.myform.visible_form_fields[i]; - if(field_id == currField._id){ + if(field_id === currField._id){ $scope.selected.index = i; break; } @@ -319,7 +292,7 @@ angular.module('view-form').directive('submitFormDirective', ['$http', 'TimeCoun return { type: deviceType, name: window.navigator.platform - } + }; }; var getIpAndGeo = function(){ @@ -364,7 +337,7 @@ angular.module('view-form').directive('submitFormDirective', ['$http', 'TimeCoun setTimeout(function () { $scope.submitPromise = $http.post('/forms/' + $scope.myform._id, form) - .success(function (data, status, headers) { + .success(function (data, status) { $scope.myform.submitted = true; $scope.loading = false; SendVisitorData.send($scope.myform, getActiveField(), _timeElapsed); @@ -378,7 +351,7 @@ angular.module('view-form').directive('submitFormDirective', ['$http', 'TimeCoun }; //Reload our form - $scope.reloadForm(); + $scope.reloadForm(); } }; } diff --git a/public/form_modules/forms/base/services/time-counter.client.service.js b/public/form_modules/forms/base/services/time-counter.client.service.js index bf2f63b8..57c42680 100644 --- a/public/form_modules/forms/base/services/time-counter.client.service.js +++ b/public/form_modules/forms/base/services/time-counter.client.service.js @@ -2,7 +2,7 @@ angular.module('view-form').service('TimeCounter', [ function(){ - var _startTime, _endTime = null, that=this; + var _startTime, _endTime = null; this.timeSpent = 0; @@ -25,9 +25,8 @@ angular.module('view-form').service('TimeCounter', [ this._startTime = this._endTime = null; return this.timeSpent; - }else{ - return new Error('Clock has not been started'); } + return new Error('Clock has not been started'); }; this.clockStarted = function(){ diff --git a/public/modules/core/services/menus.client.service.js b/public/modules/core/services/menus.client.service.js index 6aa96923..4ed5879d 100755 --- a/public/modules/core/services/menus.client.service.js +++ b/public/modules/core/services/menus.client.service.js @@ -15,22 +15,18 @@ angular.module('core').service('Menus', [ if (user) { if (~this.roles.indexOf('*')) { return true; - } else { - for (var userRoleIndex in user.roles) { - for (var roleIndex in this.roles) { - console.log(this.roles[roleIndex]); - console.log( this.roles[roleIndex] === user.roles[userRoleIndex]); - if (this.roles[roleIndex] === user.roles[userRoleIndex]) { - return true; - } + } + for (var userRoleIndex in user.roles) { + for (var roleIndex in this.roles) { + if (this.roles[roleIndex] === user.roles[userRoleIndex]) { + return true; } } } - } else { - return this.isPublic; - } + return false; - return false; + } + return this.isPublic; }; // Validate menu existance diff --git a/public/modules/core/services/subdomain.client.service.js b/public/modules/core/services/subdomain.client.service.js index eaa9c90b..39b7b048 100644 --- a/public/modules/core/services/subdomain.client.service.js +++ b/public/modules/core/services/subdomain.client.service.js @@ -2,8 +2,8 @@ angular.module('core').factory('subdomain', ['$location', function ($location) { var host = $location.host(); - if (host.indexOf('.') < 0) + if (host.indexOf('.') < 0) { return null; - else - return host.split('.')[0]; + } + return host.split('.')[0]; }]); diff --git a/public/modules/core/tests/unit/controllers/home.client.controller.test.js b/public/modules/core/tests/unit/controllers/home.client.controller.test.js index 002352d5..178f4ba8 100755 --- a/public/modules/core/tests/unit/controllers/home.client.controller.test.js +++ b/public/modules/core/tests/unit/controllers/home.client.controller.test.js @@ -3,8 +3,7 @@ (function() { describe('HomeController', function() { //Initialize global variables - var scope, - HomeController; + var scope; // Load the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); @@ -12,7 +11,7 @@ beforeEach(inject(function($controller, $rootScope) { scope = $rootScope.$new(); - HomeController = $controller('HomeController', { + $controller('HomeController', { $scope: scope }); })); diff --git a/public/modules/forms/admin/directives/auto-save.client.directive.js b/public/modules/forms/admin/directives/auto-save.client.directive.js deleted file mode 100644 index 70649b2d..00000000 --- a/public/modules/forms/admin/directives/auto-save.client.directive.js +++ /dev/null @@ -1,139 +0,0 @@ -'use strict'; - -function removeDateFieldsFunc(o) { - var clone = _.clone(o); - function eachObject(v,k){ - - if(k === 'lastModified' || k === 'created'){ - delete clone[k]; - } - } - - for(var i=0; i 0; - - //If our form's startPage or form fields have not changed, don't autosave form - if(!changedFields){ - $rootScope.finishedRender = true; - return; - } - - if(oldValue.form_fields.length === 0) { - $rootScope.finishedRender = true; - } - - console.log('Autosaving'); - console.log('\n\n----------'); - console.log('$dirty: '+ $formCtrl.$dirty ); - - // console.log('changedFieldMap: '+changedFieldMap); - // console.log('finishedRender: '+$rootScope.finishedRender); - // console.log('!saveInProgress: '+!$rootScope.saveInProgress); - // console.log('newValue: '+newValue); - // console.log('oldValue: '+oldValue); - // console.log(oldValue.form_fields); - // console.log(newValue.form_fields); - - //Save form ONLY IF rendering is finished, form_fields have been changed AND currently not save in progress - if($rootScope.finishedRender && (changedFields) && !$rootScope.saveInProgress) { - - if(savePromise) { - $timeout.cancel(savePromise); - savePromise = null; - } - - savePromise = $timeout(function() { - $rootScope.saveInProgress = true; - - var _diff = DeepDiff.diff(oldValue, newValue); - debounceSave(_diff); - }); - } - //If we are finished rendering then form saving should be finished - else if($rootScope.finishedRender && $rootScope.saveInProgress){ - $rootScope.saveInProgress = false; - } - - }, true); - }); - } - }; - -}]); diff --git a/public/modules/forms/admin/directives/edit-submissions-form.client.directive.js b/public/modules/forms/admin/directives/edit-submissions-form.client.directive.js index 65d5e2ca..9f2b841c 100644 --- a/public/modules/forms/admin/directives/edit-submissions-form.client.directive.js +++ b/public/modules/forms/admin/directives/edit-submissions-form.client.directive.js @@ -7,7 +7,7 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope', restrict: 'E', scope: { user:'=', - myform: '=' + myform: '=' }, controller: function($scope){ @@ -48,11 +48,13 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope', var totalTime = 0; var numSubmissions = $scope.table.rows.length; - for(var i=0; i<$scope.table.rows.length; i++){ + for(i=0; i<$scope.table.rows.length; i++){ totalTime += $scope.table.rows[i].timeElapsed; } - if(numSubmissions == 0) return 0; + if(numSubmissions === 0) { + return 0; + } return (totalTime/numSubmissions).toFixed(0); })(); @@ -77,7 +79,7 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope', if($scope.myform.analytics && $scope.myform.analytics.visitors) { var visitors = $scope.myform.analytics.visitors; - for (var i = 0; i < visitors.length; i++) { + for (i = 0; i < visitors.length; i++) { var visitor = visitors[i]; var deviceType = visitor.deviceType; @@ -86,12 +88,18 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope', stats[deviceType].total_time = stats[deviceType].total_time + visitor.timeElapsed; stats[deviceType].average_time = (stats[deviceType].total_time / stats[deviceType].visits).toFixed(0); - if(!stats[deviceType].average_time) stats[deviceType].average_time = 0; - - if (visitor.isSubmitted) stats[deviceType].responses++; + if(!stats[deviceType].average_time) { + stats[deviceType].average_time = 0; + } + + if (visitor.isSubmitted) { + stats[deviceType].responses++; + } stats[deviceType].completion = (stats[deviceType].responses / stats[deviceType].visits).toFixed(0); - if(!stats[deviceType].completion) stats[deviceType].completion = 0; + if(!stats[deviceType].completion) { + stats[deviceType].completion = 0; + } } } diff --git a/public/modules/forms/admin/views/directiveViews/form/edit-form.client.view.html b/public/modules/forms/admin/views/directiveViews/form/edit-form.client.view.html index 07f26093..ec8be8ee 100644 --- a/public/modules/forms/admin/views/directiveViews/form/edit-form.client.view.html +++ b/public/modules/forms/admin/views/directiveViews/form/edit-form.client.view.html @@ -1,4 +1,4 @@ -
+