got all tests to run

This commit is contained in:
David Baldwynn 2016-03-29 20:45:16 -07:00
parent 8c4129380b
commit d55775ddfc
15 changed files with 389 additions and 380 deletions

View file

@ -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({

View file

@ -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.');
};
/**

View file

@ -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();
}
};

View file

@ -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);

View file

@ -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']

View file

@ -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

View file

@ -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: '<rdohip></rdohip><rd></rd>',
// 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: '<rdohip></rdohip><rd></rd>',
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);
});
});
});

View file

@ -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')

View file

@ -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<submissionFields.length; z++){
submissionFields[z] = _.extend(myForm.form_fields[z], sampleSubmission[z]);
}
mySubmission = new FormSubmission({
admin: user._id,
admin: user._id,
form: myForm._id,
timeElapsed: 17.55,
form_fields: submissionFields
});
done();
});
});
@ -175,7 +188,7 @@ describe('FormSubmission Model Unit Tests:', function() {
// };
// async.waterfall([
// function (callback) {
// function (callback) {
// //Authenticate with API
// soap.createClient(url_login, options, function(err, client) {
// client.login(args_login, function (err, result) {
@ -203,7 +216,7 @@ describe('FormSubmission Model Unit Tests:', function() {
// console.log(result.return);
// done();
// });
// });
// });
});
@ -234,69 +247,73 @@ describe('FormSubmission Model Unit Tests:', function() {
});
describe('Test FormField and Submission Logic', function() {
var new_form_fields_add1, new_form_fields_del;
beforeEach(function(done){
new_form_fields_add1 = _.clone(myForm.toObject().form_fields);
new_form_fields_add1.push(
{'fieldType':'textfield', 'title':'Last Name', 'fieldValue': ''}
);
//Create Submission
mySubmission = new FormSubmission({
form_fields: sampleSubmission,
admin: user,
admin: user,
form: myForm,
timeElapsed: 17.55
});
});
mySubmission.save(function(err){
should.not.exist(err);
done();
});
});
// it('should preserve deleted form_fields that have submissions without any problems', function(done) {
// var old_fields = myForm.toObject().form_fields;
// var new_form_fields = _.clone(myForm.toObject().form_fields);
// new_form_fields.splice(0, 1);
it('should preserve deleted form_fields that have submissions without any problems', function(done) {
// myForm.form_fields = new_form_fields;
var old_fields = myForm.toObject().form_fields;
var new_form_fields = _.clone(myForm.toObject().form_fields);
new_form_fields.splice(0, 1);
// myForm.save(function(err, _form) {
myForm.form_fields = new_form_fields;
// should.not.exist(err);
// should.exist(_form);
myForm.save(function(err, _form) {
// // var actual_fields = _.map(_form.toObject().form_fields, function(o){ _.omit(o, '_id')});
// // old_fields = _.map(old_fields, function(o){ _.omit(o, '_id')});
should.not.exist(err);
should.exist(_form.form_fields);
// // console.log(old_fields);
// should.deepEqual(JSON.stringify(_form.toObject().form_fields), JSON.stringify(old_fields), 'old form_fields not equal to newly saved form_fields');
// done();
// });
// });
var actual_fields = _.deepOmit(_form.toObject().form_fields, ['lastModified', 'created', '_id']);
old_fields = _.deepOmit(old_fields, ['lastModified', 'created', '_id']);
// it('should delete \'preserved\' form_fields whose submissions have been removed without any problems', function(done) {
should.deepEqual(JSON.stringify(actual_fields), JSON.stringify(old_fields), 'old form_fields not equal to newly saved form_fields');
done();
});
});
//
it('should delete \'preserved\' form_fields whose submissions have been removed without any problems', function(done) {
// myForm.form_fields = new_form_fields_del;
// myForm.save(function(err, form
// should.not.exist(err);
// (form.form_fields).should.be.eql(old_fields, 'old form_fields not equal to newly saved form_fields');
// //Remove submission
// mySubmission.remove(function(err){
// myForm.submissions.should.have.length(0);
// myForm.form_fields.should.not.containDeep(old_fields[0]);
// });
// });
// });
var old_fields = myForm.toObject().form_fields;
var new_form_fields = _.clone(myForm.toObject().form_fields);
new_form_fields.splice(0, 1);
myForm.form_fields = new_form_fields;
myForm.save(function(err, _form){
should.not.exist(err);
should.exist(_form.form_fields);
should.exist(old_fields);
var actual_fields = _.deepOmit(_form.toObject().form_fields, ['lastModified', 'created', '_id']);
old_fields = _.deepOmit(old_fields, ['lastModified', 'created', '_id']);
should.deepEqual(JSON.stringify(actual_fields), JSON.stringify(old_fields)); //'old form_fields not equal to newly saved form_fields');
done();
// //Remove submission
// mySubmission.remove(function(err){
// myForm.submissions.should.have.length(0);
// myForm.form_fields.should.not.containDeep(old_fields[0]);
// done();
// });
});
});
afterEach(function(done){
mySubmission.remove(function(){
done();

View file

@ -15,20 +15,19 @@ var should = require('should'),
/**
* Globals
*/
var credentials, user, userSession;
var credentials, user;
/**
* Form routes tests
*/
describe('Form Routes Unit tests', function() {
describe('Form Submission Routes Unit tests', function() {
var FormObj, _Submission, submissionSession;
beforeEach(function(done) {
//Initialize Session
userSession = new Session();
beforeEach(function(done) {
// Create user credentials
credentials = {
email: 'test@test.com',
username: 'test@test.com',
password: 'password'
};
@ -46,7 +45,7 @@ describe('Form Routes Unit tests', function() {
// Save a user to the test db and create new Form
user.save(function(err) {
if(err) return done(err);
FormObj = {
FormObj = new Form({
title: 'Form Title',
language: 'english',
admin: user._id,
@ -55,7 +54,7 @@ describe('Form Routes Unit tests', function() {
new Field({'fieldType':'checkbox', 'title':'nascar', 'fieldValue': ''}),
new Field({'fieldType':'checkbox', 'title':'hockey', 'fieldValue': ''})
]
};
});
FormObj.save(function(err, form) {
if (err) done(err);
@ -74,8 +73,8 @@ describe('Form Routes Unit tests', function() {
FormObj = form;
//Setup test session
submissionSession = new Session();
//Initialize Session
submissionSession = Session(app);
done();
});
@ -98,21 +97,21 @@ describe('Form Routes Unit tests', function() {
});
it(' > 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) {

View file

@ -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();
// });
});

View file

@ -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) {

View file

@ -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"
}
}

View file

@ -412,7 +412,7 @@ angular.module('NodeForm.templates', []).run(['$templateCache', function($templa
$templateCache.put("../public/modules/users/views/authentication/signup-success.client.view.html",
"<section class=\"row auth signup-view success\" data-ng-controller=AuthenticationController><h3 class=\"col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6 text-center\">Signup Successful</h3><div class=\"col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6\"><h2>You've successfully registered an account at TellForm.<br><br>But your account is <b>not activated yet</b></h2><br><br><p>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 <a href=mail:hi@tellform.com>hi@TellForm.com</a></p><div class=\"text-center form-group\"><button type=submit class=\"btn btn-large btn-primary\"><a href=\"/#!/\" style=\"color: white; text-decoration: none\">Continue</a></button></div></div></section>");
$templateCache.put("../public/modules/users/views/authentication/signup.client.view.html",
"<section class=\"row auth signup-view\" data-ng-controller=AuthenticationController><h3 class=\"col-md-12 text-center\">Signup with your email</h3><div class=\"col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6\"><form name=userForm data-ng-submit=signup() class=\"signin form-horizontal\" novalidate autocomplete=off><fieldset><div data-ng-show=error id=signup_errors class=\"text-center text-danger\">Couldn't submit form due to errors:<br><strong data-ng-bind=error></strong></div><div class=form-group><label for=firstName>First Name</label><input ng-pattern=\"/^[a-zA-Z0-9 \\-.]*$/\" required id=firstName name=firstName class=form-control data-ng-model=credentials.firstName placeholder=\"First Name\"></div><div class=form-group><label for=lastName>Last Name</label><input ng-pattern=\"/^[a-zA-Z0-9 \\-.]*$/\" required id=lastName name=lastName class=form-control data-ng-model=credentials.lastName placeholder=\"Last Name\"></div><hr><div class=form-group><label for=email>Email</label><input type=email id=email name=email class=form-control data-ng-model=credentials.email placeholder=Email></div><div class=form-group><label for=password>Password</label><input type=password id=password name=password class=form-control data-ng-model=credentials.password placeholder=Password></div><div class=\"text-center form-group\"><button type=submit class=\"btn btn-large btn-primary\">Sign up</button></div></fieldset></form></div></section>");
"<section class=\"row auth signup-view\" data-ng-controller=AuthenticationController><h3 class=\"col-md-12 text-center\">Signup with your email</h3><div class=\"col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6\"><form name=userForm data-ng-submit=signup() class=\"signin form-horizontal\" novalidate autocomplete=off><fieldset><div data-ng-show=error id=signup_errors class=\"text-center text-danger\">Couldn't submit form due to errors:<br><strong data-ng-bind=error></strong></div><div class=form-group><label for=firstName>First Name</label><input ng-pattern=\"/^[a-zA-Z0-9 \\-.]*$/\" required id=firstName name=firstName class=form-control ng-model=credentials.firstName placeholder=\"First Name\"></div><div class=form-group><label for=lastName>Last Name</label><input ng-pattern=\"/^[a-zA-Z0-9 \\-.]*$/\" required id=lastName name=lastName class=form-control ng-model=credentials.lastName placeholder=\"Last Name\"></div><hr><div class=form-group><label for=email>Email</label><input type=email id=email name=email class=form-control ng-model=credentials.email placeholder=Email></div><div class=form-group><label for=password>Password</label><input type=password id=password name=password class=form-control ng-model=credentials.password placeholder=Password></div><div class=\"text-center form-group\"><button type=submit class=\"btn btn-large btn-primary\">Sign up</button></div></fieldset></form></div></section>");
$templateCache.put("../public/modules/users/views/password/forgot-password.client.view.html",
"<section class=\"auth row\" data-ng-controller=PasswordController><h3 class=\"col-md-12 text-center\">Restore your password</h3><p class=\"small text-center\">Enter your account email.</p><div class=\"col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6\"><form data-ng-submit=askForPasswordReset() class=\"signin form-horizontal\" autocomplete=off><fieldset><div class=form-group><input id=username name=username class=form-control data-ng-model=credentials.username placeholder=Username></div><div class=\"text-center form-group\"><button type=submit class=\"btn btn-primary\">Submit</button></div><div data-ng-show=error class=\"text-center text-danger\"><strong>{{error}}</strong></div><div data-ng-show=success class=\"text-center text-success\"><strong>{{success}}</strong></div></fieldset></form></div></section>");
$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');

File diff suppressed because one or more lines are too long