merged stuff

This commit is contained in:
David Baldwynn 2015-07-02 13:25:48 -07:00
commit e09bddef82
79 changed files with 1600 additions and 7604 deletions

1
.gitignore vendored
View file

@ -21,6 +21,7 @@ app/tests/coverage/
config/sslcerts/*.pem
access.log
public/dist/
uploads/
# Sublime editor
# ==============

View file

@ -8,29 +8,27 @@ var mongoose = require('mongoose'),
Form = mongoose.model('Form'),
FormSubmission = mongoose.model('FormSubmission'),
pdfFiller = require( 'pdffiller' ),
PDFParser = require('pdf2json/pdfparser'),
config = require('../../config/config'),
fs = require('fs-extra'),
async = require('async'),
path = require('path'),
_ = require('lodash');
/**
* Create a new form manually
* Create a new form
*/
exports.create = function(req, res) {
var form = new Form(req.body);
form.admin = req.user;
form.save(function(err) {
if (err) {
console.log(err);
return res.status(400).send({
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
return res.json(form);
res.json(form);
}
});
};
@ -38,23 +36,29 @@ exports.create = function(req, res) {
/**
* Upload PDF
*/
exports.uploadPDF = function(req, res) {
var parser = new PDFParser(),
pdfFile = req.files.file;
exports.uploadPDF = function(files, user, cb) {
var _user = JSON.parse(''+user);
console.log(_user.username);
console.log(config.tmpUploadPath);
<<<<<<< HEAD
// console.log(pdfFile);
var form = Form.findById(req.body.form._id);
// console.log(req.files);
=======
if(files) {
console.log('inside uploadPDF');
console.log(files.file[0]);
var pdfFile = files.file[0];
>>>>>>> dev_working
if (req.files) {
if (pdfFile.size === 0) {
return res.status(400).send({
message: 'Hey, first would you select a file?'
});
throw new Error('Files uploaded are EMPTY');
}
fs.exists(pdfFile.path, function(exists) {
<<<<<<< HEAD
console.log(pdfFile.path);
fs.open(pdfFile.path,'r',function(err,fd){
@ -65,12 +69,40 @@ exports.uploadPDF = function(req, res) {
}
return res.status(200);
});
});
}
=======
//If file exists move to user's tmp directory
if(exists) {
var newDestination = path.join(config.tmpUploadPath, _user.username);
var stat = null;
try {
stat = fs.statSync(newDestination);
} catch (err) {
fs.mkdirSync(newDestination);
}
if (stat && !stat.isDirectory()) {
console.log('Directory cannot be created');
throw 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) {
throw new Error(err.message);
}
pdfFile.path = path.join(newDestination, pdfFile.name);
return cb(pdfFile);
});
} else {
throw new Error('Did NOT get your file!');
}
>>>>>>> dev_working
});
}else {
throw new Error('File NOT uploaded');
}
return res.status(400).send({
message: 'FILE NOT UPLOADED'
});
};
/**
@ -95,9 +127,9 @@ exports.createSubmission = function(req, res) {
submission.form_fields = req.body.form_fields;
submission.title = req.body.title;
submission.timeElapsed = req.body.timeElapsed;
console.log(req.body);
// submission.ipAddr = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
if (form.isGenerated){
fdfTemplate = form.convertToFDF();
} else {
@ -108,28 +140,22 @@ exports.createSubmission = function(req, res) {
}
}
fdfData = pdfFiller.fillFdfTemplate(fdfTemplate, submission.form_fields, null);
submission.fdfData = fdfData;
//Create new file
// pdfFiller.fillForm( form.pdf.path, config.pdfUploadPath+form.title+'/'+form.title+'_'+Date.now()+'_submission.pdf', fdfData, function() {
// console.log('\n\n\n fdfData');
// console.log(fdfData);
// console.log('\n\n\n :\n');
// console.log(req.body);
if(form.autofillPDFs){
fdfData = pdfFiller.fillFdfTemplate(fdfTemplate, submission.form_fields, null);
submission.fdfData = fdfData;
}
submission.save(function(err){
if (err) {
console.error(err);
return res.status(400).send({
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
return res.status(200);
console.log('Form Submission CREATED');
res.status(200).send('Form submission successfully saved');
}
});
// });
};
@ -139,13 +165,15 @@ exports.createSubmission = function(req, res) {
exports.listSubmissions = function(req, res) {
var _form = req.form;
FormSubmission.find({ form: req.form }).exec(function(err, submissions) {
FormSubmission.find({ form: req.form }).populate('admin', 'form').exec(function(err, submissions) {
if (err) {
return res.status(400).send({
console.log(err);
res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
} else {
return res.json(submissions);
console.log('hello');
res.json(submissions);
}
});
};
@ -163,12 +191,12 @@ exports.update = function(req, res) {
form.save(function(err) {
if (err) {
console.log(err);
return res.status(400).send({
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
console.log('updated form');
return res.json(form);
res.json(form);
}
});
};
@ -178,31 +206,41 @@ exports.update = function(req, res) {
*/
exports.delete = function(req, res) {
var form = req.form;
form.remove(function(err) {
console.log('deleting form');
Form.remove({_id: form._id}, function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
res.status(500).send({
message: err.message
});
} else {
return res.status(200);
// res.json(form);
console.log('Form successfully deleted');
res.status(200).send('Form successfully deleted');
}
});
};
/**
<<<<<<< HEAD
* Get List of Forms
*/
exports.list = function(req, res) {
Form.find().sort('-created').populate('admin').exec(function(err, forms) {
=======
* Get All of Users' Forms
*/
exports.list = function(req, res) {
//Allow 'admin' user to view all forms
var searchObj = {admin: req.user};
if(req.user.isAdmin()) searchObj = {};
Form.find({}).sort('-created').populate('admin').exec(function(err, forms) {
>>>>>>> dev_working
if (err) {
return res.status(400).send({
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
console.log(forms);
return res.json(forms);
res.json(forms);
}
});
};
@ -214,26 +252,48 @@ exports.list = function(req, res) {
exports.formByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
res.status(400).send({
message: 'Form is invalid'
});
}
Form.findById(id).populate('admin').exec(function(err, form) {
if (err) return next(err);
if (!form) {
return res.status(404).send({
if (err) {
return next(err);
} else if (!form || form === null) {
res.status(404).send({
message: 'Form not found'
});
}
else {
if(!form.admin){
form.admin = req.user;
form.save(function(err) {
if (err) {
console.log(err);
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
//Remove sensitive information from User object
form.admin.password = null;
form.admin.created = null;
form.admin.salt = null;
//Remove sensitive information from User object
form.admin.password = null;
form.admin.created = null;
form.admin.salt = null;
req.form = form;
next();
}
});
}
req.form = form;
next();
//Remove sensitive information from User object
form.admin.password = null;
form.admin.created = null;
form.admin.salt = null;
req.form = form;
next();
}
});
};
@ -243,14 +303,9 @@ exports.formByID = function(req, res, next, id) {
exports.hasAuthorization = function(req, res, next) {
var form = req.form;
// console.log('\n\n\nreq.form:\n');
// console.log(form);
// console.log('req.user.id: '+req.user.id);
if (req.form.admin.id !== req.user.id) {
return res.status(403).send({
message: 'User is not authorized'
if (req.form.admin.id !== req.user.id && req.user.roles.indexOf('admin') === -1) {
res.status(403).send({
message: 'User '+req.user.username+' is not authorized'
});
}
next();

View file

@ -23,7 +23,6 @@ exports.userByID = function(req, res, next, id) {
* Require login routing middleware
*/
exports.requiresLogin = function(req, res, next) {
if (!req.isAuthenticated()) {
return res.status(401).send({
message: 'User is not logged in'

View file

@ -1,34 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Article Schema
*/
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
content: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Article', ArticleSchema);

View file

@ -10,9 +10,8 @@ var mongoose = require('mongoose'),
_ = require('lodash'),
config = require('../../config/config'),
path = require('path'),
fs = require('fs-extra');
var Field = mongoose.model('Field', FieldSchema);
fs = require('fs-extra'),
Field = mongoose.model('Field', FieldSchema);
/**
@ -23,11 +22,10 @@ var FormSchema = new Schema({
type: Date,
default: Date.now
},
// type: {
// type: String,
// default: 'template',
// enum: ['submission', 'template']
// },
lastModified: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
@ -39,7 +37,7 @@ var FormSchema = new Schema({
type: String,
default: '',
},
form_fields: [Schema.Types.Mixed],
form_fields: [{type: Schema.Types.Mixed}],
submissions: [{
type: Schema.Types.ObjectId,
@ -57,20 +55,36 @@ var FormSchema = new Schema({
pdfFieldMap: {
type: Schema.Types.Mixed
},
hideFooter: {
type: Boolean,
default: true,
},
isGenerated: {
type: Boolean,
default: false,
},
isLive: {
type: Boolean,
default: true,
},
autofillPDFs: {
type: Boolean,
default: false,
},
});
<<<<<<< HEAD
//Move PDF to permanent location after new PDF is uploaded
=======
//Update lastModified everytime we save
FormSchema.pre('save', function (next) {
this.lastModified = Date.now();
next();
});
//Move PDF to permanent location after new template is uploaded
>>>>>>> dev_working
FormSchema.pre('save', function (next) {
// console.log(this.pdf);
// debugger;
if(this.pdf && this.isModified('pdf')){
console.log('Relocating PDF');
@ -111,15 +125,31 @@ FormSchema.pre('save', function (next) {
}
});
//Delete template PDF of current Form
FormSchema.pre('remove', function (next) {
if(this.pdf){
//Delete template form
fs.unlink(this.pdf.path, function(err){
if (err) throw err;
console.log('successfully deleted', this.pdf.path);
});
}
});
//Autogenerate FORM from PDF if 'isGenerated' flag is 'true'
FormSchema.pre('save', function (next) {
var field;
var field, _form_fields;
if(this.isGenerated && this.pdf){
var _typeConvMap = {
'Multiline': 'textarea',
'Text': 'textfield',
'Button': 'checkbox'
'Button': 'checkbox',
'Choice': 'radio',
'Password': 'password',
'FileSelect': 'filefield',
'Radio': 'radio'
};
var that = this;
@ -137,14 +167,27 @@ FormSchema.pre('save', function (next) {
field.fieldType = _typeConvMap[ field.fieldType+'' ];
}
<<<<<<< HEAD
//Set field defaults
field.created = Date.now();
=======
>>>>>>> dev_working
field.fieldValue = '';
field.created = Date.now();
field.required = true;
field.disabled = false;
field.disabled = false;
// field = new Field(field);
// field.save()
// field.save(function(err) {
// if (err) {
// console.error(err.message);
// throw new Error(err.message);
// });
// } else {
// _form_fields[i] = this;
// }
// });
_form_fields[i] = field;
}
console.log('NEW FORM_FIELDS: ');
@ -183,5 +226,4 @@ FormSchema.methods.convertToFDF = function (cb) {
return jsonObj;
};
mongoose.model('Form', FormSchema);

View file

@ -11,17 +11,22 @@ function validateFormFieldType(value) {
if (!value || typeof myVar !== 'string' ) { return false; }
var validTypes = [
'textfield',
'email',
'url',
'textarea',
'checkbox',
'date',
'dropdown',
'hidden',
'password',
'radio'
];
'textfield',
'textarea',
'statement',
'email',
'legal',
'url',
'number',
'filefield',
'radio',
'checkbox',
'date',
'dropdown',
'hidden',
'password'
];
if (validTypes.indexOf(value) > -1) {
return true;
}
@ -49,7 +54,7 @@ var FormFieldSchema = new Schema({
},
required: {
type: Boolean,
default: false,
default: true,
},
disabled: {
type: Boolean,

View file

@ -11,6 +11,8 @@ var mongoose = require('mongoose'),
config = require('../../config/config'),
path = require('path'),
Form = mongoose.model('Form'),
FieldSchema = require('./form_field.server.model.js'),
Field = mongoose.model('Field', FieldSchema),
fs = require('fs-extra');
/**
@ -30,7 +32,7 @@ var FormSubmissionSchema = new Schema({
type: Schema.Types.ObjectId,
ref: 'User',
},
form_fields: [Schema.Types.Mixed],
form_fields: [{type: Schema.Types.Mixed}],
form: {
type: Schema.Types.ObjectId,
ref: 'Form',
@ -83,10 +85,10 @@ FormSubmissionSchema.pre('save', function (next) {
Form.findById(that.form, function(err, _form){
if(err) next( new Error(err.mesasge) );
// that.title = _form.title;
that.title = _form.title;
// console.log(_form);
if(true){ //_form.autofillPDFs){
if(_form.autofillPDFs){
dest_filename = _form.title.trim()+'_submission_'+Date.now()+'.pdf';
dest_path = path.join(config.pdfUploadPath, dest_filename);
@ -95,7 +97,6 @@ FormSubmissionSchema.pre('save', function (next) {
// console.log('autofillPDFs check');
pdfFiller.fillForm(_form.pdf.path, dest_path, this.fdfData, function(err){
console.log('fdfData: \n');
console.log(that.fdfData);
@ -111,13 +112,11 @@ FormSubmissionSchema.pre('save', function (next) {
next();
});
} else {
next();
}
});
});
mongoose.model('FormSubmission', FormSubmissionSchema);

View file

@ -144,4 +144,16 @@ UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
});
};
/**
* Function to check if user has Admin priviledges
*/
UserSchema.methods.isAdmin = function() {
if(this.roles.indexOf('admin') !== -1){
return true;
}
return false;
};
mongoose.model('User', UserSchema);

View file

@ -12,14 +12,21 @@ module.exports = function(app) {
.post(users.requiresLogin, forms.uploadPDF);
app.route('/forms')
.get(forms.list)
.get(users.requiresLogin, forms.list)
.post(users.requiresLogin, forms.create);
app.route('/forms/:formId/submissions')
.get(forms.listSubmissions);
app.route('/forms/:formId')
.get(forms.read)
.post(forms.createSubmission)
.put(users.requiresLogin, forms.hasAuthorization, forms.update)
<<<<<<< HEAD
.delete(users.requiresLogin, forms.hasAuthorization,forms.delete);
=======
.delete(users.requiresLogin, forms.hasAuthorization, forms.delete);
>>>>>>> dev_working
// Finish by binding the form middleware
app.param('formId', forms.formByID);

View file

@ -10,9 +10,15 @@ module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
// Setting up the users profile api
<<<<<<< HEAD
app.route('/users/me').get(users.me);
app.route('/users').put(users.requiresLogin, users.update);
app.route('/users/accounts').delete(users.removeOAuthProvider);
=======
app.route('/users/me').get(users.requiresLogin, users.me);
app.route('/users').put(users.requiresLogin, users.update);
app.route('/users/accounts').delete(users.requiresLogin, users.removeOAuthProvider);
>>>>>>> dev_working
// Setting up the users password api
app.route('/users/password').post(users.requiresLogin, users.changePassword);

View file

@ -1,5 +1,5 @@
{% extends 'layout.server.view.html' %}
{% block content %}
<section data-ui-view></section>
<section ui-view></section>
{% endblock %}

View file

@ -38,6 +38,8 @@
{% for cssFile in cssFiles %}
<link rel="stylesheet" href="{{cssFile}}">
{% endfor %}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<!-- HTML5 Shim -->
<!--[if lt IE 9]>
@ -45,12 +47,12 @@
<![endif]-->
</head>
<body class="ng-cloak" >
<body ng-cloak>
<header data-ng-include="'/modules/core/views/header.client.view.html'"></header>
<section class="content">
<section class="container">
<!-- <section class="container"> -->
{% block content %}{% endblock %}
</section>
<!-- </section> -->
</section>
<!--Embedding The User Object-->

View file

@ -11,7 +11,8 @@
"angular-bootstrap": "~0.12.0",
"angular-ui-utils": "~0.1.1",
"angular-ui-router": "~0.2.11",
"angular-strap": "~2.2.1"
"angular-strap": "~2.2.1",
"angular-permission": "~0.3.0"
},
"resolutions": {
"angular": "^1.2.21",

4
config/env/all.js vendored
View file

@ -59,12 +59,14 @@ module.exports = {
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-permission/dist/angular-permission.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/ng-file-upload/ng-file-upload-all.js'
'public/lib/ng-file-upload/ng-file-upload-all.js',
'public/lib/angular-cookies/angular-cookies.js',
]
},
css: [

View file

@ -96,34 +96,35 @@ module.exports = function(db) {
// Setting the app router and static folder
app.use(express.static(path.resolve('./public')));
var formCtrl = require('../app/controllers/forms.server.controller');
// Setting the pdf upload route and folder
app.use(multer({ dest: config.tmpUploadPath,
rename: function (fieldname, filename) {
return Date.now();
},
// changeDest: function(dest, req, res) {
// console.log(req.body.form);
// var newDestination = dest + req.body.form.title;
// var stat = null;
// try {
// stat = fs.statSync(newDestination);
// } catch (err) {
// fs.mkdirSync(newDestination);
// }
// if (stat && !stat.isDirectory()) {
// console.log('Directory cannot be created');
// throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"');
// }
// return newDestination;
// },
onFileUploadStart: function (file) {
//Check to make sure we can only upload images and pdfs
console.log(file.originalname + ' is starting ...');
},
<<<<<<< HEAD
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' has been uploaded to: ' + file.path);
// done=true;
=======
onFileUploadComplete: function (file, req, res) {
// console.log('\n\nheadersSent in onFileUploadComplete: ', res.headersSent);
console.log(req.body.user);
try{
formCtrl.uploadPDF(req.files, req.body.user, function(_file){
console.log(_file.filename + ' uploaded to ' + _file.path);
res.status(200).send(_file);
});
}catch(err) {
res.status(500).send({
message: err.message
});
}
>>>>>>> dev_working
}
}));

View file

@ -47,7 +47,8 @@
"passport-local": "~1.0.0",
"passport-twitter": "~1.0.2",
"satelize": "^0.1.1",
"swig": "~1.4.1"
"swig": "~1.4.1",
"then-fs": "^2.0.0"
},
"devDependencies": {
"supertest": "~0.14.0",

View file

@ -9,16 +9,24 @@ angular.module(ApplicationConfiguration.applicationModuleName).config(['$locatio
$locationProvider.hashPrefix('!');
}
]);
angular.module(ApplicationConfiguration.applicationModuleName).run(['$rootScope', 'Authorization', 'Principal',
function($rootScope, Authorization, Principal) {
$rootScope.$on('$stateChangeStart', function(event, toState, toStateParams) {
// track the state the user wants to go to; authorization service needs this
$rootScope.toState = toState;
$rootScope.toStateParams = toStateParams;
// if the principal is resolved, do an authorization check immediately. otherwise,
// it'll be done when the state it resolved.
if (Principal.isIdentityResolved()) Authorization.authorize();
});
angular.module(ApplicationConfiguration.applicationModuleName).run(['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {
// $rootScope.$on('$stateChangeStart', function(event, toState, toStateParams) {
// // track the state the user wants to go to; authorization service needs this
// $rootScope.toState = toState;
// $rootScope.toStateParams = toStateParams;
// // if the principal is resolved, do an authorization check immediately. otherwise,
// // it'll be done when the state it resolved.
// });
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
// add previous state property
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
$state.previous = fromState;
});
}
]);

View file

@ -12,6 +12,7 @@ angular.module('core').config(['$stateProvider', '$urlRouterProvider',
url: '/',
templateUrl: 'modules/core/views/home.client.view.html'
});
<<<<<<< HEAD
// state('restricted', {
// 'abstract': true,
// resolve: {
@ -22,5 +23,13 @@ angular.module('core').config(['$stateProvider', '$urlRouterProvider',
// ]
// }
// });
=======
$urlRouterProvider.otherwise( function($injector) {
var $state = $injector.get('$state');
$state.go('home');
});
>>>>>>> dev_working
}
]);

View file

@ -1,40 +1,73 @@
'use strict';
angular.module('core').controller('HeaderController', ['$scope', 'Principal', 'Menus', '$state',
function($scope, Principal, Menus, $state) {
$scope.authentication = Principal;
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;
console.log('isAuthenticated(): '+$scope.authentication.isAuthenticated());
$scope.isCollapsed = false;
$scope.hideNav = false;
$scope.menu = Menus.getMenu('topbar');
Principal.identity().then(function(user){
$scope.authentication.user = user;
}).then(function(){
$scope.signout = function() {
var response_obj = Principal.signout();
if( angular.isDefined(response_obj.error) ){
$scope.error = response_obj.error;
} else{
$state.go('home');
}
};
$scope.toggleCollapsibleMenu = function() {
$scope.isCollapsed = !$scope.isCollapsed;
};
$scope.signout = function() {
User.logout(function() {
Auth.logout();
$rootScope.user = null;
$state.go('home');
});
};
// Collapsing the menu after navigation
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
$scope.isCollapsed = false;
$scope.hideNav = false;
if ( angular.isDefined( toState.data ) ) {
$scope.toggleCollapsibleMenu = function() {
$scope.isCollapsed = !$scope.isCollapsed;
};
if ( angular.isDefined( toState.data.hideNav ) ) {
$scope.hideNav = toState.data.hideNav;
}
}
});
// Collapsing the menu after navigation
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
$scope.isCollapsed = false;
$scope.hideNav = false;
if ( angular.isDefined( toState.data ) ) {
if ( angular.isDefined( toState.data.hideNav ) ) {
$scope.hideNav = toState.data.hideNav;
}
}
});
// Principal.identity().then(function(user){
// $rootScope.user = user;
// console.log('topbar')
// console.log($scope.user);
// },
// function(error){
// console.log(error);
// }).then(function(){
// $scope.signout = function() {
// $http.get('/auth/signout').success(function(response) {
// $state.go('home');
// }).error(function(error) {
// $scope.error = (error.message || error);
// });
// Principal.signout().then(
// function(result){
// $state.go('home');
// },
// function(error){
// $scope.error = (error.message || error);
// }
// );
// if( angular.isDefined(response_obj.error) ){
// $scope.error = response_obj.error;
// } else{
// $state.go('home');
// }
// };
// });
}
]);

View file

@ -1,15 +1,17 @@
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Principal',
function($scope, Principal) {
// This provides Principal context.
$scope.authentication = Principal;
$scope.authentication.user = undefined;
Principal.identity().then(function(user){
$scope.authentication.user = user;
});
// console.log("user.displayName: "+Principal.user()._id);
angular.module('core').controller('HomeController', ['$rootScope', '$scope', 'User', 'Auth', '$state',
function($rootScope, $scope, User, Auth, $state) {
$scope = $rootScope;
console.log($rootScope.user);
$scope.user = Auth.ensureHasCurrentUser(User);
$scope.authentication = Auth;
if($scope.authentication.isAuthenticated()){
$state.go('listForms');
}
}
]);

View file

@ -0,0 +1,25 @@
// 'use strict';
// /**
// * @ngdoc function
// * @name medform.controller:IndexCtrl
// * @description
// * # IndexCtrl
// * Controller of core
// */
// angular.module('medform').controller('IndexCtrl', function ($scope, $rootScope, $location, User, Auth, $state) {
// $rootScope.user = Auth.ensureHasCurrentUser(User);
// // $rootScope.user = Auth.getUserState(User).user;
// $rootScope.authentication = Auth;
// $scope.signout = function() {
// User.logout(function() {
// Auth.logout();
// $rootScope.user = null;
// $state.go('home');
// // $scope.$apply();
// });
// };
// });

View file

@ -1,5 +1,18 @@
/*Navbar Custom CSS*/
.navbar .navbar-brand {
font-size: 1.6em;
font-weight: 900;
color: #FA787E;
}
.navbar .navbar-brand span {
text-decoration: underline;
}
.nav.navbar-nav.navbar-right li {
padding-right: 20px;
}
.content {
margin-top: 50px;
margin-top: 70px;
}
.undecorated-link:hover {
text-decoration: none;
@ -18,3 +31,24 @@ body.ng-cloak
{
display: block;
}
/*Hero Section CSS (for /home)*/
section.hero-section {
/*padding-top:30px;*/
width: 100%;
}
section.hero-section > .jumbotron {
background-image: url(http://yourplaceandmine.ie/wp-content/uploads/2014/09/Daingean-meeting-048_13-1080x675.jpg);
background-repeat: no-repeat;
background-position: 0 50%;
/*background-position-top: 0px;*/
background-size: cover;
}
section > .jumbotron > .opacity-background {
background-color: rgba(71,61,61,0.5);
color: white;
padding: inherit;
height: inherit;
width: inherit;
}

View file

@ -7,10 +7,13 @@
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/#!/" class="navbar-brand">MedForm</a>
<a href="/#!/" class="navbar-brand">
<!-- <i class="fa fa-5 fa-heartbeat"></i> -->
Med<span>Form</span>
</a>
</div>
<nav class="collapse navbar-collapse" collapse="!isCollapsed" role="navigation">
<ul class="nav navbar-nav" data-ng-if="menu.shouldRender(authentication.user);">
<ul class="nav navbar-nav" data-ng-if="authentication.isAuthenticated();">
<li data-ng-repeat="item in menu.items | orderBy: 'position'" data-ng-if="item.shouldRender(authentication.isAuthenticated());" ng-switch="item.menuItemType" ui-route="{{item.uiRoute}}" class="{{item.menuItemClass}}" ng-class="{active: ($uiRoute)}" dropdown="item.menuItemType === 'dropdown'">
<a ng-switch-when="dropdown" class="dropdown-toggle" dropdown-toggle>
<span data-ng-bind="item.title"></span>
@ -36,7 +39,7 @@
<ul class="nav navbar-nav navbar-right" data-ng-show="authentication.isAuthenticated()">
<li class="dropdown" dropdown>
<a href="#" class="dropdown-toggle" data-toggle="dropdown" dropdown-toggle>
<span data-ng-bind="authentication.user.displayName"></span> <b class="caret"></b>
<span data-ng-bind="user.displayName"></span> <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>

View file

@ -1,105 +1,26 @@
<section data-ng-controller="HomeController">
<section data-ng-controller="HomeController" class="hero-section">
<div class="jumbotron text-center">
<div class="row">
<div class="col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3 col-xs-12">
<!-- <img alt="MEAN.JS" class="img-responsive text-center" src="modules/core/img/brand/logo.png" /> -->
<div class="opacity-background">
<div class="row">
<div class="col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3 col-xs-12">
<!-- <img alt="MEAN.JS" class="img-responsive text-center" src="modules/core/img/brand/logo.png" /> -->
</div>
</div>
<br>
<div class="row" data-ng-if="!authentication.isAuthenticated()">
<p class="lead">
Make beautiful forms in a snap.
</p>
<br><br> <br><br>
<a class="btn btn-info" href="/#!/signup">
Signup now
</a>
</div>
</div>
<br>
<div class="row" data-ng-if="!authentication.isAuthenticated()">
<p class="lead">
Make beautiful forms in a snap.
</p>
<br><br> <br><br>
<a class="btn btn-info">
Signup now
</a>
</div>
<div class="row" data-ng-if="authentication.isAuthenticated()">
<p class="lead">
Hi there {{authentication.user.displayName}}
</p>
</div>
<div class="row" data-ng-if="authentication.isAuthenticated()">
<p>
<a class="btn btn-primary btn-lg" href="http://meanjs.org" target="_blank">Learn more</a>
</p>
</div>
</div>
<!-- <div>
<h2>Congrats! You've configured and ran the sample application successfully.</h2>
<p>MEAN.JS is a web application boilerplate, which means you should start changing everything :-)</p>
<p>This sample application tracks users and articles.</p>
<ul>
<li>
Click
<em>Signup</em>
to get started.
</li>
<li>
Configure your app to work with your social accounts, by editing the
<em>/config/env/*.js</em>
files.
</li>
<li>
Edit your users module.
</li>
<li>
Add new CRUD modules.
</li>
<li>
Have fun...
</li>
</ul>
</div>
<div class="row">
<div class="col-md-3">
<h2>
<strong>M</strong>ongoDB
</h2>
<p><a target="_blank" href="http://mongodb.org/">MongoDB</a> is a database. MongoDB's <a target="_blank" href="http://docs.mongodb.org/manual/">great manual</a> is the place to get started with NoSQL and MongoDB.</p>
</div>
<div class="col-md-3">
<h2>
<strong>E</strong>xpress
</h2>
<p><a target="_blank" href="http://expressjs.com/"> Express</a> is an app server. Check out <a target="_blank" href="http://expressjs.com/4x/api.html">The ExpressJS API reference for more information</a> or <a target="_blank" href="http://stackoverflow.com/questions/8144214/learning-express-for-node-js">StackOverflow</a> for more info.</p>
</div>
<div class="col-md-3">
<h2>
<strong>A</strong>ngularJS
</h2>
<p>AngularJS is web app framework. <a target="_blank" href="http://angularjs.org/">Angular's website</a> offers a lot. The <a target="_blank" href="http://www.thinkster.io/">Thinkster Popular Guide</a> and <a target="_blank" href="https://egghead.io/">Egghead Videos</a> are great resources.</p>
</div>
<div class="col-md-3">
<h2>
<strong>N</strong>ode.js
</h2>
<p><a target="_blank" href="http://nodejs.org/">Node.js</a> is a web server. Node's website and this <a target="_blank" href="http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js">stackOverflow thread</a> offer excellent starting points to get to grasps with node.</p>
</div>
</div>
<div class="well">
<h2>MEAN.JS Documentation</h2>
<p>
Once you're familiar with the foundation technology, check out the MEAN.JS Documentation:
<ul>
<li><a target="_blank" href="http://meanjs.org/docs.html">MEAN.JS Documentation</a>
</li>
<li><a target="_blank" href="http://meanjs.org/generator.html">Yeoman Generator</a>
</li>
<li><a target="_blank" href="http://meanjs.org/modules.html">Modules</a>
</li>
<li><a target="_blank" href="http://meanjs.org/changelog.html">Changelog</a>
</li>
<li><a target="_blank" href="http://meanjs.org/community.html">Community</a>
</li>
<li><a target="_blank" href="http://blog.meanjs.org">Blog</a>
</li>
</ul>
</p>
</div> -->
<br>Enjoy &amp; Keep Us Updated,
<br>The MedForms Team.
</section>

View file

@ -1,32 +1,80 @@
'use strict';
angular.module('forms').controller('EditFormController', ['$scope', '$state', 'Upload', '$stateParams', 'Principal', 'FormFields', 'Forms', 'CurrentForm', '$modal', '$location',
function ($scope, $state, Upload, $stateParams, Principal, FormFields, Forms, CurrentForm, $modal, $location) {
// Principal.identity().then(function(user){
// $scope.authentication.user = user;
// }).then(function(){
// console.log('aeouaoeuaoeuaou');
// console.log('isAuthenticated(): '+Principal.isAuthenticated());\
$scope.isNewForm = false;
$scope.log = '';
angular.module('forms').controller('EditFormController', ['$scope', '$state', '$rootScope', 'Upload', '$stateParams', 'FormFields', 'Forms', 'CurrentForm', '$modal', '$location',
function ($scope, $state, $rootScope, Upload, $stateParams, FormFields, Forms, CurrentForm, $modal, $location) {
// Get current form if it exists, or create new one
if($stateParams.formId){
$scope.form = {};
var _form = Forms.get({ formId: $stateParams.formId}, function(form){
_form.pdf = form.pdf;
_form.$save();
$scope.isNewForm = false;
$scope.pdfLoading = false;
var _current_upload = null;
$scope.log = '';
$scope.form = angular.fromJson(angular.toJson(_form));
console.log(JSON.stringify($scope.form.pdf));
// Get current form if it exists, or create new one
if($stateParams.formId){
$scope.form = {};
var _form = Forms.get({ formId: $stateParams.formId}, function(form){
_form.pdf = form.pdf;
_form.$save();
$scope.form = angular.fromJson(angular.toJson(_form));
console.log(JSON.stringify($scope.form.pdf));
});
} else {
$scope.form = {};
$scope.form.form_fields = [];
$scope.isNewForm = true;
}
//PDF Functions
$scope.cancelUpload = function(){
_current_upload.abort();
$scope.pdfLoading = false;
};
$scope.removePDF = function(){
$scope.form.pdf = null;
$scope.isGenerated = false;
$scope.autofillPDFs = false;
console.log('form.pdf: '+$scope.form.pdf+' REMOVED');
};
$scope.uploadPDF = function(files) {
if (files && files.length) {
// for (var i = 0; i < files.length; i++) {
var file = files[0];
_current_upload = Upload.upload({
url: '/upload/pdf',
fields: {
'user': $scope.user,
'form': $scope.form
},
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$scope.log = 'progress: ' + progressPercentage + '% ' +
evt.config.file.name + '\n' + $scope.log;
$scope.pdfLoading = true;
}).success(function (data, status, headers, config) {
$scope.log = 'file ' + data.originalname + 'uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log;
$scope.form.pdf = data;
$scope.pdfLoading = false;
console.log($scope.log);
console.log('$scope.pdf: '+$scope.form.pdf.name);
if(!$scope.$$phase) {
$scope.$apply();
}
}).error(function(err){
$scope.pdfLoading = false;
console.log('Error occured during upload.\n');
console.log(err);
});
} else {
$scope.form = {};
$scope.form.form_fields = [];
$scope.isNewForm = true;
// }
}
};
<<<<<<< HEAD
//PDF Functions
$scope.cancelUpload = function(){
@ -76,158 +124,169 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
// Create new Form
$scope.createOrUpdate = function() {
=======
$scope.goToWithId = function(route, id) {
$state.go(route, {'formId': id}, {reload: true});
};
>>>>>>> dev_working
if($scope.isNewForm){
// Create new Form object
var form = new Forms($scope.form);
// Create new Form
$scope.createOrUpdate = function() {
if($scope.isNewForm){
// Create new Form object
var form = new Forms($scope.form);
<<<<<<< HEAD
form.$save(function(response) {
console.log('create form');
// console.log(response.pdf);
=======
form.$save(function(response) {
>>>>>>> dev_working
// Clear form fields
$scope.form = {};
// Redirect after save
$location.path('forms/' + response._id + '/admin');
}, function(errorResponse) {
console.log(errorResponse.data.message);
$scope.error = errorResponse.data.message;
});
} else{
console.log('update form');
$scope.update();
}
};
// Update existing Form
$scope.update = function() {
var form = new Forms($scope.form);
form.$update(function(response) {
console.log('form updated');
console.log('form created');
// console.log(response.pdf);
$location.path('forms/' + response._id + '/admin');
// Clear form fields
$scope.form = {};
// Redirect after save
$scope.goToWithId('viewForm', response._id);
}, function(errorResponse) {
console.log(errorResponse.data.message);
$scope.error = errorResponse.data.message;
});
} else{
console.log('update form');
$scope.update();
}
};
// Update existing Form
$scope.update = function() {
var form = new Forms($scope.form);
form.$update(function(response) {
console.log('form updated');
$scope.goToWithId('viewForm', response._id);
// $location.path('forms/' + response._id + '/admin');
}, function(errorResponse) {
console.log(errorResponse.data.message);
$scope.error = errorResponse.data.message;
});
};
//Populate AddField with all available form field types
$scope.addField = {};
$scope.addField.types = FormFields.fields;
$scope.addField.new = $scope.addField.types[0].name;
$scope.addField.lastAddedID = 0;
// preview form mode
$scope.previewMode = false;
// previewForm - for preview purposes, form will be copied into this
// otherwise, actual form might get manipulated in preview mode
$scope.previewForm = {};
// accordion settings
$scope.accordion = {};
$scope.accordion.oneAtATime = true;
// create new field button click
$scope.addNewField = function(){
// incr field_id counter
$scope.addField.lastAddedID++;
var newField = {
'title' : 'New field - ' + ($scope.addField.lastAddedID),
'fieldType' : $scope.addField.new,
'fieldValue' : '',
'required' : true,
'disabled' : false
};
//Populate AddField with all available form field types
$scope.addField = {};
$scope.addField.types = FormFields.fields;
$scope.addField.new = $scope.addField.types[0].name;
$scope.addField.lastAddedID = 0;
// put newField into fields array
$scope.form.form_fields.push(newField);
// console.log($scope.form.form_fields);
};
// preview form mode
$scope.previewMode = false;
// previewForm - for preview purposes, form will be copied into this
// otherwise, actual form might get manipulated in preview mode
$scope.previewForm = {};
// accordion settings
$scope.accordion = {};
$scope.accordion.oneAtATime = true;
// create new field button click
$scope.addNewField = function(){
// incr field_id counter
$scope.addField.lastAddedID++;
var newField = {
'title' : 'New field - ' + ($scope.addField.lastAddedID),
'fieldType' : $scope.addField.new,
'fieldValue' : '',
'required' : true,
'disabled' : false
};
// put newField into fields array
$scope.form.form_fields.push(newField);
// console.log($scope.form.form_fields);
};
// deletes particular field on button click
$scope.deleteField = function (field_id){
for(var i = 0; i < $scope.form.form_fields.length; i++){
if($scope.form.form_fields[i].field_id === field_id){
$scope.form.form_fields.splice(i, 1);
break;
}
// deletes particular field on button click
$scope.deleteField = function (field_id){
for(var i = 0; i < $scope.form.form_fields.length; i++){
if($scope.form.form_fields[i].field_id === field_id){
$scope.form.form_fields.splice(i, 1);
break;
}
}
};
// add new option to the field
$scope.addOption = function (field){
if(!field.field_options)
field.field_options = [];
var lastOptionID = 0;
if(field.field_options[field.field_options.length-1])
lastOptionID = field.field_options[field.field_options.length-1].option_id;
// new option's id
var option_id = lastOptionID + 1;
var newOption = {
'option_id' : option_id,
'option_title' : 'Option ' + option_id,
'option_value' : option_id
};
// add new option to the field
$scope.addOption = function (field){
if(!field.field_options)
field.field_options = [];
// put new option into field_options array
field.field_options.push(newOption);
};
var lastOptionID = 0;
if(field.field_options[field.field_options.length-1])
lastOptionID = field.field_options[field.field_options.length-1].option_id;
// new option's id
var option_id = lastOptionID + 1;
var newOption = {
'option_id' : option_id,
'option_title' : 'Option ' + option_id,
'option_value' : option_id
};
// put new option into field_options array
field.field_options.push(newOption);
};
// delete particular option
$scope.deleteOption = function (field, option){
for(var i = 0; i < field.field_options.length; i++){
if(field.field_options[i].option_id === option.option_id){
field.field_options.splice(i, 1);
break;
}
// delete particular option
$scope.deleteOption = function (field, option){
for(var i = 0; i < field.field_options.length; i++){
if(field.field_options[i].option_id === option.option_id){
field.field_options.splice(i, 1);
break;
}
};
}
};
// preview form
$scope.previewOn = function(){
if($scope.form.form_fields === null || $scope.form.form_fields.length === 0) {
var title = 'Error';
var msg = 'No fields added yet, please add fields to the form before preview.';
var btns = [{result:'ok', label: 'OK', cssClass: 'btn-primary'}];
// preview form
$scope.previewOn = function(){
if($scope.form.form_fields === null || $scope.form.form_fields.length === 0) {
var title = 'Error';
var msg = 'No fields added yet, please add fields to the form before preview.';
var btns = [{result:'ok', label: 'OK', cssClass: 'btn-primary'}];
// $dialog.messageBox(title, msg, btns).open();
}
else {
$scope.previewMode = !$scope.previewMode;
$scope.form.submitted = false;
angular.copy($scope.form, $scope.previewForm);
}
};
// hide preview form, go back to create mode
$scope.previewOff = function(){
// $dialog.messageBox(title, msg, btns).open();
}
else {
$scope.previewMode = !$scope.previewMode;
$scope.form.submitted = false;
};
angular.copy($scope.form, $scope.previewForm);
}
};
// decides whether field options block will be shown (true for dropdown and radio fields)
$scope.showAddOptions = function (field){
if(field.field_type === 'radio' || field.field_type === 'dropdown')
return true;
else
return false;
};
// hide preview form, go back to create mode
$scope.previewOff = function(){
$scope.previewMode = !$scope.previewMode;
$scope.form.submitted = false;
};
// });
// decides whether field options block will be shown (true for dropdown and radio fields)
$scope.showAddOptions = function (field){
if(field.field_type === 'radio' || field.field_type === 'dropdown')
return true;
else
return false;
};
}
]);

View file

@ -1,22 +1,12 @@
'use strict';
// Forms controller
angular.module('forms').controller('SubmitFormController', ['$scope', '$stateParams', '$state', 'Principal', 'Forms', 'CurrentForm','$http',
function($scope, $stateParams, $state, Principal, Forms, CurrentForm, $http) {
// Principal.identity().then(function(user){
// $scope.authentication.user = user;
// }).then(function(){
angular.module('forms').controller('SubmitFormController', ['$scope', '$stateParams', '$state', 'Forms', 'CurrentForm',
function($scope, $stateParams, $state, Forms, CurrentForm) {
$scope.form = Forms.get({
formId: $stateParams.formId
});
CurrentForm.setForm($scope.form);
// console.log($scope.form);
// });
$scope.form = Forms.get({
formId: $stateParams.formId
});
CurrentForm.setForm($scope.form);
}
]);

View file

@ -0,0 +1,56 @@
'use strict';
// submissions controller
angular.module('forms').controller('ViewSubmissionController', ['$scope', '$stateParams', '$state', 'Submissions','$http',
function($scope, $stateParams, $state, Submissions, $http) {
$scope.submissionId = undefined;
// Principal.identity().then(function(user){
// $scope.authentication.user = user;
// }).then(function(){
// Return all form's submissions
$scope.findAll = function() {
$scope.submissions = Submissions.query({
formId: $stateParams.formId
});
};
// Find a specific submission
$scope.findOne = function() {
$scope.submission = Submissions.get({
submissionId: $scope.submissionId,
formId: $stateParams.formId
});
};
// Remove existing submission
$scope.remove = function(submission) {
if (submission) {
submission.$remove();
$http.delete('/forms/'+$stateParams.formId+'submissions/'+$scope.submission._id).
success(function(data, status, headers){
console.log('submission deleted successfully');
alert('submission deleted..');
});
} else {
$scope.submission.$remove(function() {
console.log('remove');
$state.path('submissions');
$http.delete('/forms/'+$stateParams.formId+'/submissions/'+$scope.submission._id).
success(function(data, status, headers){
console.log('submission deleted successfully');
alert('submission deleted..');
});
});
}
};
// });
}
]);

View file

@ -1,55 +1,76 @@
'use strict';
// Forms controller
angular.module('forms').controller('ViewFormController', ['$scope', '$stateParams', '$state', 'Principal', 'Forms', 'CurrentForm','$http',
function($scope, $stateParams, $state, Principal, Forms, CurrentForm, $http) {
angular.module('forms').controller('ViewFormController', ['$scope', '$stateParams', '$state', 'Forms', 'CurrentForm','$http',
function($scope, $stateParams, $state, Forms, CurrentForm, $http) {
// Principal.identity().then(function(user){
// $scope.authentication.user = user;
// }).then(function(){
// Return all user's Forms
$scope.find = function() {
$scope.forms = Forms.query();
};
// Find a specific Form
$scope.findOne = function() {
$scope.form = Forms.get({
formId: $stateParams.formId
});
CurrentForm.setForm($scope.form);
};
// view form submissions
$scope.form = CurrentForm.getForm();
$scope.submissions = undefined;
$scope.viewSubmissions = false;
// Remove existing Form
$scope.remove = function(form) {
if (form) {
form.$remove();
$http.delete('/forms/'+$scope.form._id).
success(function(data, status, headers){
console.log('form deleted successfully');
alert('Form deleted..');
$state.go('listForms');
//show submissions of Form
$scope.showSubmissions = function(){
$scope.viewSubmissions = true;
if(!$scope.submissions){
$http.get('/forms/'+$scope.form._id+'/submissions')
.success(function(data, status, headers){
console.log(data);
$scope.submissions = data;
console.log('form submissions successfully fetched');
})
.error(function(err){
console.log('Could not fetch form submissions.\nError: '+err);
});
} else if(!$scope.submissions.length){
$http.get('/forms/'+$scope.form._id+'/submissions')
.success(function(data, status, headers){
$scope.submissions = data;
console.log('form submissions successfully fetched');
})
.error(function(err){
console.log('Could not fetch form submissions.\nError: '+err);
});
}
console.log($scope.submissions);
}
} else {
$scope.form.$remove(function() {
console.log('remove');
$state.path('forms');
$http.delete('/forms/'+$scope.form._id).
success(function(data, status, headers){
console.log('form deleted successfully');
alert('Form deleted..');
$state.go('listForms');
});
});
}
};
//hide submissions of Form
$scope.hideSubmissions = function(){
$scope.viewSubmissions = false;
}
// });
// Return all user's Forms
$scope.findAll = function() {
$scope.forms = Forms.query();
};
// Find a specific Form
$scope.findOne = function() {
$scope.form = Forms.get({
formId: $stateParams.formId
});
CurrentForm.setForm($scope.form);
};
// Remove existing Form
$scope.remove = function() {
console.log('hello');
var form = CurrentForm.getForm()
if(!form){
form = $scope.form
}
$http.delete('/forms/'+$scope.form._id)
.success(function(data, status, headers){
console.log('form deleted successfully');
alert('Form deleted..');
$state.go('listForms');
}).error(function(error){
console.log('ERROR: Form could not be deleted.');
console.error(error);
});
};
}
]);

File diff suppressed because it is too large Load diff

View file

@ -1,25 +1,27 @@
'use strict';
angular.module('forms').directive('formDirective', ['$http', '$timeout', 'timeCounter',
function ($http, $timeout, timeCounter) {
angular.module('forms').directive('formDirective', ['$http', '$timeout', 'timeCounter', 'Auth',
function ($http, $timeout, timeCounter, Auth) {
return {
controller: function($scope){
timeCounter.startClock();
$scope.submit = function(){
var _timeElapsed = timeCounter.stopClock();
$scope.form.timeElapsed = _timeElapsed;
console.log($scope.form.timeElapsed);
// console.log($scope.form.form_fields[7]);
// console.log($scope.form.timeElapsed);
$scope.authentication = Auth;
console.log($scope.authentication.isAuthenticated());
$http.post('/forms/'+$scope.form._id,$scope.form).
success(function(data, status, headers){
console.log('form submitted successfully');
alert('Form submitted..');
$scope.form.submitted = true;
})
.error(function(error){
console.log(error);
});
};

View file

@ -1,4 +1,4 @@
'use strict';
// Use Application configuration module to register a new module
ApplicationConfiguration.registerModule('forms', ['ngFileUpload']);
ApplicationConfiguration.registerModule('forms', ['ngFileUpload', 'users']);

View file

@ -8,14 +8,7 @@ angular.module('forms').factory('Forms', ['$resource',
}, {
'query' : {
method: 'GET',
isArray: false,
// "transformResponse": function (data) {
// var _data = JSON.parse(data);
// var _pdf = JSON.parse(data).pdf;
// _data.pdf = _pdf;
// return _data;
// }
isArray: true,
},
'update': {
method: 'PUT'

View file

@ -0,0 +1,22 @@
'use strict';
//Submissions service used for communicating with the forms REST endpoints
angular.module('forms').factory('Submissions', ['$resource',
function($resource) {
return $resource('forms/:formID/submissions/:submissionId', {
submissionId: '@_id',
formId: '@_id'
}, {
'query' : {
method: 'GET',
isArray: true,
},
'update': {
method: 'PUT'
},
'save': {
method: 'POST'
}
});
}
]);

View file

@ -8,13 +8,13 @@ angular.module('forms').service('timeCounter', [
this.startClock = function(){
_startTime = Date.now();
console.log('Clock Started');
// console.log('Clock Started');
};
this.stopClock = function(){
_endTime = Date.now();
that.timeSpent = Math.abs(_endTime.valueOf() - _startTime.valueOf())/1000;
console.log('Clock Ended');
// console.log('Clock Ended');
return that.timeSpent;
};

View file

@ -1,3 +1,5 @@
<link rel="stylesheet" href="./modules/forms/css/form.css">
<section data-ng-controller="EditFormController">
<div ng-if="isNewForm">
<h1>Create your form</h1> <br>
@ -133,7 +135,7 @@
Delete
</button>
<button type="button" ng-if="form.pdfLoading" title="Abort ongoing upload" class="btn btn-default" ng-click="cancelUpload()">
<button type="button" ng-if="pdfLoading" title="Abort ongoing upload" class="btn btn-default" ng-click="cancelUpload()">
<i class="glyphicon glyphicon-ban-circle"></i>
Cancel
</button>
@ -190,12 +192,14 @@
<br><br>
<div class="row">
<div class="col-sm-offset-4 col-sm-2">
<div class="col-sm-offset-3 col-sm-2">
<button class="btn btn-primary btn-large" type="button" ng-click="createOrUpdate()"><i class="icon-arrow-left icon-white"></i> Save Changes</button>
</div>
<div class="col-sm-2">
<button class="btn btn-primary" type="button" ng-click="previewOn()"><i class="icon-eye-open icon-white"></i> Preview Form</button>
<!-- <button class="btn btn-danger right" type="button" ng-click="reset()"><i class="icon-refresh icon-white"></i> Reset</button> -->
<div class="col-sm-1">
<button class="btn btn-primary" type="button" ng-data-href="#!/forms/{{form._id}}/admin"><i class="icon-eye-open icon-white"></i> Cancel</button>
</div>
<div class="col-sm-1 col-sm-offset-1">
<button class="btn btn-secondary" type="button" ng-click="previewOn()"><i class="icon-eye-open icon-white"></i> Preview Form</button>
</div>
</div>

View file

@ -1,9 +1,7 @@
<h2>{{ form.form_name }}</h2>
<div ng-show="!form.submitted">
<div ng-hide="form.submitted">
<div class="field row">
<div class="col-sm-11 col-sm-offset-1"><h1>{{ form.title }}</h1>
<div class="col-sm-10 col-sm-offset-1"><h1>{{ form.title }}</h1>
<hr>
</div>
</div>
@ -11,31 +9,46 @@
<br>
<br>
<form class="field row" name="form" ng-model="form" ng-repeat="field in form.form_fields" >
<!-- <ul class=" col-sm-11 col-sm-offset-1" style="margin-top: 50px; margin-bottom: 50px;" ng-repeat="field in form.form_fields" > -->
<field-directive field="field" >
</field-directive>
<!-- </ul> -->
</form>
<div class="row">
<form class="field col-sm-offset-1 col-sm-10" name="form" ng-model="form" ng-repeat="field in form.form_fields" >
<!-- <ul class=" col-sm-11 col-sm-offset-1" style="margin-top: 50px; margin-bottom: 50px;" ng-repeat="field in form.form_fields" > -->
<field-directive field="field" >
</field-directive>
<!-- </ul> -->
</form>
</div>
<div class="row form-actions">
<p class="text-left col-sm-2 col-sm-offset-5">
<button class="btn btn-success right" type="button" ng-disabled="myForm.$valid" ng-click="submit()">
<i class="icon-edit icon-white"></i> Submit Form
<button class="btn btn-success col-sm-2 col-sm-offset-5" type="button" ng-disabled="myForm.$valid" ng-click="submit()" style="font-size: 1.6em;">
<i class="icon-edit icon-white"></i> submit
</button>
</p>
</div>
</div>
<div ng-show="form.submitted">
<h3>Form Successfully submitted</h3>
<br><br><br>
<div class="field row">
<div class="col-sm-11 col-sm-offset-1"><h1>{{ form.title }}</h1>
<hr>
</div>
</div>
<br>
<br>
<div class="field row text-center">
<h4 class="col-xs-6 col-xs-offset-1 text-left">Form entry successfully submitted!<br> What would you like to do next?</h4>
</div>
<br><br><br><br><br>
<div class="row form-actions">
<p class="text-left col-sm-2">
<button class="btn btn-primary left" type="button">
<a href="/form/{{form.id}}" style="color:white;"> Submit again?</a>
<p class="text-center col-xs-3 col-xs-offset-4">
<button class="btn btn-success left" type="button">
<a href="/#!/forms/{{form._id}}" style="color:white;"> Submit again?</a>
</button>
</p>
<p class="text-center col-xs-2" ng-if="authentication.isAuthenticated()">
<button class="btn btn-caution left" type="button">
<a href="/#!/forms/{{form._id}}/admin" style="color:white;">Edit Form</a>
</button>
</p>
</div>

View file

@ -1,20 +1,41 @@
<section data-ng-controller="ViewFormController" data-ng-init="find()">
<div class="page-header">
<h1>Forms</h1>
<section data-ng-controller="ViewFormController" data-ng-init="findAll()" class="container">
<div class="row">
<div class="page-header col-xs-10 col-xs-offset-1">
<h1>My MedForms</h1>
</div>
</div>
<div class="list-group">
<a data-ng-repeat="form in forms" data-ng-href="#!/forms/{{form._id}}/admin" class="list-group-item">
<small class="list-group-item-text">
Created on
<span data-ng-bind="form.created | date:'mediumDate'"></span>
by
<span data-ng-bind="form.user.displayName"></span>
</small>
<h4 class="list-group-item-heading" data-ng-bind="form.title"></h4>
<div class="row">
<a data-ng-href="#!/forms/create" class="col-xs-2 col-xs-offset-1 form-item row create-new">
<div class="title-row col-xs-12">
<h4 class=" fa fa-plus fa-6"></h4>
</div>
<div class="col-xs-12 details-row">
<small class="list-group-item-text">
Create a new form
</small>
</div>
</a>
<a data-ng-repeat="form in forms" data-ng-href="#!/forms/{{form._id}}/admin" class="col-xs-2 col-xs-offset-1 form-item row">
<div class="title-row col-xs-12">
<h4 class="list-group-item-heading" data-ng-bind="form.title"></h4>
</div>
<div class="col-xs-12 details-row">
<small class="list-group-item-text">
Created on
<span data-ng-bind="form.created | date:'mediumDate'"></span>
by
<span data-ng-bind="form.admin.username"></span>
</small>
</div>
</a>
</div>
<div class="alert alert-warning text-center" data-ng-if="forms.$resolved && !forms.length">
<!-- <div class="alert alert-warning text-center" data-ng-if="forms.$resolved && !forms.length">
No forms yet, why don't you <a href="/#!/forms/create">create one</a>?
</div>
</div> -->
</section>

View file

@ -1,31 +1,47 @@
<section data-ng-controller="ViewFormController" data-ng-init="findOne()">
<div class="page-header">
<h1 data-ng-bind="form.title"> Form Submissions</h1>
</div>
<div class="pull-right" data-ng-show="authentication.user._id == form.user._id">
<a class="btn btn-primary" href="/#!/forms/{{form._id}}/edit">
<i class="glyphicon glyphicon-edit"></i>
</a>
<a class="btn btn-primary" data-ng-click="remove();">
<i class="glyphicon glyphicon-trash"></i>
</a>
<a class="btn btn-primary" href="/#!/forms/{{form._id}}">
View Public Form
</a>
<a class="btn btn-primary" href="/#!/forms/{{form._id}}/submissions">
View Form Submissions
</a>
<section data-ng-controller="ViewSubmissionController" data-ng-init="findAll()">
<div class="page-header row" style="padding-bottom: 0px;">
<div class="col-xs-9">
<h1 data-ng-bind="form.title" style="margin-bottom: 0px;"></h1> <small>Submissions </small>
</div>
<div class="col-xs-3">
<small class=" pull-right">
<a class="btn btn-default" href="/#!/forms/{{form._id}}" disabled="form.isLive">
View Live Form
<i class="status-light status-light-on fa fa-dot-circle-o fa-3" ng-show="form.isLive"></i>
<i class="status-light status-light-off fa fa-circle-o fa-3" ng-hide="form.isLive"></i>
</a>
</small>
</div>
</div>
<div class="row">
<span class="col-md-5" data-ng-bind="form"></span>
<table class="table table-striped col-xs-7">
<thead>
<tr>
<th>#</th>
<th data-ng-repeat="(key, val) in submissions[0].form_fields">
{{key}}
</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="submission in submissions">
<td>{{$index+1}}</td>
<td data-ng-repeat="(key, val) in submission.form_fields">
{{value}}
</td>
</tr>
</tbody>
</table>
<a data-ng-repeat="submission in submissions" data-ng-href="#!/forms/{{form._id}}/admin" class="list-group-item">
<small class="list-group-item-text">
Created on
<span data-ng-bind="submission.created | date:'mediumDate'"></span>
by
<span data-ng-bind="form.user.displayName"></span>
</small>
<h4 class="list-group-item-heading" data-ng-bind="submission.title"></h4>
</a>
</div>
<small>
<em class="text-muted">
Created on
<span data-ng-bind="form.created | date:'mediumDate'"></span>
by
<span data-ng-bind="form.admin.displayName"></span>
</em>
</small>
<!-- <p class="lead" data-ng-bind="form.content"></p> -->
</section>

View file

@ -1,31 +1,93 @@
<section data-ng-controller="ViewFormController" data-ng-init="findOne()">
<div class="page-header">
<h1 data-ng-bind="form.title"></h1>
<section data-ng-controller="ViewFormController" data-ng-init="findOne()" class="container admin-form">
<div class="page-header row" style="padding-bottom: 0px;">
<div class="col-xs-9">
<h1 data-ng-bind="form.title" style="margin-bottom: 0px;"></h1>
</div>
<div class="col-xs-3">
<small class=" pull-right">
<a class="btn btn-default" href="/#!/forms/{{form._id}}">
View <span ng-show="form.isLive">Live</span> <span ng-hide="form.isLive">Preview</span> Form
<i class="status-light status-light-on fa fa-dot-circle-o" ng-show="form.isLive"></i>
<i class="status-light status-light-off fa fa-circle-o" ng-hide="form.isLive"></i>
<!-- <i class="fa fa-sign-out"></i> -->
</a>
</small>
</div>
</div>
<div class="pull-right" data-ng-show="authentication.user._id == form.user._id">
<a class="btn btn-primary" href="/#!/forms/{{form._id}}/edit">
<i class="glyphicon glyphicon-edit"></i>
</a>
<a class="btn btn-primary" data-ng-click="remove();">
<i class="glyphicon glyphicon-trash"></i>
</a>
<a class="btn btn-primary" href="/#!/forms/{{form._id}}">
View Public Form
</a>
<a class="btn btn-primary" href="/#!/forms/{{form._id}}/submissions">
View Form Submissions
</a>
<div class="row">
<div class="col-xs-8" ng-if="!viewSubmissions">
<p ng-show="form.form_fields.length == 0">No fields added yet.</p>
<accordion class="col-xs-10" close-others="accordion.oneAtATime">
<accordion-group heading="{{field.title}} (is a {{field.fieldType}})" ng-repeat="field in form.form_fields">
</accordion-group>
</accordion>
</p>
</div>
<div class="submissions-table col-xs-8" ng-if="viewSubmissions">
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th>#</th>
<th data-ng-repeat="(key, value) in submissions[0].form_fields">
{{value.title}}
</th>
<th>
Time Elapsed
</th>
<th>
Date Submitted (UTC)
</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="submission in submissions">
<th class="scope">{{$index+1}}</th>
<td data-ng-repeat="(key, value) in submission.form_fields">
{{value.fieldValue}}
</td>
<td>
{{submission.timeElapsed}}
</th>
<td>
{{submission.created | date:'yyyy-MM-dd HH:mm:ss'}}
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-3 col-xs-offset-1 container text-right form-controls" data-ng-show="authentication.user._id == form.user._id">
<div class="row">
<a class="col-xs-12 btn btn-default" href="/#!/forms/{{form._id}}/edit">
<i class="glyphicon glyphicon-edit"></i> Edit Form
</a>
</div>
<div class="row">
<a class="col-xs-12 btn btn-danger" data-ng-click="remove();">
<i class="glyphicon glyphicon-trash"></i> Delete Form
</a>
</div>
<div class="row">
<a class="col-xs-12 btn btn-default" data-ng-click="showSubmissions();" ng-hide="viewSubmissions">
View Form Submissions
</a>
<a class="col-xs-12 btn btn-primary" data-ng-click="hideSubmissions();" ng-show="viewSubmissions">
Back to Main View
</a>
</div>
</div>
</div>
<div class="row">
<span class="col-md-5" data-ng-bind="form"></span>
<small class="col-xs-12">
<em class="text-muted">
Created on
<span data-ng-bind="form.created | date:'mediumDate'"></span>
by
<span data-ng-bind="form.admin.displayName"></span>
</em>
</small>
</div>
<small>
<em class="text-muted">
Created on
<span data-ng-bind="form.created | date:'mediumDate'"></span>
by
<span data-ng-bind="form.admin.displayName"></span>
</em>
</small>
<!-- <p class="lead" data-ng-bind="form.content"></p> -->
</section>

View file

@ -1,33 +1,32 @@
<link rel="stylesheet" href="./modules/forms/css/form.css">
<section data-ng-controller="SubmitFormController">
<form-directive form="form"></form-directive><hr>
<form-directive form="form"></form-directive>
<section class="navbar navbar-fixed-bottom" style="background-color:rgba(242,242,242,0.5); padding-top:15px;">
<div class="container" >
<nav role="navigation">
<ul class="nav navbar-nav navbar-left" >
<li class="">
<!-- <p class="lead">{{form | formValidity}} out of {{form.form_fields.length}} answered</p> -->
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li style="padding-right:20px" >
<a href="/forms/create" class="btn btn-default" ng-hide="authentication.user">create a Medform</a>
</li>
<li style="padding-right:20px" ng-show="authentication.user">
<a href="/forms/{{form._id}}/edit" class="btn btn-default">edit this Medform</a>
</li>
<li style="padding-left:5px">
<div class="btn btn-info" id="focusDownButton">\/</div>
</li>
<li style="padding-left:5px">
<div class="btn btn-info" id="focusUpButton">/\</div>
</li>
</ul>
</nav>
</div>
</section>
<section ng-if="!form.hideFooter" class="navbar navbar-fixed-bottom" style="background-color:rgba(242,242,242,0.5); padding-top:15px;">
<div class="container" >
<nav role="navigation">
<ul class="nav navbar-nav navbar-left" >
<li class="">
<!-- <p class="lead">{{form | formValidity}} out of {{form.form_fields.length}} answered</p> -->
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li style="padding-right:20px" >
<a href="/forms/create" class="btn btn-default" ng-hide="authentication.user">create a Medform</a>
</li>
<li style="padding-right:20px" ng-show="authentication.user">
<a href="/forms/{{form._id}}/edit" class="btn btn-default">edit this Medform</a>
</li>
<li style="padding-left:5px">
<div class="btn btn-info" id="focusDownButton">\/</div>
</li>
<li style="padding-left:5px">
<div class="btn btn-info" id="focusUpButton">/\</div>
</li>
</ul>
</nav>
</div>
</section>
</section>

View file

@ -1,6 +1,7 @@
'use strict';
// Config HTTP Error Handling
<<<<<<< HEAD
angular.module('users').config(['$httpProvider', '$state', 'Principal', '$q',
function($httpProvider, $state, Principal, $q) {
// Set the httpProvider "not authorized" interceptor
@ -20,6 +21,61 @@ angular.module('users').config(['$httpProvider', '$state', 'Principal', '$q',
// Add unauthorized behaviour
break;
}
=======
angular.module('users').config(['$httpProvider',
function($httpProvider) {
$httpProvider.interceptors.push(function($q, $location) {
return {
responseError: function(response) {
if( $location.path() !== '/users/me' ){
console.log('intercepted rejection of ', response.config.url, response.status);
if (response.status === 401) {
// save the current location so that login can redirect back
$location.nextAfterLogin = $location.path();
$location.path('/signin');
}else if(response.status === 403){
$location.path('/access_denied');
}
}
return $q.reject(response);
}
};
});
}]);
// Config HTTP Error Handling
// angular.module('users').config(['$httpProvider',
// function($httpProvider) {
// // Set the httpProvider "not authorized" interceptor
// $httpProvider.interceptors.push(['$q', '$location', 'Principal',
// function($q, $state, Principal) {
// return {
// responseSuccess: function(response) {
// Principal.identity().then(function(user){
// console.log(user);
// // $rootScope.user = user;
// }, function(error){
// console.log("Coudn't get current user. \n ERROR: "+error);
// });
// },
// responseError: function(rejection) {
// switch (rejection.status) {
// case 401:
// // Deauthenticate the global user
// Principal.authenticate(null);
// // Redirect to signin page
// $location.path('/signin');
// break;
// case 403:
// // Add unauthorized behaviour
// break;
// }
>>>>>>> dev_working
return $q.reject(rejection);
}

View file

@ -4,13 +4,45 @@
angular.module('users').config(['$stateProvider',
function($stateProvider) {
<<<<<<< HEAD
// Users state routing
$stateProvider.
=======
var checkLoggedin = function($q, $timeout, $location, User, Auth) {
var deferred = $q.defer();
console.log(Auth.getUserState);
if (Auth.currentUser && Auth.currentUser.email) {
$timeout(deferred.resolve);
}
else {
Auth.currentUser = User.getCurrent(function() {
Auth.login();
$timeout(deferred.resolve);
},
function() {
Auth.logout();
$timeout(deferred.reject);
$location.path('/login');
});
}
return deferred.promise;
};
// Users state routing
$stateProvider.
>>>>>>> dev_working
state('profile', {
// parent: 'restricted',
// data: {
// roles: ['user', 'admin'],
// },
resolve: {
loggedin: checkLoggedin
},
url: '/settings/profile',
templateUrl: 'modules/users/views/settings/edit-profile.client.view.html'
}).
@ -22,6 +54,9 @@ angular.module('users').config(['$stateProvider',
// data: {
// roles: ['user', 'admin'],
// },
resolve: {
loggedin: checkLoggedin
},
url: '/settings/password',
templateUrl: 'modules/users/views/settings/change-password.client.view.html'
}).
@ -30,6 +65,9 @@ angular.module('users').config(['$stateProvider',
// data: {
// roles: ['user', 'admin'],
// },
resolve: {
loggedin: checkLoggedin
},
url: '/settings/accounts',
templateUrl: 'modules/users/views/settings/social-accounts.client.view.html'
}).
@ -38,6 +76,10 @@ angular.module('users').config(['$stateProvider',
url: '/signup',
templateUrl: 'modules/users/views/authentication/signup.client.view.html'
}).
state('signup-success', {
url: '/signup-success',
templateUrl: 'modules/users/views/authentication/signup.client.view.html'
}).
state('signin', {
url: '/signin',
templateUrl: 'modules/users/views/authentication/signin.client.view.html'

View file

@ -1,51 +1,111 @@
'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Principal', '$state',
function($scope, $http, $location, Principal, $state) {
angular.module('users').controller('AuthenticationController', ['$scope', '$location', '$state', '$rootScope', 'User', 'Auth',
function($scope, $location, $state, $rootScope, User, Auth) {
$scope.authentication = Principal;
// $scope.authentication.user = Principal.getUser();
$scope = $rootScope;
$scope.credentials = {};
// If user is signed in then redirect back home
if ($scope.authentication.isAuthenticated()) $state.go('home');
// $scope.authentication = Principal;
$scope.signup = function() {
var response_obj = Principal.signup($scope.credentials);
if( angular.isDefined(response_obj.error) ){
$scope.error = response_obj.error;
} else{
$state.go('home');
// If user is signed in then redirect back home
if ($scope.authentication.isAuthenticated()) $state.go('home');
$scope.signin = function() {
// console.log("signin");
// console.log($scope.credentials);
Auth.currentUser = User.login($scope.credentials).then(
function(response) {
Auth.login();
$rootScope.user = Auth.ensureHasCurrentUser(User);
$scope = $rootScope;
console.log('$state.previous: \n');
console.log($state.previous);
if($state.previous !== 'home'){
$state.go($state.previous.name);
}else{
$state.go('home');
}
},
function(error) {
$rootScope.user = Auth.ensureHasCurrentUser(User);
$scope = $rootScope;
$scope.error = error;
console.log('loginError: '+error);
}
// $http.post('/auth/signup', $scope.credentials).success(function(response) {
// // If successful we assign the response to the global user model
// $scope.authentication.user = response;
);
};
// // And redirect to the index page
// $location.path('/');
// }).error(function(response) {
// $scope.error = response.message;
// });
};
$scope.signup = function() {
$scope.user = User.save($scope.registration,
function() {
$state.go('signup-success');
},
function(error) {
if(error) {
$scope.error = error;
}else {
console.log('No response received');
}
}
);
};
$scope.signin = function() {
console.log('signin');
var response_obj = Principal.signin($scope.credentials);
if( angular.isDefined(response_obj.error) ){
$scope.error = response_obj.error;
$location.path('/signin');
} else{
$location.path('/');
}
// $http.post('/auth/signin', $scope.credentials).success(function(response) {
// // If successful we assign the response to the global user model
// $scope.authentication.user = response;
// // And redirect to the index page
// $location.path('/');
// }).error(function(response) {
// $scope.error = response.message;
// });
};
}
// $scope.signup = function() {
// Principal.signup($scope.credentials).then(
// function(result){
// $state.go('home');
// },
// function(rejection_reason){
// $scope.error = rejection_reason;
// }
// );
// // $http.post('/auth/signup', $scope.credentials).success(function(response) {
// // // If successful we assign the response to the global user model
// // $scope.authentication.user = response;
// // Principal.authenticate(response);
// // // And redirect to the index page
// // $location.path('/');
// // }).error(function(response) {
// // $scope.error = response.message;
// // });
// };
// $scope.signin = function() {
// console.log('signin');
// Principal.signin($scope.credentials).then(
// function(result){
// $state.go('home');
// },
// function(rejection_reason){
// $scope.error = rejection_reason;
// }
// );
// // var response_obj = Principal.signin($scope.credentials);
// // if( angular.isDefined(response_obj.error) ){
// // $scope.error = response_obj.error;
// // $location.path('/signin');
// // } else{
// // $location.path('/');
// // }
// // $http.post('/auth/signin', $scope.credentials).success(function(response) {
// // // If successful we assign the response to the global user model
// // $scope.authentication.user = response;
// // Principal.authenticate(response);
// // // And redirect to the index page
// // $location.path('/');
// // }).error(function(response) {
// // Principal.authenticate(null);
// // $scope.error = response.message;
// // });
// };
// }
}
]);

View file

@ -1,45 +1,61 @@
'use strict';
angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$http', '$state', 'Principal',
function($scope, $stateParams, $http, $state, Principal) {
$scope.authentication = Principal;
$scope.authentication.user = Principal.user();
angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$state', 'User',
function($scope, $stateParams, $state, User) {
// $scope.authentication = Principal;
//If user is signed in then redirect back home
if ($scope.authentication.user) $state.go('home');
if ($scope.authentication.isAuthenticated()) $state.go('home');
// Submit forgotten password account id
$scope.askForPasswordReset = function() {
$scope.success = $scope.error = null;
// Principal.identity().then(function(response){
// $scope.authentication.user = response;
$http.post('/auth/forgot', $scope.credentials).success(function(response) {
// Show user success message and clear form
$scope.credentials = null;
$scope.success = response.message;
// Submit forgotten password account id
$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;
}
);
};
}).error(function(response) {
// Show user error message and clear form
$scope.credentials = null;
$scope.error = response.message;
});
};
// Change user password
$scope.resetUserPassword = function() {
$scope.success = $scope.error = null;
User.resetPassword($scope.passwordDetails, $stateParams.token).then(
function(response){
// If successful show success message and clear form
$scope.success = response.message;
$scope.passwordDetails = null;
// Change user password
$scope.resetUserPassword = function() {
$scope.success = $scope.error = null;
// And redirect to the index page
$state.go('reset-success');
},
function(error){
$scope.error = error.message || error;
$scope.passwordDetails = null;
}
);
// $scope.success = $scope.error = null;
$http.post('/auth/reset/' + $stateParams.token, $scope.passwordDetails).success(function(response) {
// If successful show success message and clear form
$scope.passwordDetails = null;
// $http.post('/auth/reset/' + $stateParams.token, $scope.passwordDetails).success(function(response) {
// // If successful show success message and clear form
// $scope.passwordDetails = null;
// Attach user profile
// Principal.user() = response;
// // Attach user profile
// // Principal.user() = response;
// And redirect to the index page
$state.go('reset-success');
}).error(function(response) {
$scope.error = response.message;
});
};
// // And redirect to the index page
// $state.go('reset-success');
// }).error(function(response) {
// $scope.error = response.message;
// });
};
// });
}
]);

View file

@ -1,11 +1,12 @@
'use strict';
angular.module('users').controller('SettingsController', ['$scope', '$http', '$state', 'Users', 'Principal',
function($scope, $http, $state, Users, Principal) {
angular.module('users').controller('SettingsController', ['$scope', '$http', '$state', 'Users',
function($scope, $http, $state, Users) {
Principal.identity().then(function(user){
$scope.user = user;
}).then(function(){
// Principal.identity().then(function(user){
// $scope.user = user;
// }).then(function(){
// $scope.user = Principal.identity();
// If user is not signed in then redirect back home
if (!$scope.user) $state.go('home');
@ -71,6 +72,6 @@ angular.module('users').controller('SettingsController', ['$scope', '$http', '$s
});
};
});
// });
}
]);

View file

@ -11,4 +11,22 @@
top: 10px;
right: 10px;
position: absolute;
}
}
section.auth {
margin-top: 5em;
}
section.auth > h3{
font-size: 3em;
font-weight: 500;
color: #777;
}
section.auth.signup-view > h3 {
font-size: 4.4em;
padding-bottom: 0.5em;
}
section.auth.signup-view.success > h3 {
padding-bottom: 1.2em;
}

View file

@ -0,0 +1,67 @@
'use strict';
angular.module('users')
.factory('Auth', function($window) {
var userState =
{
isLoggedIn: false
};
var service = {
currentUser: null,
// Note: we can't make the User a dependency of Auth
// because that would create a circular dependency
// Auth <- $http <- $resource <- LoopBackResource <- User <- Auth
ensureHasCurrentUser: function(User) {
if (service.currentUser && service.currentUser.displayName) {
console.log('Using local current user.');
console.log(service.currentUser);
return service.currentUser;
}
else if ($window.user){
console.log('Using cached current user.');
console.log($window.user);
service.currentUser = $window.user;
return service.currentUser;
}
else{
console.log('Fetching current user from the server.');
User.getCurrent().then(function(user) {
// success
service.currentUser = user;
userState.isLoggedIn = true;
$window.user = service.currentUser;
return service.currentUser;
},
function(response) {
userState.isLoggedIn = false;
service.currentUser = null;
$window.user = null;
console.log('User.getCurrent() err', response);
return null;
});
}
},
isAuthenticated: function() {
return !!service.currentUser;
},
getUserState: function() {
return userState;
},
login: function() {
userState.isLoggedIn = true;
},
logout: function() {
$window.user = null;
userState.isLoggedIn = false;
service.currentUser = null;
service.ensureHasCurrentUser(null);
},
};
return service;
});

View file

@ -0,0 +1,91 @@
'use strict';
angular.module('users').factory('User', ['$window', '$q', '$timeout', '$http', '$state',
function($window, $q, $timeout, $http, $state) {
var userService = {
getCurrent: function() {
var deferred = $q.defer();
$http.get('/users/me')
.success(function(response) {
deferred.resolve(response);
})
.error(function() {
deferred.reject('User\'s session has expired');
});
return deferred.promise;
},
login: function(credentials) {
var deferred = $q.defer();
$http.post('/auth/signin', credentials).success(function(response) {
// console.log(response);
deferred.resolve(response);
}).error(function(error) {
deferred.reject(error.message || error);
});
return deferred.promise;
},
logout: function() {
var deferred = $q.defer();
$http.get('/auth/signout').success(function(response) {
deferred.resolve(null);
}).error(function(error) {
deferred.reject(error.message || error);
});
return deferred.promise;
},
signup: function(credentials) {
var deferred = $q.defer();
$http.post('/auth/signup', credentials).success(function(response) {
// If successful we assign the response to the global user model
deferred.resolve(response);
}).error(function(error) {
deferred.reject(error.message || error);
});
return deferred.promise;
},
resetPassword: function(passwordDetails, token) {
var deferred = $q.defer();
$http.get('/auth/password/'+token, passwordDetails).success(function(response) {
deferred.resolve();
}).error(function(error) {
deferred.reject(error.message || error);
});
return deferred.promise;
},
// Submit forgotten password account id
askForPasswordReset: function(credentials) {
var deferred = $q.defer();
$http.post('/auth/forgot', credentials).success(function(response) {
// Show user success message and clear form
deferred.resolve(response);
}).error(function(error) {
// Show user error message
deferred.reject(error.message || error);
});
return deferred.promise;
},
};
return userService;
}
]);

View file

@ -1,4 +1,4 @@
<section class="row text-center">
<section class="row text-center auth">
<h3 class="col-md-12">You need to be logged in to access this page</h3>
<a href="/#!/sigin" class="col-md-12">Login</a>
</section>

View file

@ -1,4 +1,4 @@
<section class="row" data-ng-controller="AuthenticationController">
<section class="row auth" data-ng-controller="AuthenticationController">
<h3 class="col-md-12 text-center">Sign in with your account</h3>
<!-- <div class="col-md-12 text-center">
<a href="/auth/facebook" class="undecorated-link">
@ -18,9 +18,12 @@
</a>
</div> -->
<!-- <h3 class="col-md-12 text-center">Or with your account</h3> -->
<div class="col-xs-offset-2 col-xs-8 col-md-offset-5 col-md-2">
<form class="signin form-horizontal" ng-submit="signin()" autocomplete="off">
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<form class="signin form-horizontal" autocomplete="off" action="">
<fieldset>
<div data-ng-show="error" class="text-center text-danger">
Error: <strong data-ng-bind="error"></strong>
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">
@ -29,16 +32,15 @@
<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="forgot-password">
<a href="/#!/password/forgot">Forgot your password?</a>
</div>
<div class="text-center form-group">
<button type="submit" class="btn btn-primary" ng-click="signin()">Sign in</button>&nbsp; or&nbsp;
<a href="/#!/signup">Sign up</a>
</div>
<div class="forgot-password">
<a href="/#!/password/forgot">Forgot your password?</a>
</div>
<div data-ng-show="error" class="text-center text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>

View file

@ -0,0 +1,33 @@
<section class="row auth signup-view success" data-ng-controller="AuthenticationController">
<!-- <h3 class="col-md-12 text-center">Sign up using your social accounts</h3>
<div class="col-md-12 text-center">
<a href="/auth/facebook" class="undecorated-link">
<img src="/modules/users/img/buttons/facebook.png">
</a>
<a href="/auth/twitter" class="undecorated-link">
<img src="/modules/users/img/buttons/twitter.png">
</a>
<a href="/auth/google" class="undecorated-link">
<img src="/modules/users/img/buttons/google.png">
</a>
<a href="/auth/linkedin" class="undecorated-link">
<img src="/modules/users/img/buttons/linkedin.png">
</a>
<a href="/auth/github" class="undecorated-link">
<img src="/modules/users/img/buttons/github.png">
</a>
</div> -->
<h3 class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6 text-center">Signup with your email</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<h2>Congrats! You've successfully registered an account at MedForms. </h2>
<p>Before you continue, make sure to check your email for our verification email. If you don't receive it within 24h drop us a line</p>
<ul>
<li>
Click
<em href="#!/">Here</em>
to continue
</li>
</ul>
</div>
</div>
</section>

View file

@ -1,5 +1,5 @@
<section class="row" data-ng-controller="AuthenticationController">
<h3 class="col-md-12 text-center">Sign up using your social accounts</h3>
<section class="row auth signup-view" data-ng-controller="AuthenticationController">
<!-- <h3 class="col-md-12 text-center">Sign up using your social accounts</h3>
<div class="col-md-12 text-center">
<a href="/auth/facebook" class="undecorated-link">
<img src="/modules/users/img/buttons/facebook.png">
@ -16,11 +16,15 @@
<a href="/auth/github" class="undecorated-link">
<img src="/modules/users/img/buttons/github.png">
</a>
</div>
<h3 class="col-md-12 text-center">Or with your email</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-5 col-md-2">
</div> -->
<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 type="text" required id="firstName" name="firstName" class="form-control" data-ng-model="credentials.firstName" placeholder="First Name">
@ -45,9 +49,7 @@
<button type="submit" class="btn btn-large btn-primary">Sign up</button>&nbsp; or&nbsp;
<a href="/#!/signin" class="show-signup">Sign in</a>
</div>
<div data-ng-show="error" class="text-center text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>

View file

@ -1,7 +1,7 @@
<section class="row" data-ng-controller="PasswordController">
<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 username.</p>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-5 col-md-2">
<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">

View file

@ -1,6 +1,6 @@
<section class="row" data-ng-controller="PasswordController">
<section class="row auth" data-ng-controller="PasswordController">
<h3 class="col-md-12 text-center">Reset your password</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-5 col-md-2">
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<form data-ng-submit="resetUserPassword()" class="signin form-horizontal" autocomplete="off">
<fieldset>
<div class="form-group">

View file

@ -1,4 +1,4 @@
<section class="row" data-ng-controller="SettingsController">
<section class="row auth" data-ng-controller="SettingsController">
<h3 class="col-md-12 text-center">Change your password</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<form data-ng-submit="changeUserPassword()" class="signin form-horizontal" autocomplete="off">
@ -7,6 +7,7 @@
<label for="currentPassword">Current Password</label>
<input type="password" id="currentPassword" name="currentPassword" class="form-control" data-ng-model="passwordDetails.currentPassword" placeholder="Current Password">
</div>
<hr>
<div class="form-group">
<label for="newPassword">New Password</label>
<input type="password" id="newPassword" name="newPassword" class="form-control" data-ng-model="passwordDetails.newPassword" placeholder="New Password">

View file

@ -1,8 +1,15 @@
<section class="row" data-ng-controller="SettingsController">
<section class="row auth" data-ng-controller="SettingsController">
<h3 class="col-md-12 text-center">Edit your profile</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<form name="userForm" data-ng-submit="updateUserProfile(userForm.$valid)" class="signin form-horizontal" autocomplete="off">
<fieldset>
<div data-ng-show="success" class="text-center text-success">
<strong>Profile Saved Successfully</strong>
</div>
<div data-ng-show="error" class="text-center text-danger">
Couldn't Save your Profile.<br>
Error: <strong data-ng-bind="error"></strong>
</div>
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="firstName" class="form-control" data-ng-model="user.firstName" placeholder="First Name">
@ -15,19 +22,10 @@
<label for="email">Email</label>
<input type="email" id="email" name="email" class="form-control" data-ng-model="user.email" placeholder="Email">
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" class="form-control" data-ng-model="user.username" placeholder="Username">
</div>
<div class="text-center form-group">
<button type="submit" class="btn btn-large btn-primary">Save Profile</button>
</div>
<div data-ng-show="success" class="text-center text-success">
<strong>Profile Saved Successfully</strong>
</div>
<div data-ng-show="error" class="text-center text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>

View file

@ -1,4 +1,4 @@
<section class="row" data-ng-controller="SettingsController">
<section class="row auth" data-ng-controller="SettingsController">
<h3 class="col-md-12 text-center" data-ng-show="hasConnectedAdditionalSocialAccounts()">Connected social accounts:</h3>
<div class="col-md-12 text-center">
<div data-ng-repeat="(providerName, providerData) in user.additionalProvidersData" class="remove-account-container">