From 06e6780cd1eeee68564594b20f601bebace4f48b Mon Sep 17 00:00:00 2001 From: David Baldwynn Date: Tue, 29 Mar 2016 18:16:36 -0700 Subject: [PATCH] fixed routing --- .../users.authentication.server.controller.js | 92 +- app/models/user.server.model.js | 33 +- config/express.js | 28 +- public/dist/application.js | 551 +++++++++--- public/dist/application.min.css | 4 +- public/dist/application.min.js | 6 +- .../authentication.client.controller.js | 4 +- .../authentication/signup.client.view.html | 10 +- public/populate_template_cache.js | 2 +- request | 842 ++++++++++++++++++ 10 files changed, 1374 insertions(+), 198 deletions(-) create mode 100644 request diff --git a/app/controllers/users/users.authentication.server.controller.js b/app/controllers/users/users.authentication.server.controller.js index 68242775..1850cc1f 100755 --- a/app/controllers/users/users.authentication.server.controller.js +++ b/app/controllers/users/users.authentication.server.controller.js @@ -47,7 +47,7 @@ var config_nev = function () { } else { console.log(info); } - }, + } }); nev.generateTempUserModel(User); @@ -59,10 +59,10 @@ var smtpTransport = nodemailer.createTransport(config.mailer.options); exports.validateVerificationToken = function(req, res){ nev.confirmTempUser(req.params.token, function(err, user) { - if(err) { + if(err) { console.log(errorHandler.getErrorMessage(err)); return res.status(500).send( {message: errorHandler.getErrorMessage(err) } ); - } + } else if (user){ return res.status(200).send('User successfully verified'); }else { @@ -74,10 +74,10 @@ exports.validateVerificationToken = function(req, res){ exports.resendVerificationEmail = function(req, res, next){ nev.resendVerificationEmail(req.body.email, function(err, userFound) { - if(err) { + if(err) { console.log(errorHandler.getErrorMessage(err)); return res.status(500).send( {message: errorHandler.getErrorMessage(err) } ); - } + } if (userFound){ console.log('hello'); @@ -89,58 +89,64 @@ exports.resendVerificationEmail = function(req, res, next){ }); }; - /** * Signup */ exports.signup = function(req, res) { - // For security measurement we remove the roles from the req.body object - delete req.body.roles; + console.log(req.body); + // For security measures we remove the roles from the req.body object + if (req.body) { + delete req.body.roles; + console.log(req.body); - // Init Variables - var user = new User(req.body); + // Init Variables + var user = new User(req.body); - // Add missing user fields - user.provider = 'local'; - user.username = user.email; + // Add missing user fields + user.provider = 'local'; + user.username = user.email; - // Then save the temporary user - nev.createTempUser(user, function(err, newTempUser) { - - if (err) { - console.log('Error: '); - console.log(err); - return res.status(400).send({ - message: errorHandler.getErrorMessage(err) - }); - }else { + // Then save the temporary user + nev.createTempUser(user, function (err, newTempUser) { - // new user created - if (newTempUser) { - nev.registerTempUser(newTempUser, function (err) { - if (err) { - console.log('Error: '); - console.log(err); - return res.status(400).send({ - 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.'); - } - }); - } else { - console.log('Error: User already exists!'); - return res.status(400).send({ message: 'Error: User already exists!' }); - } - } - }); + if (err) { + console.log('Error: '); + console.log(err); + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + + // new user created + if (newTempUser) { + nev.registerTempUser(newTempUser, function (err) { + if (err) { + console.log('Error: '); + console.log(err); + return res.status(400).send({ + 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.'); + } + }); + } else { + console.log('Error: User already exists!'); + return res.status(400).send({message: 'Error: User already exists!'}); + } + } + }); + } else { + res.status(500).send('Incomplete Data'); + } }; /** * 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); diff --git a/app/models/user.server.model.js b/app/models/user.server.model.js index 8ced579a..7b72fced 100755 --- a/app/models/user.server.model.js +++ b/app/models/user.server.model.js @@ -33,20 +33,43 @@ var UserSchema = new Schema({ type: String, trim: true, default: '', - validate: [validateLocalStrategyProperty, 'Please fill in your first name'] + validate: { + validator: function(property) { + return ((this.provider !== 'local' && !this.updated) || property.length); + }, + message: 'Please fill in your first name' + } }, lastName: { type: String, trim: true, default: '', - validate: [validateLocalStrategyProperty, 'Please fill in your last name'] + validate: { + validator: function(property) { + console.log(property); + return ((this.provider !== 'local' && !this.updated) || property.length); + }, + message: 'Please fill in your last name' + } }, email: { type: String, trim: true, unique: 'Account already exists with this email', required: 'Please enter your email', - validate: [validateLocalStrategyProperty, 'Please fill in your email'], + validate: { + validator: function(property) { + var propHasLength; + if (property) { + propHasLength = !!property.length; + } else { + propHasLength = false; + } + + return ((this.provider !== 'local' && !this.updated) || propHasLength); + }, + message: 'Please fill in your email' + }, match: [/.+\@.+\..+/, 'Please fill a valid email address'] }, username: { @@ -57,7 +80,7 @@ var UserSchema = new Schema({ }, passwordHash: { type: String, - default: '', + default: '' }, salt: { type: String @@ -127,7 +150,7 @@ UserSchema.pre('save', function (next) { }else{ next(); } - } + } next(); }); diff --git a/config/express.js b/config/express.js index b0ccbd18..370464ed 100755 --- a/config/express.js +++ b/config/express.js @@ -32,16 +32,6 @@ module.exports = function(db) { // Initialize express app var app = express(); - // Globbing model files - config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) { - require(path.resolve(modelPath)); - }); - - // Globbing routing files - config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) { - require(path.resolve(routePath))(app); - }); - // Setting application local variables app.locals.title = config.app.title; app.locals.description = config.app.description; @@ -77,7 +67,6 @@ module.exports = function(db) { // Showing stack errors app.set('showStackError', true); - // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); @@ -103,6 +92,16 @@ module.exports = function(db) { app.use(bodyParser.json()); app.use(methodOverride()); + // Globbing model files + config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) { + require(path.resolve(modelPath)); + }); + + // Globbing routing files + config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) { + require(path.resolve(routePath))(app); + }); + // Use helmet to secure Express headers app.use(helmet.xframe()); app.use(helmet.xssFilter()); @@ -141,6 +140,7 @@ module.exports = function(db) { app.use(flash()); // Add headers for Sentry + /* app.use(function (req, res, next) { // Website you wish to allow to connect @@ -159,12 +159,12 @@ module.exports = function(db) { // Pass to next layer of middleware next(); }); - + */ // Sentry (Raven) middleware - app.use(raven.middleware.express.requestHandler(config.DSN)); + // app.use(raven.middleware.express.requestHandler(config.DSN)); // Should come before any other error middleware - app.use(raven.middleware.express.errorHandler(config.DSN)); + // app.use(raven.middleware.express.errorHandler(config.DSN)); // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use(function(err, req, res, next) { diff --git a/public/dist/application.js b/public/dist/application.js index 1dfa89cd..9c784fc1 100644 --- a/public/dist/application.js +++ b/public/dist/application.js @@ -1,5 +1,28 @@ 'use strict'; +// Init the application configuration module for AngularJS application +var ApplicationConfiguration = (function() { + // Init module configuration options + var applicationModuleName = 'NodeForm'; + var applicationModuleVendorDependencies = ['ngResource', 'NodeForm.templates', 'ngAnimate', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven', 'cgBusy']; + + // Add a new vertical module + var registerModule = function(moduleName, dependencies) { + // Create angular module + angular.module(moduleName, dependencies || []); + + // Add the module to the AngularJS configuration file + angular.module(applicationModuleName).requires.push(moduleName); + }; + + return { + applicationModuleName: applicationModuleName, + applicationModuleVendorDependencies: applicationModuleVendorDependencies, + registerModule: registerModule + }; +})(); +'use strict'; + //Start by defining the main module and adding the module dependencies angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); @@ -85,35 +108,12 @@ angular.element(document).ready(function() { //Then init the app angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); }); -'use strict'; - -// Init the application configuration module for AngularJS application -var ApplicationConfiguration = (function() { - // Init module configuration options - var applicationModuleName = 'TellForm'; - var applicationModuleVendorDependencies = ['ngResource', 'TellForm.templates', 'ngAnimate', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven', 'cgBusy']; - - // Add a new vertical module - var registerModule = function(moduleName, dependencies) { - // Create angular module - angular.module(moduleName, dependencies || []); - - // Add the module to the AngularJS configuration file - angular.module(applicationModuleName).requires.push(moduleName); - }; - - return { - applicationModuleName: applicationModuleName, - applicationModuleVendorDependencies: applicationModuleVendorDependencies, - registerModule: registerModule - }; -})(); -angular.module('TellForm.templates', []).run(['$templateCache', function($templateCache) { +angular.module('NodeForm.templates', []).run(['$templateCache', function($templateCache) { "use strict"; $templateCache.put("../public/modules/core/views/header.client.view.html", "
"); $templateCache.put("../public/modules/core/views/home.client.view.html", - "

TellForm

Craft beautiful forms in seconds.

Craft beautiful forms.

TellForm is an opensource alternative to TypeForm that can create stunning forms from PDFs or from scratch

TellForm is an opensource alternative to TypeForm that can create stunning forms from PDFs or from scratch

Create your next ______.

Tell a story with a form.

TellForm is an opensource alternative to TypeForm that can create stunning forms from PDFs or from scratch

TellForm is an opensource alternative to TypeForm that can create stunning forms from PDFs or from scratch

"); + "

TellForm

Craft beautiful forms in seconds.

Craft beautiful forms.

TellForm is an opensource alternative to TypeForm that can create stunning forms from PDFs or from scratch

TellForm is an opensource alternative to TypeForm that can create stunning forms from PDFs or from scratch

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/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 diff --git a/public/modules/users/controllers/authentication.client.controller.js b/public/modules/users/controllers/authentication.client.controller.js index 98dcda59..eaede4b1 100755 --- a/public/modules/users/controllers/authentication.client.controller.js +++ b/public/modules/users/controllers/authentication.client.controller.js @@ -8,6 +8,7 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca $scope.error = ''; $scope.signin = function() { + $scope.credentials.email = $scope.credentials.username; User.login($scope.credentials).then( function(response) { Auth.login(response); @@ -30,6 +31,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'); @@ -49,4 +51,4 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca }; } -]); \ No newline at end of file +]); diff --git a/public/modules/users/views/authentication/signup.client.view.html b/public/modules/users/views/authentication/signup.client.view.html index 09cd7d8d..f66c3f6b 100644 --- a/public/modules/users/views/authentication/signup.client.view.html +++ b/public/modules/users/views/authentication/signup.client.view.html @@ -27,20 +27,20 @@
- +
- +

- +
- +
@@ -49,4 +49,4 @@
- \ No newline at end of file + diff --git a/public/populate_template_cache.js b/public/populate_template_cache.js index 591d8071..1233ea82 100644 --- a/public/populate_template_cache.js +++ b/public/populate_template_cache.js @@ -302,7 +302,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", diff --git a/request b/request new file mode 100644 index 00000000..fccbc292 --- /dev/null +++ b/request @@ -0,0 +1,842 @@ +IncomingMessage { + _readableState: + ReadableState { + objectMode: false, + highWaterMark: 16384, + buffer: [], + length: 0, + pipes: null, + pipesCount: 0, + flowing: null, + ended: false, + endEmitted: false, + reading: false, + sync: true, + needReadable: false, + emittedReadable: false, + readableListening: false, + resumeScheduled: false, + defaultEncoding: 'utf8', + ranOut: false, + awaitDrain: 0, + readingMore: false, + decoder: null, + encoding: null }, + readable: true, + domain: null, + _events: {}, + _eventsCount: 0, + _maxListeners: undefined, + socket: + Socket { + _connecting: false, + _hadError: false, + _handle: + TCP { + _externalStream: {}, + fd: 31, + reading: true, + owner: [Circular], + onread: [Function: onread], + onconnection: null, + writeQueueSize: 0 }, + _parent: null, + _host: null, + _readableState: + ReadableState { + objectMode: false, + highWaterMark: 16384, + buffer: [], + length: 0, + pipes: null, + pipesCount: 0, + flowing: true, + ended: false, + endEmitted: false, + reading: true, + sync: false, + needReadable: true, + emittedReadable: false, + readableListening: false, + resumeScheduled: false, + defaultEncoding: 'utf8', + ranOut: false, + awaitDrain: 0, + readingMore: false, + decoder: null, + encoding: null }, + readable: true, + domain: null, + _events: + { end: [Object], + finish: [Function: onSocketFinish], + _socketEnd: [Function: onSocketEnd], + drain: [Object], + timeout: [Function], + error: [Object], + close: [Object], + data: [Function: socketOnData], + resume: [Function: onSocketResume], + pause: [Function: onSocketPause] }, + _eventsCount: 10, + _maxListeners: undefined, + _writableState: + WritableState { + objectMode: false, + highWaterMark: 16384, + needDrain: false, + ending: false, + ended: false, + finished: false, + decodeStrings: false, + defaultEncoding: 'utf8', + length: 0, + writing: false, + corked: 0, + sync: false, + bufferProcessing: false, + onwrite: [Function], + writecb: null, + writelen: 0, + bufferedRequest: null, + lastBufferedRequest: null, + pendingcb: 0, + prefinished: false, + errorEmitted: false, + bufferedRequestCount: 0, + corkedRequestsFree: [Object] }, + writable: true, + allowHalfOpen: true, + destroyed: false, + bytesRead: 0, + _bytesDispatched: 6281, + _sockname: null, + _pendingData: null, + _pendingEncoding: '', + server: + Server { + domain: null, + _events: [Object], + _eventsCount: 3, + _maxListeners: undefined, + _connections: 6, + _handle: [Object], + _usingSlaves: false, + _slaves: [], + _unref: false, + allowHalfOpen: true, + pauseOnConnect: false, + httpAllowHalfOpen: false, + timeout: 120000, + _pendingResponseData: 0, + _connectionKey: '6::::3000' }, + _server: + Server { + domain: null, + _events: [Object], + _eventsCount: 3, + _maxListeners: undefined, + _connections: 6, + _handle: [Object], + _usingSlaves: false, + _slaves: [], + _unref: false, + allowHalfOpen: true, + pauseOnConnect: false, + httpAllowHalfOpen: false, + timeout: 120000, + _pendingResponseData: 0, + _connectionKey: '6::::3000' }, + _idleTimeout: 120000, + _idleNext: + Socket { + _connecting: false, + _hadError: false, + _handle: [Object], + _parent: null, + _host: null, + _readableState: [Object], + readable: true, + domain: null, + _events: [Object], + _eventsCount: 10, + _maxListeners: undefined, + _writableState: [Object], + writable: true, + allowHalfOpen: true, + destroyed: false, + bytesRead: 0, + _bytesDispatched: 4792, + _sockname: null, + _pendingData: null, + _pendingEncoding: '', + server: [Object], + _server: [Object], + _idleTimeout: 120000, + _idleNext: [Object], + _idlePrev: [Circular], + _idleStart: 5391, + parser: [Object], + on: [Function: socketOnWrap], + _paused: false, + read: [Function], + _consuming: true, + _httpMessage: null, + _peername: [Object] }, + _idlePrev: + TimersList { + _idleNext: [Circular], + _idlePrev: [Object], + _timer: [Object], + _unrefed: true, + msecs: 120000 }, + _idleStart: 6269, + parser: + HTTPParser { + '0': [Function: parserOnHeaders], + '1': [Function: parserOnHeadersComplete], + '2': [Function: parserOnBody], + '3': [Function: parserOnMessageComplete], + '4': [Function: onParserExecute], + _headers: [], + _url: '', + _consumed: true, + socket: [Circular], + incoming: [Circular], + outgoing: null, + maxHeaderPairs: 2000, + onIncoming: [Function: parserOnIncoming] }, + on: [Function: socketOnWrap], + _paused: false, + read: [Function], + _consuming: true, + _httpMessage: + ServerResponse { + domain: null, + _events: [Object], + _eventsCount: 1, + _maxListeners: undefined, + output: [], + outputEncodings: [], + outputCallbacks: [], + outputSize: 0, + writable: true, + _last: false, + chunkedEncoding: false, + shouldKeepAlive: true, + useChunkedEncodingByDefault: true, + sendDate: true, + _removedHeader: {}, + _contentLength: null, + _hasBody: true, + _trailer: '', + finished: false, + _headerSent: false, + socket: [Circular], + connection: [Circular], + _header: null, + _headers: null, + _headerNames: {}, + _onPendingData: [Function: updateOutgoingData], + req: [Circular], + locals: {} }, + _peername: { address: '::1', family: 'IPv6', port: 50247 } }, + connection: + Socket { + _connecting: false, + _hadError: false, + _handle: + TCP { + _externalStream: {}, + fd: 31, + reading: true, + owner: [Circular], + onread: [Function: onread], + onconnection: null, + writeQueueSize: 0 }, + _parent: null, + _host: null, + _readableState: + ReadableState { + objectMode: false, + highWaterMark: 16384, + buffer: [], + length: 0, + pipes: null, + pipesCount: 0, + flowing: true, + ended: false, + endEmitted: false, + reading: true, + sync: false, + needReadable: true, + emittedReadable: false, + readableListening: false, + resumeScheduled: false, + defaultEncoding: 'utf8', + ranOut: false, + awaitDrain: 0, + readingMore: false, + decoder: null, + encoding: null }, + readable: true, + domain: null, + _events: + { end: [Object], + finish: [Function: onSocketFinish], + _socketEnd: [Function: onSocketEnd], + drain: [Object], + timeout: [Function], + error: [Object], + close: [Object], + data: [Function: socketOnData], + resume: [Function: onSocketResume], + pause: [Function: onSocketPause] }, + _eventsCount: 10, + _maxListeners: undefined, + _writableState: + WritableState { + objectMode: false, + highWaterMark: 16384, + needDrain: false, + ending: false, + ended: false, + finished: false, + decodeStrings: false, + defaultEncoding: 'utf8', + length: 0, + writing: false, + corked: 0, + sync: false, + bufferProcessing: false, + onwrite: [Function], + writecb: null, + writelen: 0, + bufferedRequest: null, + lastBufferedRequest: null, + pendingcb: 0, + prefinished: false, + errorEmitted: false, + bufferedRequestCount: 0, + corkedRequestsFree: [Object] }, + writable: true, + allowHalfOpen: true, + destroyed: false, + bytesRead: 0, + _bytesDispatched: 6281, + _sockname: null, + _pendingData: null, + _pendingEncoding: '', + server: + Server { + domain: null, + _events: [Object], + _eventsCount: 3, + _maxListeners: undefined, + _connections: 6, + _handle: [Object], + _usingSlaves: false, + _slaves: [], + _unref: false, + allowHalfOpen: true, + pauseOnConnect: false, + httpAllowHalfOpen: false, + timeout: 120000, + _pendingResponseData: 0, + _connectionKey: '6::::3000' }, + _server: + Server { + domain: null, + _events: [Object], + _eventsCount: 3, + _maxListeners: undefined, + _connections: 6, + _handle: [Object], + _usingSlaves: false, + _slaves: [], + _unref: false, + allowHalfOpen: true, + pauseOnConnect: false, + httpAllowHalfOpen: false, + timeout: 120000, + _pendingResponseData: 0, + _connectionKey: '6::::3000' }, + _idleTimeout: 120000, + _idleNext: + Socket { + _connecting: false, + _hadError: false, + _handle: [Object], + _parent: null, + _host: null, + _readableState: [Object], + readable: true, + domain: null, + _events: [Object], + _eventsCount: 10, + _maxListeners: undefined, + _writableState: [Object], + writable: true, + allowHalfOpen: true, + destroyed: false, + bytesRead: 0, + _bytesDispatched: 4792, + _sockname: null, + _pendingData: null, + _pendingEncoding: '', + server: [Object], + _server: [Object], + _idleTimeout: 120000, + _idleNext: [Object], + _idlePrev: [Circular], + _idleStart: 5391, + parser: [Object], + on: [Function: socketOnWrap], + _paused: false, + read: [Function], + _consuming: true, + _httpMessage: null, + _peername: [Object] }, + _idlePrev: + TimersList { + _idleNext: [Circular], + _idlePrev: [Object], + _timer: [Object], + _unrefed: true, + msecs: 120000 }, + _idleStart: 6269, + parser: + HTTPParser { + '0': [Function: parserOnHeaders], + '1': [Function: parserOnHeadersComplete], + '2': [Function: parserOnBody], + '3': [Function: parserOnMessageComplete], + '4': [Function: onParserExecute], + _headers: [], + _url: '', + _consumed: true, + socket: [Circular], + incoming: [Circular], + outgoing: null, + maxHeaderPairs: 2000, + onIncoming: [Function: parserOnIncoming] }, + on: [Function: socketOnWrap], + _paused: false, + read: [Function], + _consuming: true, + _httpMessage: + ServerResponse { + domain: null, + _events: [Object], + _eventsCount: 1, + _maxListeners: undefined, + output: [], + outputEncodings: [], + outputCallbacks: [], + outputSize: 0, + writable: true, + _last: false, + chunkedEncoding: false, + shouldKeepAlive: true, + useChunkedEncodingByDefault: true, + sendDate: true, + _removedHeader: {}, + _contentLength: null, + _hasBody: true, + _trailer: '', + finished: false, + _headerSent: false, + socket: [Circular], + connection: [Circular], + _header: null, + _headers: null, + _headerNames: {}, + _onPendingData: [Function: updateOutgoingData], + req: [Circular], + locals: {} }, + _peername: { address: '::1', family: 'IPv6', port: 50247 } }, + httpVersionMajor: 1, + httpVersionMinor: 1, + httpVersion: '1.1', + complete: false, + headers: + { host: 'localhost:3000', + connection: 'keep-alive', + 'content-length': '92', + accept: 'application/json, text/plain, */*', + origin: 'http://localhost:3000', + 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36', + 'content-type': 'application/json;charset=UTF-8', + dnt: '1', + referer: 'http://localhost:3000/', + 'accept-encoding': 'gzip, deflate', + 'accept-language': 'en-US,en;q=0.8,fr;q=0.6,it;q=0.4' }, + rawHeaders: + [ 'Host', + 'localhost:3000', + 'Connection', + 'keep-alive', + 'Content-Length', + '92', + 'Accept', + 'application/json, text/plain, */*', + 'Origin', + 'http://localhost:3000', + 'User-Agent', + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36', + 'Content-Type', + 'application/json;charset=UTF-8', + 'DNT', + '1', + 'Referer', + 'http://localhost:3000/', + 'Accept-Encoding', + 'gzip, deflate', + 'Accept-Language', + 'en-US,en;q=0.8,fr;q=0.6,it;q=0.4' ], + trailers: {}, + rawTrailers: [], + upgrade: false, + url: '/auth/signin', + method: 'POST', + statusCode: null, + statusMessage: null, + client: + Socket { + _connecting: false, + _hadError: false, + _handle: + TCP { + _externalStream: {}, + fd: 31, + reading: true, + owner: [Circular], + onread: [Function: onread], + onconnection: null, + writeQueueSize: 0 }, + _parent: null, + _host: null, + _readableState: + ReadableState { + objectMode: false, + highWaterMark: 16384, + buffer: [], + length: 0, + pipes: null, + pipesCount: 0, + flowing: true, + ended: false, + endEmitted: false, + reading: true, + sync: false, + needReadable: true, + emittedReadable: false, + readableListening: false, + resumeScheduled: false, + defaultEncoding: 'utf8', + ranOut: false, + awaitDrain: 0, + readingMore: false, + decoder: null, + encoding: null }, + readable: true, + domain: null, + _events: + { end: [Object], + finish: [Function: onSocketFinish], + _socketEnd: [Function: onSocketEnd], + drain: [Object], + timeout: [Function], + error: [Object], + close: [Object], + data: [Function: socketOnData], + resume: [Function: onSocketResume], + pause: [Function: onSocketPause] }, + _eventsCount: 10, + _maxListeners: undefined, + _writableState: + WritableState { + objectMode: false, + highWaterMark: 16384, + needDrain: false, + ending: false, + ended: false, + finished: false, + decodeStrings: false, + defaultEncoding: 'utf8', + length: 0, + writing: false, + corked: 0, + sync: false, + bufferProcessing: false, + onwrite: [Function], + writecb: null, + writelen: 0, + bufferedRequest: null, + lastBufferedRequest: null, + pendingcb: 0, + prefinished: false, + errorEmitted: false, + bufferedRequestCount: 0, + corkedRequestsFree: [Object] }, + writable: true, + allowHalfOpen: true, + destroyed: false, + bytesRead: 0, + _bytesDispatched: 6281, + _sockname: null, + _pendingData: null, + _pendingEncoding: '', + server: + Server { + domain: null, + _events: [Object], + _eventsCount: 3, + _maxListeners: undefined, + _connections: 6, + _handle: [Object], + _usingSlaves: false, + _slaves: [], + _unref: false, + allowHalfOpen: true, + pauseOnConnect: false, + httpAllowHalfOpen: false, + timeout: 120000, + _pendingResponseData: 0, + _connectionKey: '6::::3000' }, + _server: + Server { + domain: null, + _events: [Object], + _eventsCount: 3, + _maxListeners: undefined, + _connections: 6, + _handle: [Object], + _usingSlaves: false, + _slaves: [], + _unref: false, + allowHalfOpen: true, + pauseOnConnect: false, + httpAllowHalfOpen: false, + timeout: 120000, + _pendingResponseData: 0, + _connectionKey: '6::::3000' }, + _idleTimeout: 120000, + _idleNext: + Socket { + _connecting: false, + _hadError: false, + _handle: [Object], + _parent: null, + _host: null, + _readableState: [Object], + readable: true, + domain: null, + _events: [Object], + _eventsCount: 10, + _maxListeners: undefined, + _writableState: [Object], + writable: true, + allowHalfOpen: true, + destroyed: false, + bytesRead: 0, + _bytesDispatched: 4792, + _sockname: null, + _pendingData: null, + _pendingEncoding: '', + server: [Object], + _server: [Object], + _idleTimeout: 120000, + _idleNext: [Object], + _idlePrev: [Circular], + _idleStart: 5391, + parser: [Object], + on: [Function: socketOnWrap], + _paused: false, + read: [Function], + _consuming: true, + _httpMessage: null, + _peername: [Object] }, + _idlePrev: + TimersList { + _idleNext: [Circular], + _idlePrev: [Object], + _timer: [Object], + _unrefed: true, + msecs: 120000 }, + _idleStart: 6269, + parser: + HTTPParser { + '0': [Function: parserOnHeaders], + '1': [Function: parserOnHeadersComplete], + '2': [Function: parserOnBody], + '3': [Function: parserOnMessageComplete], + '4': [Function: onParserExecute], + _headers: [], + _url: '', + _consumed: true, + socket: [Circular], + incoming: [Circular], + outgoing: null, + maxHeaderPairs: 2000, + onIncoming: [Function: parserOnIncoming] }, + on: [Function: socketOnWrap], + _paused: false, + read: [Function], + _consuming: true, + _httpMessage: + ServerResponse { + domain: null, + _events: [Object], + _eventsCount: 1, + _maxListeners: undefined, + output: [], + outputEncodings: [], + outputCallbacks: [], + outputSize: 0, + writable: true, + _last: false, + chunkedEncoding: false, + shouldKeepAlive: true, + useChunkedEncodingByDefault: true, + sendDate: true, + _removedHeader: {}, + _contentLength: null, + _hasBody: true, + _trailer: '', + finished: false, + _headerSent: false, + socket: [Circular], + connection: [Circular], + _header: null, + _headers: null, + _headerNames: {}, + _onPendingData: [Function: updateOutgoingData], + req: [Circular], + locals: {} }, + _peername: { address: '::1', family: 'IPv6', port: 50247 } }, + _consuming: false, + _dumped: false, + next: [Function: next], + baseUrl: '', + originalUrl: '/auth/signin', + _parsedUrl: + Url { + protocol: null, + slashes: null, + auth: null, + host: null, + port: null, + hostname: null, + hash: null, + search: null, + query: null, + pathname: '/auth/signin', + path: '/auth/signin', + href: '/auth/signin', + _raw: '/auth/signin' }, + params: {}, + query: {}, + res: + ServerResponse { + domain: null, + _events: { finish: [Function: resOnFinish] }, + _eventsCount: 1, + _maxListeners: undefined, + output: [], + outputEncodings: [], + outputCallbacks: [], + outputSize: 0, + writable: true, + _last: false, + chunkedEncoding: false, + shouldKeepAlive: true, + useChunkedEncodingByDefault: true, + sendDate: true, + _removedHeader: {}, + _contentLength: null, + _hasBody: true, + _trailer: '', + finished: false, + _headerSent: false, + socket: + Socket { + _connecting: false, + _hadError: false, + _handle: [Object], + _parent: null, + _host: null, + _readableState: [Object], + readable: true, + domain: null, + _events: [Object], + _eventsCount: 10, + _maxListeners: undefined, + _writableState: [Object], + writable: true, + allowHalfOpen: true, + destroyed: false, + bytesRead: 0, + _bytesDispatched: 6281, + _sockname: null, + _pendingData: null, + _pendingEncoding: '', + server: [Object], + _server: [Object], + _idleTimeout: 120000, + _idleNext: [Object], + _idlePrev: [Object], + _idleStart: 6269, + parser: [Object], + on: [Function: socketOnWrap], + _paused: false, + read: [Function], + _consuming: true, + _httpMessage: [Circular], + _peername: [Object] }, + connection: + Socket { + _connecting: false, + _hadError: false, + _handle: [Object], + _parent: null, + _host: null, + _readableState: [Object], + readable: true, + domain: null, + _events: [Object], + _eventsCount: 10, + _maxListeners: undefined, + _writableState: [Object], + writable: true, + allowHalfOpen: true, + destroyed: false, + bytesRead: 0, + _bytesDispatched: 6281, + _sockname: null, + _pendingData: null, + _pendingEncoding: '', + server: [Object], + _server: [Object], + _idleTimeout: 120000, + _idleNext: [Object], + _idlePrev: [Object], + _idleStart: 6269, + parser: [Object], + on: [Function: socketOnWrap], + _paused: false, + read: [Function], + _consuming: true, + _httpMessage: [Circular], + _peername: [Object] }, + _header: null, + _headers: null, + _headerNames: {}, + _onPendingData: [Function: updateOutgoingData], + req: [Circular], + locals: {} }, + route: + Route { + path: '/auth/signin', + stack: [ [Object] ], + methods: { post: true } } }