diff --git a/app/controllers/forms.server.controller.js b/app/controllers/forms.server.controller.js index 24f9a8d1..5da1310a 100644 --- a/app/controllers/forms.server.controller.js +++ b/app/controllers/forms.server.controller.js @@ -15,7 +15,7 @@ var mongoose = require('mongoose'), _ = require('lodash'); /** - * Upload PDF + * Upload PDF */ exports.uploadPDF = function(req, res, next) { @@ -24,7 +24,7 @@ exports.uploadPDF = function(req, res, next) { // console.log(req.files.file); // console.log('\n\nProperty Descriptor\n-----------'); // console.log(Object.getOwnPropertyDescriptor(req.files.file, 'path')); - + if(req.file){ var pdfFile = req.file; var _user = req.user; @@ -33,9 +33,9 @@ exports.uploadPDF = function(req, res, next) { }else if(req.files.size > 200000000){ next(new Error('File uploaded exceeds MAX SIZE of 200MB')); }else { - fs.exists(pdfFile.path, function(exists) { + fs.exists(pdfFile.path, function(exists) { //If file exists move to user's tmp directory - if(exists) { + if(exists) { var newDestination = config.tmpUploadPath+_user.username; var stat = null; @@ -48,7 +48,7 @@ exports.uploadPDF = function(req, res, next) { console.log('Directory cannot be created'); next(new Error('Directory cannot be created because an inode of a different type exists at "' + newDestination + '"')); } - + fs.move(pdfFile.path, path.join(newDestination, pdfFile.name), function (err) { if (err) { next(new Error(err.message)); @@ -56,12 +56,12 @@ exports.uploadPDF = function(req, res, next) { pdfFile.path = path.join(newDestination, pdfFile.name); console.log(pdfFile.name + ' uploaded to ' + pdfFile.path); res.json(pdfFile); - }); + }); - } else { + } else { next(new Error('Did NOT get your file!')); - } - }); + } + }); } }else { next(new Error('Uploaded files were NOT detected')); @@ -78,7 +78,7 @@ exports.deleteSubmissions = function(req, res) { form = req.form; FormSubmission.remove({ form: req.form, admin: req.user, _id: {$in: submission_id_list} }, function(err){ - + if(err){ res.status(400).send({ message: errorHandler.getErrorMessage(err) @@ -134,7 +134,7 @@ exports.createSubmission = function(req, res) { } submission.save(function(err, submission){ - // console.log('in submissions.save()\n submission: '+JSON.stringify(submission) ) + // console.log('in submissions.save()\n submission: '+JSON.stringify(submission) ) if(err){ console.log(err.message); res.status(400).send({ @@ -167,10 +167,10 @@ exports.listSubmissions = function(req, res) { res.status(400).send({ message: errorHandler.getErrorMessage(err) }); - } + } res.json(_submissions); }); - + }); }; @@ -213,7 +213,7 @@ exports.read = function(req, res) { /** * Update a form */ -exports.update = function(req, res) { +exports.update = function(req, res) { var form = req.form; delete req.body.form.__v; delete req.body.form._id; @@ -229,9 +229,9 @@ exports.update = function(req, res) { delete field._id; } } - + form = _.extend(form, req.body.form); - + form.save(function(err, form) { if (err) { console.log(err); @@ -306,7 +306,7 @@ exports.formByID = function(req, res, next, id) { form.admin.password = undefined; form.admin.salt = undefined; form.provider = undefined; - + req.form = form; next(); } @@ -318,7 +318,6 @@ exports.formByID = function(req, res, next, id) { * Form authorization middleware */ exports.hasAuthorization = function(req, res, next) { - var form = req.form; if (req.form.admin.id !== req.user.id && req.user.roles.indexOf('admin') === -1) { res.status(403).send({ diff --git a/app/controllers/users/users.authentication.server.controller.js b/app/controllers/users/users.authentication.server.controller.js index 1850cc1f..71050860 100755 --- a/app/controllers/users/users.authentication.server.controller.js +++ b/app/controllers/users/users.authentication.server.controller.js @@ -93,7 +93,6 @@ exports.resendVerificationEmail = function(req, res, next){ * Signup */ exports.signup = function(req, res) { - console.log(req.body); // For security measures we remove the roles from the req.body object if (req.body) { delete req.body.roles; @@ -127,7 +126,6 @@ exports.signup = function(req, res) { message: errorHandler.getErrorMessage(err) }); } else { - console.log('new tmpuser registered'); return res.status(200).send('An email has been sent to you. Please check it to verify your account.'); } }); @@ -146,7 +144,6 @@ exports.signup = function(req, res) { * Signin after passport authentication */ exports.signin = function(req, res, next) { - console.log(req); passport.authenticate('local', function(err, user, info) { if (err || !user) { res.status(400).send(info); @@ -174,8 +171,9 @@ exports.signin = function(req, res, next) { */ exports.signout = function(req, res) { req.logout(); - res.redirect('/'); - return res.end(); + //res.redirect('/'); + return res.status(200).send('You have successfully logged out.'); + }; /** diff --git a/app/controllers/users/users.authorization.server.controller.js b/app/controllers/users/users.authorization.server.controller.js index 683fdd8f..0926bd36 100755 --- a/app/controllers/users/users.authorization.server.controller.js +++ b/app/controllers/users/users.authorization.server.controller.js @@ -36,10 +36,11 @@ exports.userByID = function (req, res, next, id) { */ exports.requiresLogin = function(req, res, next) { if (!req.isAuthenticated()) { + console.log('\n\nSENDING 401 STATUS\n\n'); return res.status(401).send({ message: 'User is not logged in' }); - }else { + } else { return next(); } }; diff --git a/app/models/form.server.model.js b/app/models/form.server.model.js index f340e6d6..354ae895 100644 --- a/app/models/form.server.model.js +++ b/app/models/form.server.model.js @@ -58,10 +58,10 @@ var FormSchema = new Schema({ }, description: { type: String, - default: '', + default: '' }, form_fields: { - type: [FieldSchema], + type: [FieldSchema] }, submissions: [{ @@ -92,46 +92,46 @@ var FormSchema = new Schema({ default: 'Welcome to Form' }, introParagraph:{ - type: String, + type: String }, buttons:[ButtonSchema] }, hideFooter: { type: Boolean, - default: false, + default: false }, isGenerated: { type: Boolean, - default: false, + default: false }, isLive: { type: Boolean, - default: false, + default: false }, autofillPDFs: { type: Boolean, - default: false, + default: false }, design: { colors:{ - backgroundColor: { + backgroundColor: { type: String, match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/], default: '#fff' }, - questionColor: { + questionColor: { type: String, match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/], default: '#333', }, - answerColor: { + answerColor: { type: String, match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/], default: '#333', }, - buttonColor: { + buttonColor: { type: String, match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/] }, @@ -369,7 +369,7 @@ FormSchema.pre('save', function (next) { //console.log('field has been deleted: '); //console.log(this.isModified('form_fields') && !!this.form_fields && !!_original); - if(this.isModified('form_fields') && this.form_fields.length >= 0 && _original){ + if(this.isModified('form_fields') && this.form_fields && _original){ var old_form_fields = _original.form_fields, new_ids = _.map(_.pluck(this.form_fields, '_id'), function(id){ return ''+id;}), @@ -389,9 +389,9 @@ FormSchema.pre('save', function (next) { var modifiedSubmissions = []; - async.forEachOfSeries(deletedIds, + async.forEachOfSeries(deletedIds, function (deletedIdIndex, key, callback) { - + var deleted_id = old_ids[deletedIdIndex]; //Find FormSubmissions that contain field with _id equal to 'deleted_id' @@ -407,14 +407,14 @@ FormSchema.pre('save', function (next) { if(submissions.length) { // console.log('adding submissions'); // console.log(submissions); - //Add submissions + //Add submissions modifiedSubmissions.push.apply(modifiedSubmissions, submissions); } callback(null); }); // } - }, + }, function (err) { if(err){ console.error(err.message); @@ -431,7 +431,7 @@ FormSchema.pre('save', function (next) { for(var i = 0; i < deletedIds.length; i++){ //Get index of deleted field - var index = _.findIndex(submission.form_fields, function(field) { + var index = _.findIndex(submission.form_fields, function(field) { var tmp_id = field._id+''; return tmp_id === old_ids[ deletedIds[i] ]; }); @@ -458,7 +458,7 @@ FormSchema.pre('save', function (next) { submission.save(function (err) { if(err) callback(err); else callback(null); - }); + }); }, function (err) { if(err){ console.error(err.message); diff --git a/app/models/user.server.model.js b/app/models/user.server.model.js index 7b72fced..898f995a 100755 --- a/app/models/user.server.model.js +++ b/app/models/user.server.model.js @@ -15,7 +15,14 @@ var mongoose = require('mongoose'), * A Validation function for local strategy properties */ var validateLocalStrategyProperty = function(property) { - return ((this.provider !== 'local' && !this.updated) || property.length); + var propHasLength; + if (property) { + propHasLength = !!property.length; + } else { + propHasLength = false; + } + + return ((this.provider !== 'local' && !this.updated) || propHasLength); }; /** @@ -34,9 +41,7 @@ var UserSchema = new Schema({ trim: true, default: '', validate: { - validator: function(property) { - return ((this.provider !== 'local' && !this.updated) || property.length); - }, + validator: validateLocalStrategyProperty, message: 'Please fill in your first name' } }, @@ -45,10 +50,7 @@ var UserSchema = new Schema({ trim: true, default: '', validate: { - validator: function(property) { - console.log(property); - return ((this.provider !== 'local' && !this.updated) || property.length); - }, + validator: validateLocalStrategyProperty, message: 'Please fill in your last name' } }, @@ -58,16 +60,7 @@ var UserSchema = new Schema({ unique: 'Account already exists with this email', required: 'Please enter your email', validate: { - validator: function(property) { - var propHasLength; - if (property) { - propHasLength = !!property.length; - } else { - propHasLength = false; - } - - return ((this.provider !== 'local' && !this.updated) || propHasLength); - }, + validator: validateLocalStrategyProperty, message: 'Please fill in your email' }, match: [/.+\@.+\..+/, 'Please fill a valid email address'] diff --git a/app/routes/forms.server.routes.js b/app/routes/forms.server.routes.js index 0b4b20de..3f59e752 100644 --- a/app/routes/forms.server.routes.js +++ b/app/routes/forms.server.routes.js @@ -38,7 +38,7 @@ module.exports = function(app) { .delete(users.requiresLogin, forms.hasAuthorization, forms.delete); app.route('/forms/:formId([a-zA-Z0-9]+)/submissions') - .get(forms.listSubmissions, users.requiresLogin, forms.hasAuthorization) + .get(users.requiresLogin, forms.hasAuthorization, forms.listSubmissions) .delete(users.requiresLogin, forms.hasAuthorization, forms.deleteSubmissions); // Finish by binding the form middleware diff --git a/app/tests/form.server.model.test.js b/app/tests/form.server.model.test.js index 4d4d009d..4da41857 100644 --- a/app/tests/form.server.model.test.js +++ b/app/tests/form.server.model.test.js @@ -1,137 +1,137 @@ -// 'use strict'; +'use strict'; -// /** -// * Module dependencies. -// */ -// var should = require('should'), -// mongoose = require('mongoose'), -// User = mongoose.model('User'), -// Form = mongoose.model('Form'), -// Field = mongoose.model('Field'), -// _ = require('lodash'), -// config = require('../../config/config'), -// FormSubmission = mongoose.model('FormSubmission'); +/** + * Module dependencies. + */ +var should = require('should'), + mongoose = require('mongoose'), + User = mongoose.model('User'), + Form = mongoose.model('Form'), + Field = mongoose.model('Field'), + _ = require('lodash'), + config = require('../../config/config'), + FormSubmission = mongoose.model('FormSubmission'); -// var exampleDemo = { -// activeCount: 1, -// DOB: '', -// address: '880-9650 Velit. St.', -// chartNo: '', -// city: '', -// dateJoined: Date.now(), -// dateOfBirth: '10', -// displayName: 'LITTLE, URIAH', -// email: '', -// familyDoctor: '', -// firstName: 'Uriah F.', -// hcType: 'BC', -// hin: '', -// hsAlertCount: 0, -// lastName: 'Little', -// lastUpdateDate: Date.now(), -// lastUpdateUser: '', -// links: '', -// monthOfBirth: '05', -// officialLanguage: 'English', -// patientStatus: 'AC', -// patientStatusDate: Date.now(), -// phone: '250-', -// phone2: '', -// postal: 'S4M 7T8', -// providerNo: '4', -// province: 'BC', -// rosterStatus: '', -// sex: 'M', -// sexDesc: 'Female', -// sin: '', -// spokenLanguage: 'English', -// title: 'MS.', -// yearOfBirth: '2015' -// }; +var exampleDemo = { + activeCount: 1, + DOB: '', + address: '880-9650 Velit. St.', + chartNo: '', + city: '', + dateJoined: Date.now(), + dateOfBirth: '10', + displayName: 'LITTLE, URIAH', + email: '', + familyDoctor: '', + firstName: 'Uriah F.', + hcType: 'BC', + hin: '', + hsAlertCount: 0, + lastName: 'Little', + lastUpdateDate: Date.now(), + lastUpdateUser: '', + links: '', + monthOfBirth: '05', + officialLanguage: 'English', + patientStatus: 'AC', + patientStatusDate: Date.now(), + phone: '250-', + phone2: '', + postal: 'S4M 7T8', + providerNo: '4', + province: 'BC', + rosterStatus: '', + sex: 'M', + sexDesc: 'Female', + sin: '', + spokenLanguage: 'English', + title: 'MS.', + yearOfBirth: '2015' +}; -// /** -// * Globals -// */ -// var user, myForm, mySubmission; +/** + * Globals + */ +var user, myForm, mySubmission; -// /** -// * Unit tests -// */ -// describe('Form Model Unit Tests:', function() { -// this.timeout(15000); -// beforeEach(function(done) { -// user = new User({ -// firstName: 'Full', -// lastName: 'Name', -// displayName: 'Full Name', -// email: 'test@test.com', -// username: 'aueoaueoa', -// password: 'password', -// provider: 'local' -// }); +/** + * Unit tests + */ +describe('Form Model Unit Tests:', function() { + this.timeout(15000); + beforeEach(function(done) { + user = new User({ + firstName: 'Full', + lastName: 'Name', + displayName: 'Full Name', + email: 'test@test.com', + username: 'aueoaueoa', + password: 'password', + provider: 'local' + }); -// user.save(function(err) { -// if(err) { -// done(err); -// return; -// } -// myForm = new Form({ -// title: 'Form Title', -// admin: user, -// language: 'english', -// form_fields: [ -// {'fieldType':'textfield', title:'First Name', 'fieldValue': ''}, -// {'fieldType':'checkbox', title:'nascar', 'fieldValue': ''}, -// {'fieldType':'checkbox', title:'hockey', 'fieldValue': ''} -// ] -// }); -// done(); -// }); -// }); + user.save(function(err) { + if(err) { + done(err); + return; + } + myForm = new Form({ + title: 'Form Title', + admin: user, + language: 'english', + form_fields: [ + {'fieldType':'textfield', title:'First Name', 'fieldValue': ''}, + {'fieldType':'checkbox', title:'nascar', 'fieldValue': ''}, + {'fieldType':'checkbox', title:'hockey', 'fieldValue': ''} + ] + }); + done(); + }); + }); -// describe('Method Save', function() { -// it('should be able to save without problems', function(done) { -// return myForm.save(function(err) { -// should.not.exist(err); -// done(); -// }); -// }); + describe('Method Save', function() { + it('should be able to save without problems', function(done) { + return myForm.save(function(err) { + should.not.exist(err); + done(); + }); + }); -// it('should be able to show an error when try to save without title', function(done) { + it('should be able to show an error when try to save without title', function(done) { -// var _form = myForm; -// _form.title = ''; + var _form = myForm; + _form.title = ''; -// return _form.save(function(err) { -// should.exist(err); -// should.equal(err.errors.title.message, 'Form Title cannot be blank'); -// done(); -// }); -// }); -// }); + return _form.save(function(err) { + should.exist(err); + should.equal(err.errors.title.message, 'Form Title cannot be blank'); + done(); + }); + }); + }); -// describe('Method Find', function(){ -// beforeEach(function(done){ -// myForm.save(function(err) { -// if(err) return done(err); -// done(); -// }); -// }); -// it('should be able to findOne my form without problems', function(done) { -// return Form.findOne({title: myForm.title}).exec(function(err,form) { -// should.not.exist(err); -// should.exist(form); -// should.deepEqual(form.toObject(), myForm.toObject()); -// done(); -// }); -// }); -// }); + describe('Method Find', function(){ + beforeEach(function(done){ + myForm.save(function(err) { + if(err) return done(err); + done(); + }); + }); + it('should be able to findOne my form without problems', function(done) { + return Form.findOne({title: myForm.title}).exec(function(err,form) { + should.not.exist(err); + should.exist(form); + should.deepEqual(form.toObject(), myForm.toObject()); + done(); + }); + }); + }); -// afterEach(function(done) { -// Form.remove().exec(function() { -// User.remove().exec(done); -// }); -// }); -// }); + afterEach(function(done) { + Form.remove().exec(function() { + User.remove().exec(done); + }); + }); +}); diff --git a/app/tests/form.server.routes.test.js b/app/tests/form.server.routes.test.js index 8c31212e..3bca8cd3 100644 --- a/app/tests/form.server.routes.test.js +++ b/app/tests/form.server.routes.test.js @@ -4,7 +4,7 @@ var should = require('should'), lodash = require('lodash'), app = require('../../server'), request = require('supertest'), - session = require('supertest-session'), + Session = require('supertest-session'), mongoose = require('mongoose'), User = mongoose.model('User'), Form = mongoose.model('Form'), @@ -20,12 +20,13 @@ describe('Form Routes Unit tests', function() { /** * Globals */ - var credentials, user, myForm, userSession = null; + this.timeout(15000); + var credentials, user, myForm, userSession; beforeEach(function(done) { //Initialize Session - userSession = session(app); + userSession = Session(app); // Create user credentials credentials = { @@ -38,7 +39,7 @@ describe('Form Routes Unit tests', function() { firstName: 'Full', lastName: 'Name', displayName: 'Full Name', - email: 'test1@test.com', + email: 'test5@test.com', username: credentials.username, password: credentials.password, provider: 'local' @@ -50,20 +51,19 @@ describe('Form Routes Unit tests', function() { myForm = { title: 'Form Title', language: 'english', - admin: user.lodashid, - formlodashfields: [ + admin: user.id, + form_fields: [ new Field({'fieldType':'textfield', 'title':'First Name', 'fieldValue': ''}), new Field({'fieldType':'checkbox', 'title':'nascar', 'fieldValue': ''}), new Field({'fieldType':'checkbox', 'title':'hockey', 'fieldValue': ''}) ] }; - done(); }); }); describe(' > Login and Save a new Form >', function() { - var lodashuser, lodashform; + var _user, _form; before(function(done){ userSession.post('/auth/signin') .send(credentials) @@ -74,7 +74,7 @@ describe('Form Routes Unit tests', function() { // Handle signin error if (signinErr) return done(signinErr); - lodashuser = signinRes.body; + _user = signinRes.body; done(); }); }); @@ -87,14 +87,14 @@ describe('Form Routes Unit tests', function() { .end(function(FormSaveErr, FormSaveRes) { // Handle Form save error if (FormSaveErr) return done(FormSaveErr); - lodashform = FormSaveRes.body; + _form = FormSaveRes.body; done(); }); }); it(' > should be able to fetch newly created form', function(done){ // Get a list of Forms - userSession.get('/forms/'+lodashform.lodashid) + userSession.get('/forms/'+_form._id) .expect('Content-Type', /json/) .expect(200) .end(function(FormsGetErr, FormsGetRes) { @@ -103,8 +103,8 @@ describe('Form Routes Unit tests', function() { var fetchedForm = FormsGetRes.body; // Set assertions - (fetchedForm.admin).should.equal(lodashuser.lodashid); - (fetchedForm.title).should.match(lodashform.title); + (fetchedForm.admin).should.equal(_user._id); + (fetchedForm.title).should.match(_form.title); // Call the assertion callback done(); @@ -147,18 +147,13 @@ describe('Form Routes Unit tests', function() { // Set Form with a invalid title field myForm.title = ''; - agent.post('/auth/signin') + agent.post('http://localhost:3001/auth/signin') .send(credentials) .expect('Content-Type', /json/) .expect(200) .end(function(signinErr, signinRes) { should.not.exist(signinErr); - // Handle signin error - if (signinErr) { - console.log(signinErr); - return done(signinErr); - } done(); // Save a new Form // userSession.post('/forms') @@ -195,7 +190,7 @@ describe('Form Routes Unit tests', function() { myForm.title = 'WHY YOU GOTTA BE SO MEAN?'; // Update an existing Form - userSession.put('/forms/' + FormSaveRes.body.lodashid) + userSession.put('/forms/' + FormSaveRes.body._id) .send({form: myForm}) .expect('Content-Type', /json/) .expect(200) @@ -204,7 +199,7 @@ describe('Form Routes Unit tests', function() { if (FormUpdateErr) done(FormUpdateErr); // Set assertions - (FormUpdateRes.body.lodashid).should.equal(FormSaveRes.body.lodashid); + (FormUpdateRes.body._id).should.equal(FormSaveRes.body._id); (FormUpdateRes.body.title).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback @@ -222,7 +217,7 @@ describe('Form Routes Unit tests', function() { FormObj.save(function(err, form) { if(err) return done(err); - agent.get('/forms/' + form.lodashid) + agent.get('/forms/' + form._id) .expect('Content-Type', /json/) .expect(200) .end(function(err, res) { @@ -257,7 +252,7 @@ describe('Form Routes Unit tests', function() { if (FormSaveErr) return done(FormSaveErr); // Delete an existing Form - userSession.delete('/forms/' + FormSaveRes.body.lodashid) + userSession.delete('/forms/' + FormSaveRes.body._id) .send(myForm) .expect('Content-Type', /json/) .expect(200) @@ -267,7 +262,7 @@ describe('Form Routes Unit tests', function() { // Set assertions (FormDeleteRes.body).should.exist(); - // (FormDeleteRes.body.lodashid).should.equal(FormSaveRes.body.lodashid); + // (FormDeleteRes.body._id).should.equal(FormSaveRes.body._id); // Call the assertion callback done(); @@ -287,7 +282,7 @@ describe('Form Routes Unit tests', function() { // Save the Form FormObj.save(function() { // Try deleting Form - agent.delete('/forms/' + FormObj.lodashid) + agent.delete('/forms/' + FormObj._id) .expect(401) .end(function(FormDeleteErr, FormDeleteRes) { // Set message assertion @@ -311,7 +306,7 @@ describe('Form Routes Unit tests', function() { if (signinErr) return done(signinErr); var user = signinRes.body; - var userId = user.lodashid; + var userId = user._id; // Save a new Form userSession.post('/forms') diff --git a/app/tests/form_submission.model.test.js b/app/tests/form_submission.model.test.js index 50d60452..d9529ea2 100644 --- a/app/tests/form_submission.model.test.js +++ b/app/tests/form_submission.model.test.js @@ -15,7 +15,7 @@ var should = require('should'), OscarSecurity = require('../../scripts/oscarhost/OscarSecurity'), FormSubmission = mongoose.model('FormSubmission'); -var exampleDemo = { +var exampleDemo = { address: '880-9650 Velit. St.', city: '', dateOfBirth: '10', @@ -36,7 +36,7 @@ var exampleDemo = { sin: '', spokenLanguage: 'English', title: 'MS.', - yearOfBirth: '2015' + yearOfBirth: '2015' }; @@ -56,6 +56,19 @@ var sampleSubmission = [ {'fieldType':'number', 'title':'What\'s your phone #?', 'fieldValue': '6043158008'} ]; +_.mixin({ + deepOmit: function(obj, iteratee, context) { + var r = _.omit(obj, iteratee, context); + + _.each(r, function(val, key) { + if (typeof(val) === "object") + r[key] = _.deepOmit(val, iteratee, context); + }); + + return r; + } +}); + /** * Globals @@ -83,7 +96,7 @@ describe('FormSubmission Model Unit Tests:', function() { console.log(err.errors); done(err); return; - } + } myForm = new Form({ title: 'Form Title1', admin: user._id, @@ -94,14 +107,14 @@ describe('FormSubmission Model Unit Tests:', function() { {'fieldType':'radio', 'title':'And your sex', 'fieldOptions': [{ 'option_id': 0, 'option_title': 'Male', 'option_value': 'M' }, { 'option_id': 1, 'option_title': 'Female', 'option_value': 'F' }], 'fieldValue': ''}, {'fieldType':'date', 'title':'When were you born?', 'fieldValue': ''}, {'fieldType':'number', 'title':'What\'s your phone #?', 'fieldValue': ''}, - ], + ], plugins: { oscarhost: { baseUrl: config.oscarhost.baseUrl, settings: { - updateType: 'force_add', + updateType: 'force_add' }, - auth: config.oscarhost.auth, + auth: config.oscarhost.auth } } }); @@ -117,14 +130,14 @@ describe('FormSubmission Model Unit Tests:', function() { for(var z=0; z should be able to get Form Submissions if signed in', function(done) { - submissionSession.post('/auth/signin') - .send(credentials) - .expect('Content-Type', /json/) + //Create Submission + submissionSession.post('/forms/' + FormObj._id) + .send(_Submission) .expect(200) - .end(function(signinErr, signinRes) { + .end(function(err, res) { - should.not.exist(signinErr); + should.not.exist(err); - //Create Submission - submissionSession.post('/forms/' + FormObj._id) - .send(_Submission) + submissionSession.post('/auth/signin') + .send(credentials) + .expect('Content-Type', /json/) .expect(200) - .end(function(err, res) { + .end(function(signinErr, signinRes) { - should.not.exist(err); + should.not.exist(signinErr); submissionSession.get('/forms/' + FormObj._id + '/submissions') .expect('Content-Type', /json/) @@ -129,44 +128,6 @@ describe('Form Routes Unit tests', function() { }); }); - it(' > should not be able to get Form Submissions if not signed in', function(done) { - // Attempt to fetch form submissions - submissionSession.get('/forms/' + FormObj._id + '/submissions') - .expect(401) - .end(function(err, res) { - - // Set assertions - (res.body.message).should.equal('User is not logged in'); - - // Call the assertion callback - done(); - }); - }); - - it(' > should not be able to delete Form Submission if not signed in', function(done) { - var SubmissionObj = new FormSubmission(_Submission); - - SubmissionObj.save(function (err, submission) { - should.not.exist(err); - - var submission_ids = _.pluck([submission], '_id'); - - // Attempt to delete form submissions - submissionSession.delete('/forms/' + FormObj._id + '/submissions') - .send({deleted_submissions: submission_ids}) - .expect(401) - .end(function(err, res) { - - // Set assertions - should.not.exist(err); - (res.body.message).should.equal('User is not logged in'); - - // Call the assertion callback - done(); - }); - }); - }); - it(' > should be able to delete Form Submission if signed in', function(done) { // Create new FormSubmission model instance var SubmissionObj = new FormSubmission(_Submission); @@ -174,14 +135,14 @@ describe('Form Routes Unit tests', function() { SubmissionObj.save(function (err, submission) { should.not.exist(err); - // Signin as user + // Sign n as user submissionSession.post('/auth/signin') .send(credentials) .expect('Content-Type', /json/) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error - if (signinErr) return done(signinErr); + should.not.exist(signinErr); var submission_ids = _.pluck([submission], '_id'); @@ -202,6 +163,46 @@ describe('Form Routes Unit tests', function() { }); }); + it(' > should not be able to get Form Submissions if not signed in', function(done) { + // Attempt to fetch form submissions + submissionSession.get('/forms/' + FormObj._id + '/submissions') + .expect(401) + .end(function(err, res) { + should.not.exist(err); + + // Set assertions + (res.body.message).should.equal('User is not logged in'); + + // Call the assertion callback + done(); + }); + + }); + + it(' > should not be able to delete Form Submission if not signed in', function(done) { + var SubmissionObj = new FormSubmission(_Submission); + + SubmissionObj.save(function (err, submission) { + should.not.exist(err); + + var submission_ids = _.pluck([submission], '_id'); + + // Attempt to delete form submissions + submissionSession.delete('/forms/' + FormObj._id + '/submissions') + .send({deleted_submissions: submission_ids}) + .expect(401) + .end(function (err, res) { + + // Set assertions + should.not.exist(err); + (res.body.message).should.equal('User is not logged in'); + + // Call the assertion callback + done(); + }); + }); + }); + afterEach(function(done) {//logout current user if there is one FormSubmission.remove().exec(function() { Form.remove().exec(function (err) { diff --git a/app/tests/user.server.routes.test.js b/app/tests/user.server.routes.test.js index 2108edc7..b032e410 100644 --- a/app/tests/user.server.routes.test.js +++ b/app/tests/user.server.routes.test.js @@ -9,30 +9,32 @@ var should = require('should'), User = mongoose.model('User'), config = require('../../config/config'), tmpUser = mongoose.model(config.tempUserCollection), - agent = request.agent(app), url = require('url'); - -var mailosaur = require('mailosaur')(config.mailosaur.key), - mailbox = new mailosaur.Mailbox(config.mailosaur.mailbox_id); - -var mandrill = require('node-mandrill')(config.mailer.options.auth.pass); +// +// var mailosaur = require('mailosaur')(config.mailosaur.key), +// mailbox = new mailosaur.Mailbox(config.mailosaur.mailbox_id); +// +// var mandrill = require('node-mandrill')(config.mailer.options.auth.pass); /** * Globals */ -var credentials, _User, _Session; +var credentials, _User; +var _tmpUser, activateToken; +var username, userSession; + +username = 'testActiveAccount1.be1e58fb@mailosaur.in'; + +//Initialize Session +userSession = Session(app); /** * Form routes tests */ describe('User CRUD tests', function() { - this.timeout(15000); - var userSession; + //this.timeout(15000); beforeEach(function() { - //Initialize Session - userSession = new Session(); - // Create user credentials credentials = { username: 'be1e58fb@mailosaur.in', @@ -48,34 +50,21 @@ describe('User CRUD tests', function() { password: credentials.password, provider: 'local' }; + }); - describe(' > Create, Verify and Activate a User > ', function() { - var username = 'testActiveAccount1.be1e58fb@mailosaur.in'; - var link, _tmpUser, activateToken; - this.timeout(15000); + //describe(' > Create, Verify and Activate a User > ', function() { + //this.timeout(15000); it('should be able to create a temporary (non-activated) User', function(done) { - _User.email = _User.username = username; + //_User.email = _User.username = username; userSession.post('/auth/signup') .send(_User) - .expect(200, 'An email has been sent to you. Please check it to verify your account.') + .expect(200) .end(function(FormSaveErr, FormSaveRes) { // Handle error - if (FormSaveErr) return done(FormSaveErr); - - 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); - _User.lastName.should.equal(user.lastName); - activateToken = user.GENERATED_VERIFYING_URL; - - done(); - }); + should.not.exist(FormSaveErr); + done(); // // mandrill('/messages/search', { // // query: "subject:Confirm", @@ -125,8 +114,24 @@ describe('User CRUD tests', function() { }); }); + it('should produce valid activation token', function(done) { + console.log('activation token'); + 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); + _User.lastName.should.equal(user.lastName); + activateToken = user.GENERATED_VERIFYING_URL; + + done(); + }); + }); + it('should be able to verify a User Account', function(done) { - console.log('activateToken: '+activateToken); + //console.log('activateToken: '+activateToken); userSession.get('/auth/verify/'+activateToken) .expect(200) .end(function(VerifyErr, VerifyRes) { @@ -162,7 +167,7 @@ describe('User CRUD tests', function() { }); }); }); - }); + //}); it(' > should be able to reset a User\'s password'); @@ -173,7 +178,7 @@ describe('User CRUD tests', function() { tmpUser.remove().exec(function(){ // mailbox.deleteAllEmail(function (err, body) { // if(err) throw err; - userSession.destroy(); + //userSession.destroy(); done(); // }); }); diff --git a/config/express.js b/config/express.js index 370464ed..3e7e9bf3 100755 --- a/config/express.js +++ b/config/express.js @@ -92,6 +92,23 @@ module.exports = function(db) { app.use(bodyParser.json()); app.use(methodOverride()); + // use passport session + app.use(passport.initialize()); + app.use(passport.session()); + + // setup express-device + app.use(device.capture({ parseUserAgent: true })); + + // connect flash for flash messages + app.use(flash()); + + // Use helmet to secure Express headers + app.use(helmet.xframe()); + app.use(helmet.xssFilter()); + app.use(helmet.nosniff()); + app.use(helmet.ienoopen()); + app.disable('x-powered-by'); + // Globbing model files config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) { require(path.resolve(modelPath)); @@ -102,13 +119,6 @@ module.exports = function(db) { require(path.resolve(routePath))(app); }); - // Use helmet to secure Express headers - app.use(helmet.xframe()); - app.use(helmet.xssFilter()); - app.use(helmet.nosniff()); - app.use(helmet.ienoopen()); - app.disable('x-powered-by'); - // Setting the app router and static folder app.use('/', express.static(path.resolve('./public'))); app.use('/uploads', express.static(path.resolve('./uploads'))); @@ -129,16 +139,6 @@ module.exports = function(db) { name: config.sessionName })); - // use passport session - app.use(passport.initialize()); - app.use(passport.session()); - - // setup express-device - app.use(device.capture({ parseUserAgent: true })); - - // connect flash for flash messages - app.use(flash()); - // Add headers for Sentry /* app.use(function (req, res, next) { diff --git a/package.json b/package.json index 65c1b785..c50b5aa5 100644 --- a/package.json +++ b/package.json @@ -111,7 +111,7 @@ "node-mandrill": "^1.0.1", "phantomjs": "^1.9.18", "should": "~7.1.1", - "supertest": "~1.1.0", - "supertest-session": "~2.0.0" + "supertest": "~1.2.0", + "supertest-session": "~2.0.1" } } diff --git a/public/dist/application.js b/public/dist/application.js index 9c784fc1..3ec39329 100644 --- a/public/dist/application.js +++ b/public/dist/application.js @@ -412,7 +412,7 @@ angular.module('NodeForm.templates', []).run(['$templateCache', function($templa $templateCache.put("../public/modules/users/views/authentication/signup-success.client.view.html", "

Signup Successful

You've successfully registered an account at TellForm.

But your account is not activated yet



Before you continue, make sure to check your email for our verification. If you don't receive it within 24h drop us a line at hi@TellForm.com

"); $templateCache.put("../public/modules/users/views/authentication/signup.client.view.html", - "

Signup with your email

Couldn't submit form due to errors:

"); + "

Signup with your email

Couldn't submit form due to errors:

"); $templateCache.put("../public/modules/users/views/password/forgot-password.client.view.html", "

Restore your password

Enter your account email.

{{error}}
{{success}}
"); $templateCache.put("../public/modules/users/views/password/reset-password-invalid.client.view.html", @@ -2168,7 +2168,6 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca $scope.error = ''; $scope.signin = function() { - console.log($scope.credentials); $scope.credentials.email = $scope.credentials.username; User.login($scope.credentials).then( function(response) { @@ -2192,6 +2191,7 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca }; $scope.signup = function() { + console.log($scope.credentials); User.signup($scope.credentials).then( function(response) { console.log('signup-success'); diff --git a/public/dist/application.min.js b/public/dist/application.min.js index 5369fda4..491ad9ff 100644 --- a/public/dist/application.min.js +++ b/public/dist/application.min.js @@ -1,4 +1,4 @@ "use strict";var ApplicationConfiguration=function(){var applicationModuleName="NodeForm",applicationModuleVendorDependencies=["ngResource","NodeForm.templates","ngAnimate","ui.router","ui.bootstrap","ui.utils","ngRaven","cgBusy"],registerModule=function(moduleName,dependencies){angular.module(moduleName,dependencies||[]),angular.module(applicationModuleName).requires.push(moduleName)};return{applicationModuleName:applicationModuleName,applicationModuleVendorDependencies:applicationModuleVendorDependencies,registerModule:registerModule}}();angular.module(ApplicationConfiguration.applicationModuleName,ApplicationConfiguration.applicationModuleVendorDependencies),angular.module(ApplicationConfiguration.applicationModuleName).config(["$locationProvider",function($locationProvider){$locationProvider.hashPrefix("!")}]),angular.module(ApplicationConfiguration.applicationModuleName).constant("APP_PERMISSIONS",{viewAdminSettings:"viewAdminSettings",editAdminSettings:"editAdminSettings",editForm:"editForm",viewPrivateForm:"viewPrivateForm"}),angular.module(ApplicationConfiguration.applicationModuleName).constant("USER_ROLES",{admin:"admin",normal:"user",superuser:"superuser"}),angular.module(ApplicationConfiguration.applicationModuleName).run(["$rootScope","Auth","$state","$stateParams",function($rootScope,Auth,$state,$stateParams){$rootScope.$state=$state,$rootScope.$stateParams=$stateParams,$rootScope.$on("$stateChangeSuccess",function(event,toState,toParams,fromState){$state.previous=fromState,console.log("toState: "+toState.name),"home"===toState.name||"signin"===toState.name||"resendVerifyEmail"===toState.name||"verify"===toState.name||"signup"===toState.name||"signup-success"===toState.name?Auth.isAuthenticated()&&(event.preventDefault(),$state.go("listForms")):"access_denied"===toState.name||Auth.isAuthenticated()||"submitForm"===toState.name||(console.log("go to home"),event.preventDefault(),$state.go("home"))})}]),angular.module(ApplicationConfiguration.applicationModuleName).run(["$rootScope","Auth","User","Authorizer","$state","$stateParams",function($rootScope,Auth,User,Authorizer,$state,$stateParams){$rootScope.$on("$stateChangeStart",function(event,next){var authenticator,permissions,user;permissions=next&&next.data&&next.data.permissions?next.data.permissions:null,Auth.ensureHasCurrentUser(User),user=Auth.currentUser,user&&(authenticator=new Authorizer(user),console.log("access denied: "+!authenticator.canAccess(permissions)),null===permissions||authenticator.canAccess(permissions)||(event.preventDefault(),console.log("access denied"),$state.go("access_denied")))})}]),angular.element(document).ready(function(){"#_=_"===window.location.hash&&(window.location.hash="#!"),angular.bootstrap(document,[ApplicationConfiguration.applicationModuleName])}),angular.module("NodeForm.templates",[]).run(["$templateCache",function($templateCache){$templateCache.put("../public/modules/core/views/header.client.view.html",''),$templateCache.put("../public/modules/core/views/home.client.view.html",'

Craft beautiful forms in seconds.

Create your next ______.

Tell a story with a form.

'),$templateCache.put("../public/modules/forms/views/admin-form.client.view.html",'
'),$templateCache.put("../public/modules/forms/views/list-forms.client.view.html",'

Create a new form
Name
Language

'),$templateCache.put("../public/modules/forms/views/submit-form.client.view.html","
"),$templateCache.put("../public/modules/forms/views/adminTabs/analyze.html",""),$templateCache.put("../public/modules/forms/views/adminTabs/configure.html",""),$templateCache.put("../public/modules/forms/views/adminTabs/create.html",""),$templateCache.put("../public/modules/forms/views/adminTabs/design.html",'
Background Color
Question Font Color
Answer Font Color
'),$templateCache.put("../public/modules/forms/views/directiveViews/cgBusy/update-form-message-TypeA.html",'
{{$message}}
'),$templateCache.put("../public/modules/forms/views/directiveViews/cgBusy/update-form-message-TypeB.html",'
{{$message}}
'),$templateCache.put("../public/modules/forms/views/directiveViews/entryPage/startPage.html",'

{{pageData.introTitle}}

{{pageData.introParagraph}}

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/checkbox.html",'
{{field.title}} (* required)
'),$templateCache.put("../public/modules/forms/views/directiveViews/field/date.html",'

{{field.title}} *(required)

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/dropdown.html",'
'),$templateCache.put("../public/modules/forms/views/directiveViews/field/email.html",'

{{field.title}} *(required)

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/file.html",'
{{field.title}} (* required)
…
{{field.file.originalname}}
Upload your File
'),$templateCache.put("../public/modules/forms/views/directiveViews/field/hidden.html",''),$templateCache.put("../public/modules/forms/views/directiveViews/field/legal.html",'
'),$templateCache.put("../public/modules/forms/views/directiveViews/field/link.html",'

{{field.title}} *(required)

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/natural.html",'

{{field.title}} *(required)


'),$templateCache.put("../public/modules/forms/views/directiveViews/field/number.html",'

{{field.title}} *(required)

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/password.html",'

{{field.title}} *(required)

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/radio.html",'

{{field.title}} *(required)


'),$templateCache.put("../public/modules/forms/views/directiveViews/field/rating.html",'

{{field.title}} *(required)

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/statement.html",'

{{field.title}}

{{field.description}}


'),$templateCache.put("../public/modules/forms/views/directiveViews/field/textarea.html",'

{{field.title}} *(required)

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/textfield.html",'

{{field.title}} *(required)

'),$templateCache.put("../public/modules/forms/views/directiveViews/field/yes_no.html",'

{{field.title}} *(required)

{{field.description}}


'),$templateCache.put("../public/modules/forms/views/directiveViews/form/configure-form.client.view.html",'
Save Submissions as PDFs?
Upload Your PDF Template
…
{{myform.pdf.originalname}}
Upload your PDF
Autogenerate Form?
Use Oscarhost API?
Oscarhost API Username
Oscarhost API Password
Oscarhost API URL
Oscarhost API Update Type
Form Name
Form Status
Language
* required
Display Form Footer?
Display Start Page?
'), -$templateCache.put("../public/modules/forms/views/directiveViews/form/edit-form.client.view.html",'

Edit Start Page


Intro Title:
Intro Paragraph:
\n
\n\n

\n
\n
Options:
\n
\n
\n \n\n \n \n \n
\n
\n \n
\n
\n
\n\n

\n\n
\n
Required:
\n
\n \n\n \n
\n
\n\n
\n
Disabled:
\n
\n \n\n \n
\n
\n\n
\n \n\n
\n
\n

\n Click on Fields to add them here\n

\n
\n
\n\n
\n \n
\n\n \n \n\n \n
\n
\n\n'),$templateCache.put("../public/modules/forms/views/directiveViews/form/edit-submissions-form.client.view.html",'
#{{value.title}}OscarEMR User ProfilePercentage CompleteTime ElapsedDeviceLocationIP AddressDate Submitted (UTC)Generated PDF
{{$index+1}}{{field.fieldValue}}User Profile #{{row.oscarDemoNum}}{{row.percentageComplete}}%{{row.timeElapsed}}{{row.device.name}}, {{row.device.type}}{{row.geoLocation.city}}, {{row.geoLocation.country}}{{row.ipAddr}}{{row.created | date:\'yyyy-MM-dd HH:mm:ss\'}}Generated PDF
'),$templateCache.put("../public/modules/forms/views/directiveViews/form/submit-form.client.view.html",'

{{ myform.title }} (private preview)



'),$templateCache.put("../public/modules/users/views/authentication/access-denied.client.view.html",'

You need to be logged in to access this page

Login
'),$templateCache.put("../public/modules/users/views/authentication/signin.client.view.html",'

Sign into your account

'),$templateCache.put("../public/modules/users/views/authentication/signup-success.client.view.html",''),$templateCache.put("../public/modules/users/views/authentication/signup.client.view.html",''),$templateCache.put("../public/modules/users/views/password/forgot-password.client.view.html",'

Restore your password

Enter your account email.

'),$templateCache.put("../public/modules/users/views/password/reset-password-invalid.client.view.html",'

Password reset is invalid

Ask for a new password reset
'),$templateCache.put("../public/modules/users/views/password/reset-password-success.client.view.html",'

Password successfully reset

Continue to home page
'),$templateCache.put("../public/modules/users/views/password/reset-password.client.view.html",'

Reset your password

'),$templateCache.put("../public/modules/users/views/settings/change-password.client.view.html",'

Change your password

'),$templateCache.put("../public/modules/users/views/settings/edit-profile.client.view.html",'

Edit your profile

'),$templateCache.put("../public/modules/users/views/settings/social-accounts.client.view.html",'

Connected social accounts:

Connect other social accounts:

'), +$templateCache.put("../public/modules/forms/views/directiveViews/form/edit-form.client.view.html",'

Edit Start Page


Intro Title:
Intro Paragraph:
\n
\n\n

\n
\n
Options:
\n
\n
\n \n\n \n \n \n
\n
\n \n
\n
\n
\n\n

\n\n
\n
Required:
\n
\n \n\n \n
\n
\n\n
\n
Disabled:
\n
\n \n\n \n
\n
\n\n
\n \n\n
\n
\n

\n Click on Fields to add them here\n

\n
\n
\n\n
\n \n
\n\n \n \n\n \n
\n
\n\n'),$templateCache.put("../public/modules/forms/views/directiveViews/form/edit-submissions-form.client.view.html",'
#{{value.title}}OscarEMR User ProfilePercentage CompleteTime ElapsedDeviceLocationIP AddressDate Submitted (UTC)Generated PDF
{{$index+1}}{{field.fieldValue}}User Profile #{{row.oscarDemoNum}}{{row.percentageComplete}}%{{row.timeElapsed}}{{row.device.name}}, {{row.device.type}}{{row.geoLocation.city}}, {{row.geoLocation.country}}{{row.ipAddr}}{{row.created | date:\'yyyy-MM-dd HH:mm:ss\'}}Generated PDF
'),$templateCache.put("../public/modules/forms/views/directiveViews/form/submit-form.client.view.html",'

{{ myform.title }} (private preview)



'),$templateCache.put("../public/modules/users/views/authentication/access-denied.client.view.html",'

You need to be logged in to access this page

Login
'),$templateCache.put("../public/modules/users/views/authentication/signin.client.view.html",'

Sign into your account

'),$templateCache.put("../public/modules/users/views/authentication/signup-success.client.view.html",''),$templateCache.put("../public/modules/users/views/authentication/signup.client.view.html",''),$templateCache.put("../public/modules/users/views/password/forgot-password.client.view.html",'

Restore your password

Enter your account email.

'),$templateCache.put("../public/modules/users/views/password/reset-password-invalid.client.view.html",'

Password reset is invalid

Ask for a new password reset
'),$templateCache.put("../public/modules/users/views/password/reset-password-success.client.view.html",'

Password successfully reset

Continue to home page
'),$templateCache.put("../public/modules/users/views/password/reset-password.client.view.html",'

Reset your password

'),$templateCache.put("../public/modules/users/views/settings/change-password.client.view.html",'

Change your password

'),$templateCache.put("../public/modules/users/views/settings/edit-profile.client.view.html",'

Edit your profile

'),$templateCache.put("../public/modules/users/views/settings/social-accounts.client.view.html",'

Connected social accounts:

Connect other social accounts:

'), $templateCache.put("../public/modules/users/views/verify/resend-verify-email.client.view.html",'

Resend your account verification email

Enter your account email.

{{error}}

Verification Email has been Sent

A verification email has been sent to {{username}}.
But your account is still not activated yet

Check your email and click on the activation link to activate your account. If you have any questions drop us a line at hi@TellForm.com

'),$templateCache.put("../public/modules/users/views/verify/verify-account.client.view.html",'

Account successfuly activated

Continue to login page

Verification link is invalid or has expired

Resend your verification email Signin to your account
')}]),ApplicationConfiguration.registerModule("core",["users"]),ApplicationConfiguration.registerModule("forms",["ngFileUpload","ui.router.tabs","colorpicker.module","ui.date","ui.sortable","angular-input-stars","users"]),ApplicationConfiguration.registerModule("users"),angular.module("core").config(["$stateProvider","$urlRouterProvider",function($stateProvider,$urlRouterProvider,Authorization){$urlRouterProvider.otherwise("/"),$stateProvider.state("home",{url:"/",templateUrl:"modules/core/views/home.client.view.html"})}]),angular.module("core").controller("HeaderController",["$rootScope","$scope","Menus","$state","Auth","User",function($rootScope,$scope,Menus,$state,Auth,User){$scope.user=$rootScope.user=Auth.ensureHasCurrentUser(User),$scope.authentication=$rootScope.authentication=Auth,$rootScope.languages=$scope.languages=["english","french","spanish"],$scope.isCollapsed=!1,$rootScope.hideNav=!1,$scope.menu=Menus.getMenu("topbar"),$scope.signout=function(){var promise=User.logout();promise.then(function(){Auth.logout(),Auth.ensureHasCurrentUser(User),$scope.user=$rootScope.user=null,$state.go("home")},function(reason){console.log("Logout Failed: "+reason)})},$scope.toggleCollapsibleMenu=function(){$scope.isCollapsed=!$scope.isCollapsed},$scope.$on("$stateChangeSuccess",function(event,toState,toParams,fromState,fromParams){$scope.isCollapsed=!1,$rootScope.hideNav=!1,angular.isDefined(toState.data)&&angular.isDefined(toState.data.hideNav)&&($rootScope.hideNav=toState.data.hideNav)})}]),angular.module("core").controller("HomeController",["$rootScope","$scope","User","$state",function($rootScope,$scope,User,$state){$scope=$rootScope}]),angular.module("core").service("Menus",[function(){this.defaultRoles=["*"],this.menus={};var shouldRender=function(user){if(!user)return this.isPublic;if(~this.roles.indexOf("*"))return!0;for(var userRoleIndex in user.roles)for(var roleIndex in this.roles)if(console.log(this.roles[roleIndex]),console.log(this.roles[roleIndex]===user.roles[userRoleIndex]),this.roles[roleIndex]===user.roles[userRoleIndex])return!0;return!1};this.validateMenuExistance=function(menuId){if(menuId&&menuId.length){if(this.menus[menuId])return!0;throw new Error("Menu does not exists")}throw new Error("MenuId was not provided")},this.getMenu=function(menuId){return this.validateMenuExistance(menuId),this.menus[menuId]},this.addMenu=function(menuId,isPublic,roles){return this.menus[menuId]={isPublic:isPublic||!1,roles:roles||this.defaultRoles,items:[],shouldRender:shouldRender},this.menus[menuId]},this.removeMenu=function(menuId){this.validateMenuExistance(menuId),delete this.menus[menuId]},this.addMenuItem=function(menuId,menuItemTitle,menuItemURL,menuItemType,menuItemUIRoute,isPublic,roles,position){return this.validateMenuExistance(menuId),this.menus[menuId].items.push({title:menuItemTitle,link:menuItemURL,menuItemType:menuItemType||"item",menuItemClass:menuItemType,uiRoute:menuItemUIRoute||"/"+menuItemURL,isPublic:null===isPublic||"undefined"==typeof isPublic?this.menus[menuId].isPublic:isPublic,roles:null===roles||"undefined"==typeof roles?this.menus[menuId].roles:roles,position:position||0,items:[],shouldRender:shouldRender}),this.menus[menuId]},this.addSubMenuItem=function(menuId,rootMenuItemURL,menuItemTitle,menuItemURL,menuItemUIRoute,isPublic,roles,position){this.validateMenuExistance(menuId);for(var itemIndex in this.menus[menuId].items)this.menus[menuId].items[itemIndex].link===rootMenuItemURL&&this.menus[menuId].items[itemIndex].items.push({title:menuItemTitle,link:menuItemURL,uiRoute:menuItemUIRoute||"/"+menuItemURL,isPublic:null===isPublic||"undefined"==typeof isPublic?this.menus[menuId].items[itemIndex].isPublic:isPublic,roles:null===roles||"undefined"==typeof roles?this.menus[menuId].items[itemIndex].roles:roles,position:position||0,shouldRender:shouldRender});return this.menus[menuId]},this.removeMenuItem=function(menuId,menuItemURL){this.validateMenuExistance(menuId);for(var itemIndex in this.menus[menuId].items)this.menus[menuId].items[itemIndex].link===menuItemURL&&this.menus[menuId].items.splice(itemIndex,1);return this.menus[menuId]},this.removeSubMenuItem=function(menuId,submenuItemURL){this.validateMenuExistance(menuId);for(var itemIndex in this.menus[menuId].items)for(var subitemIndex in this.menus[menuId].items[itemIndex].items)this.menus[menuId].items[itemIndex].items[subitemIndex].link===submenuItemURL&&this.menus[menuId].items[itemIndex].items.splice(subitemIndex,1);return this.menus[menuId]},this.addMenu("topbar",!1,["*"]),this.addMenu("bottombar",!1,["*"])}]),angular.module("forms").run(["Menus",function(Menus){Menus.addMenuItem("topbar","My Forms","forms","","/forms",!1)}]).filter("formValidity",function(){return function(formObj){if(formObj&&formObj.form_fields&&formObj.visible_form_fields){var formKeys=Object.keys(formObj),fields=(formKeys.filter(function(key){return"$"!==key[0]}),formObj.form_fields),valid_count=fields.filter(function(field){return"object"==typeof field?"rating"===field.fieldType||"statement"===field.fieldType?!0:!!field.fieldValue:void 0}).length;return valid_count-(formObj.form_fields.length-formObj.visible_form_fields.length)}return 0}}).config(["$provide",function($provide){$provide.decorator("accordionDirective",["$delegate",function($delegate){var directive=$delegate[0];return directive.replace=!0,$delegate}])}]),angular.module("forms").config(["$stateProvider",function($stateProvider){$stateProvider.state("listForms",{url:"/forms",templateUrl:"modules/forms/views/list-forms.client.view.html",data:{permissions:["editForm"]}}).state("submitForm",{url:"/forms/:formId",templateUrl:"modules/forms/views/submit-form.client.view.html",data:{hideNav:!0},resolve:{Forms:"Forms",myForm:["Forms","$stateParams",function(Forms,$stateParams){return Forms.get({formId:$stateParams.formId}).$promise}]},controller:"SubmitFormController"}).state("viewForm",{url:"/forms/:formId/admin",templateUrl:"modules/forms/views/admin-form.client.view.html",data:{permissions:["editForm"]},resolve:{Forms:"Forms",myForm:["Forms","$stateParams",function(Forms,$stateParams){return Forms.get({formId:$stateParams.formId}).$promise}]},controller:"AdminFormController"}).state("viewForm.configure",{url:"/configure",templateUrl:"modules/forms/views/adminTabs/configure.html"}).state("viewForm.design",{url:"/design",templateUrl:"modules/forms/views/adminTabs/design.html"}).state("viewForm.analyze",{url:"/analyze",templateUrl:"modules/forms/views/adminTabs/analyze.html"}).state("viewForm.create",{url:"/create",templateUrl:"modules/forms/views/adminTabs/create.html"})}]),angular.module("forms").controller("AdminFormController",["$rootScope","$scope","$stateParams","$state","Forms","CurrentForm","$http","$uibModal","myForm",function($rootScope,$scope,$stateParams,$state,Forms,CurrentForm,$http,$uibModal,myForm){$scope=$rootScope,$scope.animationsEnabled=!0,$scope.myform=myForm,$rootScope.saveInProgress=!1,CurrentForm.setForm($scope.myform),$scope.tabData=[{heading:"Create",route:"viewForm.create"},{heading:"Design",route:"viewForm.design"},{heading:"Configure",route:"viewForm.configure"},{heading:"Analyze",route:"viewForm.analyze"}],$scope.setForm=function(form){$scope.myform=form},$rootScope.resetForm=function(){$scope.myform=Forms.get({formId:$stateParams.formId})},$scope.openDeleteModal=function(){$scope.deleteModal=$uibModal.open({animation:$scope.animationsEnabled,templateUrl:"myModalContent.html",controller:"AdminFormController",resolve:{myForm:function(){return $scope.myform}}}),$scope.deleteModal.result.then(function(selectedItem){$scope.selected=selectedItem},function(){console.log("Modal dismissed at: "+new Date)})},$scope.cancelDeleteModal=function(){$scope.deleteModal&&$scope.deleteModal.dismiss("cancel")},$scope.removeCurrentForm=function(){if($scope.deleteModal&&$scope.deleteModal.opened){$scope.deleteModal.close();var form_id=$scope.myform._id;if(!form_id)throw new Error("Error - removeCurrentForm(): $scope.myform._id does not exist");$http["delete"]("/forms/"+form_id).success(function(data,status,headers){console.log("form deleted successfully"),$state.go("listForms",{},{reload:!0})}).error(function(error){console.log("ERROR: Form could not be deleted."),console.error(error)})}},$scope.update=$rootScope.update=function(updateImmediately,cb){var continueUpdate=!0;if(updateImmediately||(continueUpdate=!$rootScope.saveInProgress),continueUpdate){var err=null;updateImmediately||($rootScope.saveInProgress=!0),$scope.updatePromise=$http.put("/forms/"+$scope.myform._id,{form:$scope.myform}).then(function(response){$rootScope.myform=$scope.myform=response.data})["catch"](function(response){console.log("Error occured during form UPDATE.\n"),err=response.data})["finally"](function(){updateImmediately||($rootScope.saveInProgress=!1),"function"==typeof cb&&cb(err)})}}}]),angular.module("forms").controller("ListFormsController",["$rootScope","$scope","$stateParams","$state","Forms","CurrentForm","$http",function($rootScope,$scope,$stateParams,$state,Forms,CurrentForm,$http){$scope=$rootScope,$scope.forms={},$scope.showCreateModal=!1,$scope.findAll=function(){Forms.query(function(_forms){$scope.myforms=_forms})},$scope.openCreateModal=function(){$scope.showCreateModal||($scope.showCreateModal=!0)},$scope.closeCreateModal=function(){$scope.showCreateModal&&($scope.showCreateModal=!1)},$scope.setForm=function(form){$scope.myform=form},$scope.goToWithId=function(route,id){$state.go(route,{formId:id},{reload:!0})},$scope.duplicateForm=function(form_index){var form=_.cloneDeep($scope.myforms[form_index]);delete form._id,$http.post("/forms",{form:form}).success(function(data,status,headers){$scope.myforms.splice(form_index+1,0,data)}).error(function(errorResponse){console.error(errorResponse),null===errorResponse&&($scope.error=errorResponse.data.message)})},$scope.createNewForm=function(){var form={};form.title=$scope.forms.createForm.title.$modelValue,form.language=$scope.forms.createForm.language.$modelValue,$scope.forms.createForm.$valid&&$scope.forms.createForm.$dirty&&$http.post("/forms",{form:form}).success(function(data,status,headers){console.log("new form created"),$scope.goToWithId("viewForm.create",data._id+"")}).error(function(errorResponse){console.error(errorResponse),$scope.error=errorResponse.data.message})},$scope.removeForm=function(form_index){if(form_index>=$scope.myforms.length||0>form_index)throw new Error("Error: form_index in removeForm() must be between 0 and "+$scope.myforms.length-1);$http["delete"]("/forms/"+$scope.myforms[form_index]._id).success(function(data,status,headers){console.log("form deleted successfully"),$scope.myforms.splice(form_index,1)}).error(function(error){console.log("ERROR: Form could not be deleted."),console.error(error)})}}]),angular.module("forms").controller("SubmitFormController",["$scope","$rootScope","$state","myForm","Auth",function($scope,$rootScope,$state,myForm,Auth){$scope.authentication=Auth,$scope.myform=myForm,$scope.myform.isLive?$scope.hideNav=$rootScope.hideNav=!0:$scope.authentication.isAuthenticated()?$scope.hideNav=$rootScope.hideNav=!1:($scope.hideNav=$rootScope.hideNav=!0,$state.go("access_denied"))}]),_.mixin({removeDateFields:function(o){for(var clone=_.clone(o),i=0;i0){$scope.myform.plugins.oscarhost.settings.fieldMap||($scope.myform.plugins.oscarhost.settings.fieldMap={});var oscarhostFields=$scope.myform.plugins.oscarhost.settings.validFields,currentFields=_($scope.myform.plugins.oscarhost.settings.fieldMap).invert().keys().value();return $scope.myform.plugins.oscarhost.settings.fieldMap.hasOwnProperty(field_id)&&(currentFields=_(currentFields).difference($scope.myform.plugins.oscarhost.settings.fieldMap[field_id])),_(oscarhostFields).difference(currentFields).value()}return[]},$scope.dropzone={handle:" .handle",containment:".dropzoneContainer",cursor:"grabbing"},$scope.addNewField=function(modifyForm,fieldType){$scope.addField.lastAddedID++;for(var fieldTitle,i=0;i<$scope.addField.types.length;i++)if($scope.addField.types[i].name===fieldType){$scope.addField.types[i].lastAddedID++,fieldTitle=$scope.addField.types[i].value+$scope.addField.types[i].lastAddedID;break}var newField={title:fieldTitle,fieldType:fieldType,fieldValue:"",required:!0,disabled:!1,deletePreserved:!1};return modifyForm&&$scope.myform.form_fields.push(newField),newField},$scope.deleteField=function(field_index){var currFieldId=$scope.myform.form_fields[field_index]._id;$scope.myform.hasOwnProperty("plugins.oscarhost.baseUrl")&&delete $scope.myform.plugins.oscarhost.settings.fieldMap[currFieldId],$scope.myform.form_fields.splice(field_index,1)},$scope.duplicateField=function(field_index){var currField=_.cloneDeep($scope.myform.form_fields[field_index]);currField._id="cloned"+_.uniqueId(),currField.title+=" copy",$scope.myform.form_fields.splice(field_index+1,0,currField)},$scope.addButton=function(){var newButton={};newButton.bgColor="#ddd",newButton.color="#ffffff",newButton.text="Button",newButton._id=Math.floor(1e5*Math.random()),$scope.myform.startPage.buttons.push(newButton)},$scope.deleteButton=function(button){for(var currID,i=0;i<$scope.myform.startPage.buttons.length;i++)if(currID=$scope.myform.startPage.buttons[i]._id,console.log(currID),currID===button._id){$scope.myform.startPage.buttons.splice(i,1);break}},$scope.addOption=function(field_index){var currField=$scope.myform.form_fields[field_index];if("checkbox"===currField.fieldType||"dropdown"===currField.fieldType||"radio"===currField.fieldType){currField.fieldOptions||($scope.myform.form_fields[field_index].fieldOptions=[]);var lastOptionID=0;currField.fieldOptions[currField.fieldOptions.length-1]&&(lastOptionID=currField.fieldOptions[currField.fieldOptions.length-1].option_id);var newOption={option_id:Math.floor(1e5*Math.random()),option_title:"Option "+lastOptionID,option_value:"Option "+lastOptionID};$scope.myform.form_fields[field_index].fieldOptions.push(newOption)}},$scope.deleteOption=function(field_index,option){var currField=$scope.myform.form_fields[field_index];if("checkbox"===currField.fieldType||"dropdown"===currField.fieldType||"radio"===currField.fieldType)for(var i=0;i',restrict:"E",scope:{typeName:"@"},controller:["$scope",function($scope){var iconTypeMap={textfield:"fa fa-pencil-square-o",dropdown:"fa fa-th-list",date:"fa fa-calendar",checkbox:"fa fa-check-square-o",radio:"fa fa-dot-circle-o",email:"fa fa-envelope-o",textarea:"fa fa-pencil-square",legal:"fa fa-legal",file:"fa fa-cloud-upload",rating:"fa fa-star-half-o",link:"fa fa-link",scale:"fa fa-sliders",stripe:"fa fa-credit-card",statement:"fa fa-quote-left",yes_no:"fa fa-toggle-on",number:"fa fa-slack"};$scope.typeIcon=iconTypeMap[$scope.typeName]}]}});var __indexOf=[].indexOf||function(item){for(var i=0,l=this.length;l>i;i++)if(i in this&&this[i]===item)return i;return-1};angular.module("forms").directive("fieldDirective",["$http","$compile","$rootScope","$templateCache",function($http,$compile,$rootScope,$templateCache){var getTemplateUrl=function(field){var type=field.fieldType,templateUrl="modules/forms/views/directiveViews/field/",supported_fields=["textfield","email","textarea","checkbox","date","link","dropdown","hidden","password","radio","legal","statement","rating","yes_no","number","natural"];return __indexOf.call(supported_fields,type)>=0&&(templateUrl=templateUrl+type+".html"),$templateCache.get("../public/"+templateUrl)};return{template:"
{{field.title}}
",restrict:"E",scope:{field:"=",required:"&",design:"=",index:"="},link:function(scope,element){scope.setActiveField=$rootScope.setActiveField,"date"===scope.field.fieldType&&(scope.dateOptions={changeYear:!0,changeMonth:!0,altFormat:"mm/dd/yyyy",yearRange:"1900:-0",defaultDate:0});var template=getTemplateUrl(scope.field);element.html(template).show(),$compile(element.contents())(scope)}}}]),angular.module("forms").directive("onFinishRender",["$rootScope","$timeout",function($rootScope,$timeout){return{restrict:"A",link:function(scope,element,attrs){if(element.attr("ng-repeat")||element.attr("data-ng-repeat")){var broadcastMessage=attrs.onFinishRender||"ngRepeat";scope.$first&&!scope.$last?scope.$evalAsync(function(){$rootScope.$broadcast(broadcastMessage+" Started")}):scope.$last&&scope.$evalAsync(function(){$rootScope.$broadcast(broadcastMessage+" Finished")})}}}}]),angular.module("forms").directive("submitFormDirective",["$http","TimeCounter","$filter","$rootScope","Auth",function($http,TimeCounter,$filter,$rootScope,Auth){return{templateUrl:"modules/forms/views/directiveViews/form/submit-form.client.view.html",restrict:"E",scope:{myform:"="},controller:["$scope",function($scope){$scope.authentication=$rootScope.authentication,$scope.reloadForm=function(){$scope.myform.submitted=!1,$scope.myform.form_fields=_.chain($scope.myform.form_fields).map(function(field){return field.fieldValue="",field}).value(),$scope.error="",$scope.selected={_id:"",index:null},TimeCounter.restartClock()},$rootScope.setActiveField=function(field_id,field_index){null===$scope.selected&&($scope.selected={_id:"",index:0}),console.log("field_id: "+field_id),console.log("field_index: "+field_index),console.log($scope.selected),$scope.selected._id=field_id,$scope.selected.index=field_index,setTimeout(function(){$("html, body").animate({scrollTop:$(".activeField").offset().top},200)},10)},$scope.nextField=function(){$scope.selected.index<$scope.myform.form_fields.length-1&&($scope.selected.index++,$scope.selected._id=$scope.myform.form_fields[$scope.selected.index]._id,$rootScope.setActiveField($scope.selected._id,$scope.selected.index))},$scope.prevField=function(){$scope.selected.index>0&&($scope.selected.index=$scope.selected.index-1,$scope.selected._id=$scope.myform.form_fields[$scope.selected.index]._id,$rootScope.setActiveField($scope.selected._id,$scope.selected.index))},$scope.hideOverlay=function(){$scope.selected={_id:"",index:null}},$scope.exitStartPage=function(){$scope.myform.startPage.showStart=!1,$scope.myform.form_fields.length>0&&($scope.selected._id=$scope.myform.form_fields[0]._id)},$scope.submitForm=function(){var _timeElapsed=TimeCounter.stopClock(),form=_.cloneDeep($scope.myform);form.timeElapsed=_timeElapsed,form.percentageComplete=$filter("formValidity")($scope.myform)/$scope.myform.visible_form_fields.length*100,delete form.visible_form_fields,$scope.submitPromise=$http.post("/forms/"+$scope.myform._id,form).success(function(data,status,headers){console.log("form submitted successfully"),$scope.myform.submitted=!0}).error(function(error){console.log(error),$scope.error=error.message})},angular.element(document).ready(function(){$scope.reloadForm()})}]}}]),angular.module("forms").service("CurrentForm",function(){var _form={};this.getForm=function(){return _form},this.setForm=function(form){_form=form}}),angular.module("forms").service("FormFields",[function(){this.types=[{name:"textfield",value:"Short Text"},{name:"email",value:"Email"},{name:"radio",value:"Multiple Choice"},{name:"dropdown",value:"Dropdown"},{name:"date",value:"Date"},{name:"textarea",value:"Paragraph Text"},{name:"checkbox",value:"Checkbox"},{name:"yes_no",value:"Yes/No"},{name:"legal",value:"Legal"},{name:"rating",value:"Rating"},{name:"link",value:"Link"},{name:"number",value:"Numbers"},{name:"statement",value:"Statement"}]}]),angular.module("forms").factory("Forms",["$resource",function($resource){return $resource("/forms/:formId",{formId:"@_id"},{query:{method:"GET",isArray:!0},get:{method:"GET",transformResponse:function(data,header){var form=angular.fromJson(data);return console.log(form),form.visible_form_fields=_.filter(form.form_fields,function(field){return field.deletePreserved===!1}),form}},update:{method:"PUT"},save:{method:"POST"}})}]),angular.module("forms").factory("Submissions",["$resource",function($resource){return $resource("forms/:formID/submissions/:submissionId",{submissionId:"@_id",formId:"@_id"},{query:{method:"GET",isArray:!0},update:{method:"PUT"},save:{method:"POST"}})}]),angular.module("forms").service("TimeCounter",[function(){var _startTime,_endTime,that=this;this.timeSpent=0,this.restartClock=function(){_startTime=Date.now(),_endTime=_startTime},this.stopClock=function(){return _startTime?(_endTime=Date.now(),that.timeSpent=Math.abs(_endTime.valueOf()-_startTime.valueOf())/1e3,that.timeSpent):new Error("Clock has not been started")},this.clockStarted=function(){return!!this._startTime}}]),angular.module("users").config(["$httpProvider",function($httpProvider){$httpProvider.interceptors.push(["$q","$location",function($q,$location){return{responseError:function(response){return"/users/me"!==$location.path()&&response.config&&"/users/me"!==response.config.url&&(console.log("intercepted rejection of ",response.config.url,response.status),401===response.status?($location.nextAfterLogin=$location.path(),$location.path("/signin")):403===response.status&&$location.path("/access_denied")),$q.reject(response)}}}])}]),angular.module("users").config(["$stateProvider",function($stateProvider){var checkLoggedin=function($q,$timeout,$state,User,Auth){var deferred=$q.defer();return Auth.currentUser&&Auth.currentUser.email?$timeout(deferred.resolve):Auth.currentUser=User.getCurrent(function(){Auth.login(),$timeout(deferred.resolve())},function(){Auth.logout(),$timeout(deferred.reject()),$state.go("sigin",{reload:!0})}),deferred.promise};checkLoggedin.$inject=["$q","$timeout","$state","User","Auth"],$stateProvider.state("profile",{resolve:{loggedin:checkLoggedin},url:"/settings/profile",templateUrl:"modules/users/views/settings/edit-profile.client.view.html"}).state("password",{resolve:{loggedin:checkLoggedin},url:"/settings/password",templateUrl:"modules/users/views/settings/change-password.client.view.html"}).state("accounts",{resolve:{loggedin:checkLoggedin},url:"/settings/accounts", -templateUrl:"modules/users/views/settings/social-accounts.client.view.html"}).state("signup",{url:"/signup",templateUrl:"modules/users/views/authentication/signup.client.view.html"}).state("signup-success",{url:"/signup-success",templateUrl:"modules/users/views/authentication/signup-success.client.view.html"}).state("signin",{url:"/signin",templateUrl:"modules/users/views/authentication/signin.client.view.html"}).state("access_denied",{url:"/access_denied",templateUrl:"modules/users/views/authentication/access-denied.client.view.html"}).state("resendVerifyEmail",{url:"/verify",templateUrl:"modules/users/views/verify/resend-verify-email.client.view.html"}).state("verify",{url:"/verify/:token",templateUrl:"modules/users/views/verify/verify-account.client.view.html"}).state("forgot",{url:"/password/forgot",templateUrl:"modules/users/views/password/forgot-password.client.view.html"}).state("reset-invalid",{url:"/password/reset/invalid",templateUrl:"modules/users/views/password/reset-password-invalid.client.view.html"}).state("reset-success",{url:"/password/reset/success",templateUrl:"modules/users/views/password/reset-password-success.client.view.html"}).state("reset",{url:"/password/reset/:token",templateUrl:"modules/users/views/password/reset-password.client.view.html"})}]),angular.module("users").controller("AuthenticationController",["$scope","$location","$state","$rootScope","User","Auth",function($scope,$location,$state,$rootScope,User,Auth){$scope=$rootScope,$scope.credentials={},$scope.error="",$scope.signin=function(){User.login($scope.credentials).then(function(response){Auth.login(response),$scope.user=$rootScope.user=Auth.ensureHasCurrentUser(User),"home"!==$state.previous.name&&"verify"!==$state.previous.name&&""!==$state.previous.name?$state.go($state.previous.name):$state.go("listForms")},function(error){$rootScope.user=Auth.ensureHasCurrentUser(User),$scope.user=$rootScope.user,$scope.error=error,console.log("loginError: "+error)})},$scope.signup=function(){User.signup($scope.credentials).then(function(response){console.log("signup-success"),$state.go("signup-success")},function(error){console.log("Error: "),console.log(error),error?($scope.error=error,console.log(error)):console.log("No response received")})}}]),angular.module("users").controller("PasswordController",["$scope","$stateParams","$state","User",function($scope,$stateParams,$state,User){$scope.error="",$scope.askForPasswordReset=function(){User.askForPasswordReset($scope.credentials).then(function(response){$scope.success=response.message,$scope.credentials=null},function(error){$scope.error=error,$scope.credentials=null})},$scope.resetUserPassword=function(){$scope.success=$scope.error=null,User.resetPassword($scope.passwordDetails,$stateParams.token).then(function(response){$scope.success=response.message,$scope.passwordDetails=null,$state.go("reset-success")},function(error){$scope.error=error.message||error,$scope.passwordDetails=null})}}]),angular.module("users").controller("SettingsController",["$scope","$rootScope","$http","$state","Users",function($scope,$rootScope,$http,$state,Users){$scope.user=$rootScope.user,$scope.hasConnectedAdditionalSocialAccounts=function(provider){for(var i in $scope.user.additionalProvidersData)return!0;return!1},$scope.isConnectedSocialAccount=function(provider){return $scope.user.provider===provider||$scope.user.additionalProvidersData&&$scope.user.additionalProvidersData[provider]},$scope.removeUserSocialAccount=function(provider){$scope.success=$scope.error=null,$http["delete"]("/users/accounts",{params:{provider:provider}}).success(function(response){$scope.success=!0,$scope.user=response}).error(function(response){$scope.error=response.message})},$scope.updateUserProfile=function(isValid){if(isValid){$scope.success=$scope.error=null;var user=new Users($scope.user);user.$update(function(response){$scope.success=!0,$scope.user=response},function(response){$scope.error=response.data.message})}else $scope.submitted=!0},$scope.changeUserPassword=function(){$scope.success=$scope.error=null,$http.post("/users/password",$scope.passwordDetails).success(function(response){$scope.success=!0,$scope.passwordDetails=null}).error(function(response){$scope.error=response.message})}}]),angular.module("users").controller("VerifyController",["$scope","$state","$rootScope","User","Auth","$stateParams",function($scope,$state,$rootScope,User,Auth,$stateParams){$scope.isResetSent=!1,$scope.credentials={},$scope.error="",$scope.resendVerifyEmail=function(){User.resendVerifyEmail($scope.credentials.email).then(function(response){console.log(response),$scope.success=response.message,$scope.credentials=null,$scope.isResetSent=!0},function(error){$scope.error=error,$scope.credentials.email=null,$scope.isResetSent=!1})},$scope.validateVerifyToken=function(){$stateParams.token&&(console.log($stateParams.token),User.validateVerifyToken($stateParams.token).then(function(response){console.log("Success: "+response.message),$scope.success=response.message,$scope.isResetSent=!0,$scope.credentials.email=null},function(error){console.log("Error: "+error.message),$scope.isResetSent=!1,$scope.error=error,$scope.credentials.email=null}))}}]),angular.module("users").factory("Auth",["$window",function($window){var userState={isLoggedIn:!1},service={_currentUser:null,get currentUser(){return this._currentUser},ensureHasCurrentUser:function(User){return service._currentUser&&service._currentUser.username?(console.log("Using local current user."),service._currentUser):$window.user?(console.log("Using cached current user."),service._currentUser=$window.user,service._currentUser):(console.log("Fetching current user from the server."),void User.getCurrent().then(function(user){return service._currentUser=user,userState.isLoggedIn=!0,$window.user=service._currentUser,service._currentUser},function(response){return userState.isLoggedIn=!1,service._currentUser=null,$window.user=null,console.log("User.getCurrent() err",response),null}))},isAuthenticated:function(){return!!service._currentUser},getUserState:function(){return userState},login:function(new_user){userState.isLoggedIn=!0,service._currentUser=new_user},logout:function(){$window.user=null,userState.isLoggedIn=!1,service._currentUser=null}};return service}]),angular.module("users").service("Authorizer",["APP_PERMISSIONS","USER_ROLES",function(APP_PERMISSIONS,USER_ROLES){return function(user){return{canAccess:function(permissions){var i,len,permission;for(angular.isArray(permissions)||(permissions=[permissions]),i=0,len=permissions.length;len>i;i++){if(permission=permissions[i],null===APP_PERMISSIONS[permission])throw"Bad permission value";if(!user||!user.roles)return!1;switch(permission){case APP_PERMISSIONS.viewAdminSettings:case APP_PERMISSIONS.editAdminSettings:return user.roles.indexOf(USER_ROLES.admin)>-1;case APP_PERMISSIONS.viewPrivateForm:case APP_PERMISSIONS.editForm:return user.roles.indexOf(USER_ROLES.admin)>-1||user.roles.indexOf(USER_ROLES.normal)>-1}}return!1}}}}]),angular.module("users").factory("User",["$window","$q","$timeout","$http","$state",function($window,$q,$timeout,$http,$state){var userService={getCurrent:function(){var deferred=$q.defer();return $http.get("/users/me").success(function(response){deferred.resolve(response)}).error(function(){deferred.reject("User's session has expired")}),deferred.promise},login:function(credentials){var deferred=$q.defer();return $http.post("/auth/signin",credentials).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},logout:function(){var deferred=$q.defer();return $http.get("/auth/signout").success(function(response){deferred.resolve(null)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},signup:function(credentials){var deferred=$q.defer();return $http.post("/auth/signup",credentials).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},resendVerifyEmail:function(_email){var deferred=$q.defer();return $http.post("/auth/verify",{email:_email}).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},validateVerifyToken:function(token){var validTokenRe=/^([A-Za-z0-9]{48})$/g;if(!validTokenRe.test(token))throw new Error("Error token: "+token+" is not a valid verification token");var deferred=$q.defer();return $http.get("/auth/verify/"+token).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error)}),deferred.promise},resetPassword:function(passwordDetails,token){var deferred=$q.defer();return $http.get("/auth/password/"+token,passwordDetails).success(function(response){deferred.resolve()}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},askForPasswordReset:function(credentials){var deferred=$q.defer();return $http.post("/auth/forgot",credentials).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise}};return userService}]),angular.module("users").factory("Users",["$resource",function($resource){return $resource("users",{},{update:{method:"PUT"}})}]); \ No newline at end of file +templateUrl:"modules/users/views/settings/social-accounts.client.view.html"}).state("signup",{url:"/signup",templateUrl:"modules/users/views/authentication/signup.client.view.html"}).state("signup-success",{url:"/signup-success",templateUrl:"modules/users/views/authentication/signup-success.client.view.html"}).state("signin",{url:"/signin",templateUrl:"modules/users/views/authentication/signin.client.view.html"}).state("access_denied",{url:"/access_denied",templateUrl:"modules/users/views/authentication/access-denied.client.view.html"}).state("resendVerifyEmail",{url:"/verify",templateUrl:"modules/users/views/verify/resend-verify-email.client.view.html"}).state("verify",{url:"/verify/:token",templateUrl:"modules/users/views/verify/verify-account.client.view.html"}).state("forgot",{url:"/password/forgot",templateUrl:"modules/users/views/password/forgot-password.client.view.html"}).state("reset-invalid",{url:"/password/reset/invalid",templateUrl:"modules/users/views/password/reset-password-invalid.client.view.html"}).state("reset-success",{url:"/password/reset/success",templateUrl:"modules/users/views/password/reset-password-success.client.view.html"}).state("reset",{url:"/password/reset/:token",templateUrl:"modules/users/views/password/reset-password.client.view.html"})}]),angular.module("users").controller("AuthenticationController",["$scope","$location","$state","$rootScope","User","Auth",function($scope,$location,$state,$rootScope,User,Auth){$scope=$rootScope,$scope.credentials={},$scope.error="",$scope.signin=function(){$scope.credentials.email=$scope.credentials.username,User.login($scope.credentials).then(function(response){Auth.login(response),$scope.user=$rootScope.user=Auth.ensureHasCurrentUser(User),"home"!==$state.previous.name&&"verify"!==$state.previous.name&&""!==$state.previous.name?$state.go($state.previous.name):$state.go("listForms")},function(error){$rootScope.user=Auth.ensureHasCurrentUser(User),$scope.user=$rootScope.user,$scope.error=error,console.log("loginError: "+error)})},$scope.signup=function(){console.log($scope.credentials),User.signup($scope.credentials).then(function(response){console.log("signup-success"),$state.go("signup-success")},function(error){console.log("Error: "),console.log(error),error?($scope.error=error,console.log(error)):console.log("No response received")})}}]),angular.module("users").controller("PasswordController",["$scope","$stateParams","$state","User",function($scope,$stateParams,$state,User){$scope.error="",$scope.askForPasswordReset=function(){User.askForPasswordReset($scope.credentials).then(function(response){$scope.success=response.message,$scope.credentials=null},function(error){$scope.error=error,$scope.credentials=null})},$scope.resetUserPassword=function(){$scope.success=$scope.error=null,User.resetPassword($scope.passwordDetails,$stateParams.token).then(function(response){$scope.success=response.message,$scope.passwordDetails=null,$state.go("reset-success")},function(error){$scope.error=error.message||error,$scope.passwordDetails=null})}}]),angular.module("users").controller("SettingsController",["$scope","$rootScope","$http","$state","Users",function($scope,$rootScope,$http,$state,Users){$scope.user=$rootScope.user,$scope.hasConnectedAdditionalSocialAccounts=function(provider){for(var i in $scope.user.additionalProvidersData)return!0;return!1},$scope.isConnectedSocialAccount=function(provider){return $scope.user.provider===provider||$scope.user.additionalProvidersData&&$scope.user.additionalProvidersData[provider]},$scope.removeUserSocialAccount=function(provider){$scope.success=$scope.error=null,$http["delete"]("/users/accounts",{params:{provider:provider}}).success(function(response){$scope.success=!0,$scope.user=response}).error(function(response){$scope.error=response.message})},$scope.updateUserProfile=function(isValid){if(isValid){$scope.success=$scope.error=null;var user=new Users($scope.user);user.$update(function(response){$scope.success=!0,$scope.user=response},function(response){$scope.error=response.data.message})}else $scope.submitted=!0},$scope.changeUserPassword=function(){$scope.success=$scope.error=null,$http.post("/users/password",$scope.passwordDetails).success(function(response){$scope.success=!0,$scope.passwordDetails=null}).error(function(response){$scope.error=response.message})}}]),angular.module("users").controller("VerifyController",["$scope","$state","$rootScope","User","Auth","$stateParams",function($scope,$state,$rootScope,User,Auth,$stateParams){$scope.isResetSent=!1,$scope.credentials={},$scope.error="",$scope.resendVerifyEmail=function(){User.resendVerifyEmail($scope.credentials.email).then(function(response){console.log(response),$scope.success=response.message,$scope.credentials=null,$scope.isResetSent=!0},function(error){$scope.error=error,$scope.credentials.email=null,$scope.isResetSent=!1})},$scope.validateVerifyToken=function(){$stateParams.token&&(console.log($stateParams.token),User.validateVerifyToken($stateParams.token).then(function(response){console.log("Success: "+response.message),$scope.success=response.message,$scope.isResetSent=!0,$scope.credentials.email=null},function(error){console.log("Error: "+error.message),$scope.isResetSent=!1,$scope.error=error,$scope.credentials.email=null}))}}]),angular.module("users").factory("Auth",["$window",function($window){var userState={isLoggedIn:!1},service={_currentUser:null,get currentUser(){return this._currentUser},ensureHasCurrentUser:function(User){return service._currentUser&&service._currentUser.username?(console.log("Using local current user."),service._currentUser):$window.user?(console.log("Using cached current user."),service._currentUser=$window.user,service._currentUser):(console.log("Fetching current user from the server."),void User.getCurrent().then(function(user){return service._currentUser=user,userState.isLoggedIn=!0,$window.user=service._currentUser,service._currentUser},function(response){return userState.isLoggedIn=!1,service._currentUser=null,$window.user=null,console.log("User.getCurrent() err",response),null}))},isAuthenticated:function(){return!!service._currentUser},getUserState:function(){return userState},login:function(new_user){userState.isLoggedIn=!0,service._currentUser=new_user},logout:function(){$window.user=null,userState.isLoggedIn=!1,service._currentUser=null}};return service}]),angular.module("users").service("Authorizer",["APP_PERMISSIONS","USER_ROLES",function(APP_PERMISSIONS,USER_ROLES){return function(user){return{canAccess:function(permissions){var i,len,permission;for(angular.isArray(permissions)||(permissions=[permissions]),i=0,len=permissions.length;len>i;i++){if(permission=permissions[i],null===APP_PERMISSIONS[permission])throw"Bad permission value";if(!user||!user.roles)return!1;switch(permission){case APP_PERMISSIONS.viewAdminSettings:case APP_PERMISSIONS.editAdminSettings:return user.roles.indexOf(USER_ROLES.admin)>-1;case APP_PERMISSIONS.viewPrivateForm:case APP_PERMISSIONS.editForm:return user.roles.indexOf(USER_ROLES.admin)>-1||user.roles.indexOf(USER_ROLES.normal)>-1}}return!1}}}}]),angular.module("users").factory("User",["$window","$q","$timeout","$http","$state",function($window,$q,$timeout,$http,$state){var userService={getCurrent:function(){var deferred=$q.defer();return $http.get("/users/me").success(function(response){deferred.resolve(response)}).error(function(){deferred.reject("User's session has expired")}),deferred.promise},login:function(credentials){var deferred=$q.defer();return $http.post("/auth/signin",credentials).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},logout:function(){var deferred=$q.defer();return $http.get("/auth/signout").success(function(response){deferred.resolve(null)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},signup:function(credentials){var deferred=$q.defer();return $http.post("/auth/signup",credentials).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},resendVerifyEmail:function(_email){var deferred=$q.defer();return $http.post("/auth/verify",{email:_email}).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},validateVerifyToken:function(token){var validTokenRe=/^([A-Za-z0-9]{48})$/g;if(!validTokenRe.test(token))throw new Error("Error token: "+token+" is not a valid verification token");var deferred=$q.defer();return $http.get("/auth/verify/"+token).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error)}),deferred.promise},resetPassword:function(passwordDetails,token){var deferred=$q.defer();return $http.get("/auth/password/"+token,passwordDetails).success(function(response){deferred.resolve()}).error(function(error){deferred.reject(error.message||error)}),deferred.promise},askForPasswordReset:function(credentials){var deferred=$q.defer();return $http.post("/auth/forgot",credentials).success(function(response){deferred.resolve(response)}).error(function(error){deferred.reject(error.message||error)}),deferred.promise}};return userService}]),angular.module("users").factory("Users",["$resource",function($resource){return $resource("users",{},{update:{method:"PUT"}})}]); \ No newline at end of file