added files

This commit is contained in:
David Baldwynn 2015-06-29 23:12:32 -07:00
parent ebca4591fa
commit 0d0af31c4e
40 changed files with 326 additions and 369 deletions

View file

@ -1,120 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Article = mongoose.model('Article'),
_ = require('lodash');
/**
* Create a article
*/
exports.create = function(req, res) {
var article = new Article(req.body);
article.user = req.user;
article.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* Show the current article
*/
exports.read = function(req, res) {
res.json(req.article);
};
/**
* Update a article
*/
exports.update = function(req, res) {
var article = req.article;
article = _.extend(article, req.body);
article.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* Delete an article
*/
exports.delete = function(req, res) {
var article = req.article;
article.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
/**
* List of Articles
*/
exports.list = function(req, res) {
Article.find().sort('-created').populate('user', 'displayName').exec(function(err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
};
/**
* Article middleware
*/
exports.articleByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Article is invalid'
});
}
Article.findById(id).populate('user', 'displayName').exec(function(err, article) {
if (err) return next(err);
if (!article) {
return res.status(404).send({
message: 'Article not found'
});
}
req.article = article;
next();
});
};
/**
* Article authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.article.user.id !== req.user.id) {
return res.status(403).send({
message: 'User is not authorized'
});
}
next();
};

View file

@ -42,10 +42,10 @@ exports.uploadPDF = function(req, res) {
var parser = new PDFParser(),
pdfFile = req.files.file;
console.log(pdfFile);
// console.log(pdfFile);
var form = Form.findById(req.body.form._id);
console.log(req.files);
// console.log(req.files);
if (req.files) {
@ -55,16 +55,16 @@ exports.uploadPDF = function(req, res) {
});
}
fs.exists(pdfFile.path, function(exists) {
if(exists) {
// console.log('UPLOADING FILE \N\N');
return res.status(200).send({
message: 'Got your file!'
});
} else {
return res.status(400).send({
message: 'Did NOT get your file!'
});
}
console.log(pdfFile.path);
fs.open(pdfFile.path,'r',function(err,fd){
if (err && err.code === 'ENOENT') {
return res.status(400).send({
message: 'Did NOT get your file!'
});
}
return res.status(200);
});
});
}
@ -134,7 +134,7 @@ exports.createSubmission = function(req, res) {
/**
* Get List of Submissions for a given Template Form
* Get List of Submissions for a given Form
*/
exports.listSubmissions = function(req, res) {
var _form = req.form;
@ -192,10 +192,10 @@ exports.delete = function(req, res) {
};
/**
* Get List of Template Forms
* Get List of Forms
*/
exports.list = function(req, res) {
Form.find({ type: 'template' }).sort('-created').populate('admin').exec(function(err, forms) {
Form.find().sort('-created').populate('admin').exec(function(err, forms) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)

View file

@ -28,9 +28,9 @@ exports.requiresLogin = function(req, res, next) {
return res.status(401).send({
message: 'User is not logged in'
});
}else {
next();
}
next();
};
/**

View file

@ -67,45 +67,45 @@ var FormSchema = new Schema({
},
});
//Move PDF to permanent location after first save
//Move PDF to permanent location after new PDF is uploaded
FormSchema.pre('save', function (next) {
// console.log(this.pdf);
// debugger;
if(this.pdf){
if(this.pdf.modified){
if(this.pdf && this.isModified('pdf')){
console.log('Relocating PDF');
var new_filename = this.pdf.title.trim()+'_template.pdf';
var new_filename = this.pdf.title.trim()+'_template.pdf';
var newDestination = path.join(config.pdfUploadPath, this.pdf.title.trim()),
stat = null;
var newDestination = path.join(config.pdfUploadPath, this.pdf.title.trim()),
stat = null;
try {
stat = fs.statSync(newDestination);
} catch (err) {
fs.mkdirSync(newDestination);
}
if (stat && !stat.isDirectory()) {
console.log('Directory cannot be created');
next( new Error('Directory cannot be created because an inode of a different type exists at "' + config.pdfUploadPath + '"') );
}
try {
stat = fs.statSync(newDestination);
} catch (err) {
fs.mkdirSync(newDestination);
}
if (stat && !stat.isDirectory()) {
console.log('Directory cannot be created');
next( new Error('Directory cannot be created because an inode of a different type exists at "' + config.pdfUploadPath + '"') );
}
console.log('about to move PDF');
fs.move(this.pdf.path, path.join(newDestination, new_filename), function (err) {
if (err) {
console.error(err);
next( new Error(err.message) );
}
console.log('about to move PDF');
fs.move(this.pdf.path, path.join(newDestination, new_filename), function (err) {
if (err) {
console.error(err);
next( new Error(err.message) );
}
this.pdf.path = path.join(newDestination, new_filename);
this.pdf.name = new_filename;
this.pdf.path = path.join(newDestination, new_filename);
this.pdf.name = new_filename;
console.log('PDF file:'+this.pdf.name+' successfully moved to: '+this.pdf.path);
console.log('PDF file:'+this.pdf.name+' successfully moved to: '+this.pdf.path);
next();
});
next();
});
}
}else {
next();
}
@ -134,9 +134,10 @@ FormSchema.pre('save', function (next) {
//Convert types from FDF to 'FormField' types
if(_typeConvMap[ field.fieldType+'' ]){
field.fieldType = _pdfConvMap[ field.fieldType+'' ];
field.fieldType = _typeConvMap[ field.fieldType+'' ];
}
//Set field defaults
field.created = Date.now();
field.fieldValue = '';
field.required = true;

View file

@ -58,21 +58,21 @@ var FormSubmissionSchema = new Schema({
});
//Check for IP Address of submitting person
// FormSubmissionSchema.pre('save', function (next){
// if(this.ipAddr){
// if(this.ipAddr.modified){
// satelize.satelize({ip: this.ipAddr}, function(err, geoData){
// if (err) next( new Error(err.message) );
FormSubmissionSchema.pre('save', function (next){
if(this.ipAddr){
if(this.ipAddr.modified){
satelize.satelize({ip: this.ipAddr}, function(err, geoData){
if (err) next( new Error(err.message) );
this.geoLocation = JSON.parse(geoData);
next();
});
}
}
// console.log('ipAddr check');
next();
});
// this.geoLocation = JSON.parse(geoData);
// next();
// });
// }
// }
// console.log('ipAddr check');
// next();
// });
//Generate autofilled PDF if flags are set
FormSubmissionSchema.pre('save', function (next) {

View file

@ -1,22 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var users = require('../../app/controllers/users.server.controller'),
articles = require('../../app/controllers/articles.server.controller');
module.exports = function(app) {
// Article Routes
app.route('/articles')
.get(articles.list)
.post(users.requiresLogin, articles.create);
app.route('/articles/:articleId')
.get(articles.read)
.put(users.requiresLogin, articles.hasAuthorization, articles.update)
.delete(users.requiresLogin, articles.hasAuthorization, articles.delete);
// Finish by binding the article middleware
app.param('articleId', articles.articleByID);
};

View file

@ -9,7 +9,7 @@ var users = require('../../app/controllers/users.server.controller'),
module.exports = function(app) {
// Form Routes
app.route('/upload/pdf')
.post(forms.uploadPDF);
.post(users.requiresLogin, forms.uploadPDF);
app.route('/forms')
.get(forms.list)
@ -19,7 +19,7 @@ module.exports = function(app) {
.get(forms.read)
.post(forms.createSubmission)
.put(users.requiresLogin, forms.hasAuthorization, forms.update)
.delete(users.requiresLogin, forms.delete);
.delete(users.requiresLogin, forms.hasAuthorization,forms.delete);
// Finish by binding the form middleware
app.param('formId', forms.formByID);

View file

@ -11,11 +11,11 @@ module.exports = function(app) {
// Setting up the users profile api
app.route('/users/me').get(users.me);
app.route('/users').put(users.update);
app.route('/users').put(users.requiresLogin, users.update);
app.route('/users/accounts').delete(users.removeOAuthProvider);
// Setting up the users password api
app.route('/users/password').post(users.changePassword);
app.route('/users/password').post(users.requiresLogin, users.changePassword);
app.route('/auth/forgot').post(users.forgot);
app.route('/auth/reset/:token').get(users.validateResetToken);
app.route('/auth/reset/:token').post(users.reset);

View file

@ -58,6 +58,7 @@
var user = {{ user | json | safe }};
</script>
<!--Application JavaScript Files-->
{% for jsFile in jsFiles %}
<script type="text/javascript" src="{{jsFile}}"></script>

View file

@ -118,11 +118,12 @@ module.exports = function(db) {
// return newDestination;
// },
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...');
//Check to make sure we can only upload images and pdfs
console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path);
// done=true;
console.log(file.fieldname + ' has been uploaded to: ' + file.path);
// done=true;
}
}));

View file

@ -11,16 +11,16 @@ angular.module('core').config(['$stateProvider', '$urlRouterProvider',
state('home', {
url: '/',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('restricted', {
'abstract': true,
resolve: {
authorize: ['Authorization',
function(Authorization) {
return Authorization.authorize();
}
]
}
});
// state('restricted', {
// 'abstract': true,
// resolve: {
// authorize: ['Authorization',
// function(Authorization) {
// return Authorization.authorize();
// }
// ]
// }
// });
}
]);

View file

@ -34,9 +34,9 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
};
$scope.removePDF = function(){
$scope.form.pdf = null;
console.log('form.pdf exists: '+!!$scope.form.pdf);
$scope.form.pdf = undefined;
$scope.form.isGenerated = false;
$scope.form.autofillPDFs = false;
};
$scope.uploadPDF = function(files) {
@ -57,7 +57,6 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
evt.config.file.name + '\n' + $scope.log;
}).success(function (data, status, headers, config) {
$scope.log = 'file ' + data.originalname + 'uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log;
$scope.pdf = data;
$scope.form.pdf = data;
if(!$scope.$$phase) {
@ -85,7 +84,7 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
form.$save(function(response) {
console.log('form created');
console.log('create form');
// console.log(response.pdf);
// Clear form fields

View file

@ -1,30 +1,30 @@
// 'use strict';
'use strict';
// // 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, $location, Principal) {
// return {
// responseError: function(rejection) {
// switch (rejection.status) {
// case 401:
// // Deauthenticate the global user
// Principal.authenticate(null);
// Config HTTP Error Handling
angular.module('users').config(['$httpProvider', '$state', 'Principal', '$q',
function($httpProvider, $state, Principal, $q) {
// Set the httpProvider "not authorized" interceptor
$httpProvider.interceptors.push(['$q', '$state', 'Principal',
function($q, $state, Principal) {
return {
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;
// }
// Redirect to signin page
$state.go('signin');
break;
case 403:
// Add unauthorized behaviour
break;
}
// return $q.reject(rejection);
// }
// };
// }
// ]);
// }
// ]);
return $q.reject(rejection);
}
};
}
]);
}
]);

View file

@ -3,6 +3,7 @@
// Setting up route
angular.module('users').config(['$stateProvider',
function($stateProvider) {
// Users state routing
$stateProvider.
state('profile', {
@ -14,6 +15,9 @@ angular.module('users').config(['$stateProvider',
templateUrl: 'modules/users/views/settings/edit-profile.client.view.html'
}).
state('password', {
// resolve: {
// checkLoggedin: Authorization.authorize
// },
// parent: 'restricted',
// data: {
// roles: ['user', 'admin'],

View file

@ -1,28 +1,47 @@
'use strict';
angular.module('users').service('Authorization', ['$rootScope', '$location', 'Principal',
function($rootScope, $location, Principal) {
angular.module('users').factory('Authorization', ['$rootScope', '$http', '$q', '$state', 'Principal',
function($rootScope, $http, $q, $state, Principal) {
var service = {
authorize: function(){
var deferred = $q.defer();
$http.get('/user/me').success(function(response) {
this.authorize = function() {
return Principal.identity().then(function(){
var isAuthenticated = Principal.isAuthenticated();
if( angular.isDefined($rootScope.toState.data) ){
// if ($rootScope.toState.data.roles && $rootScope.toState.data.roles.length > 0 && !principal.isInAnyRole($rootScope.toState.data.roles)) {
if (!isAuthenticated){ //$location.path('/access_denied'); // user is signed in but not authorized for desired state
// console.log('isAuthenticated: '+isAuthenticated);
// else {
// user is not authenticated. so the state they wanted before you
// send them to the signin state, so you can return them when you're done
$rootScope.returnToState = $rootScope.toState;
$rootScope.returnToStateParams = $rootScope.toStateParams;
// now, send them to the signin state so they can log in
$location.path('/signin');
}
// }
}
//user is logged in
if(response.data !== null){
deferred.resolve();
}else {
$rootScope.message = 'You need to log in.';
deferred.reject();
$state.go('/login');
}
});
};
return deferred.promise();
}
};
return service;
// this.authorize = function() {
// return Principal.identity().then(function(){
// var isAuthenticated = Principal.isAuthenticated();
// if( angular.isDefined($rootScope.toState.data) ){
// // if ($rootScope.toState.data.roles && $rootScope.toState.data.roles.length > 0 && !principal.isInAnyRole($rootScope.toState.data.roles)) {
// if (!isAuthenticated){ //$location.path('/access_denied'); // user is signed in but not authorized for desired state
// // console.log('isAuthenticated: '+isAuthenticated);
// // else {
// // user is not authenticated. so the state they wanted before you
// // send them to the signin state, so you can return them when you're done
// $rootScope.returnToState = $rootScope.toState;
// $rootScope.returnToStateParams = $rootScope.toStateParams;
// // now, send them to the signin state so they can log in
// $location.path('/signin');
// }
// // }
// }
// });
// };
}
]);

View file

@ -1,24 +1,69 @@
'use strict';
angular.module('users').factory('Principal', ['$window', '$http', '$q', '$timeout', '$state',
function($window, $http, $q, $timeout, $state) {
var _identity,
_authenticated = false;
angular.module('users').factory('AuthenticationService', function($http, $timeout, $q) {
var error;
var service = {
// Information about the current user
currentUser: null,
return {
isIdentityResolved: function() {
return angular.isDefined(_identity);
login: function(credentials) {
var login = $http.post('/auth/signin', credentials);
login.success(function(data) {
service.currentUser = data.user;
// $flash.clear();
}).error(function(error) {
error = error.error ? error.error : error;
console.error(error.message || error);
});
return login;
},
logout: function() {
var logout = $http.get('/auth/logout');
logout.success(function() {
service.currentUser = null;
console.log("You've successfully logged out");
});
return logout;
},
signup: function(credentials) {
var signup = $http.post('/auth/signup', credentials)
signup.success(function(response) {
console.log("You've successfully created an account");
}).error(function(response) {
error = error.error ? error.error : error;
console.error(error.message || error);
});
return signup;
},
// Ask the backend to see if a user is already authenticated -
// this may be from a previous session.
identity: function() {
if (service.isAuthenticated()) {
return $q.when(service.currentUser);
} else {
return $http.get('/user/me').then(function(response) {
service.currentUser = response.data.user;
return service.currentUser;
});
}
},
// Is the current user authenticated?
isAuthenticated: function() {
return _authenticated;
return !!service.currentUser;
},
isInRole: function(role) {
if (!_authenticated || !_identity.roles) return false;
return _identity.roles.indexOf(role) !== -1;
isInRole: function(role) {
return service.isAuthenticated() (service.currentUser.roles.indexOf(role) !== -1);
},
isInAnyRole: function(roles) {
if (!_authenticated || !_identity.roles) return false;
if ( !service.isAuthenticated() || !service.currentUser.roles) return false;
var roles = service.currentUser.roles;
for (var i = 0; i < roles.length; i++) {
if (this.isInRole(roles[i])) return true;
@ -26,103 +71,132 @@ angular.module('users').factory('Principal', ['$window', '$http', '$q', '$timeou
return false;
},
authenticate: function(user) {
_identity = user;
_authenticated = (user !== null);
};
return service;
});
// .factory('Principal', ['$window', '$http', '$q', '$timeout', '$state',
// function($window, $http, $q, $timeout, $state) {
// var _identity,
// _authenticated = false;
// return {
// isIdentityResolved: function() {
// return angular.isDefined(_identity);
// },
// isAuthenticated: function() {
// return _authenticated;
// },
// isInRole: function(role) {
// if (!_authenticated || !_identity.roles) return false;
// return _identity.roles.indexOf(role) !== -1;
// },
// isInAnyRole: function(roles) {
// if (!_authenticated || !_identity.roles) return false;
// for (var i = 0; i < roles.length; i++) {
// if (this.isInRole(roles[i])) return true;
// }
// return false;
// },
// authenticate: function(user) {
// _identity = user;
// _authenticated = (user !== null);
// for this demo, we'll store the identity in localStorage. For you, it could be a cookie, sessionStorage, whatever
if (user) $window.user = user;
else $window.user = null;
},
signin: function(credentials) {
// // for this demo, we'll store the identity in localStorage. For you, it could be a cookie, sessionStorage, whatever
// if (user) $window.user = user;
// else $window.user = null;
// },
// signin: function(credentials) {
var deferred = $q.defer();
var self = this;
$http.post('/auth/signin', credentials).success(function(response) {
// If successful we assign the response to the global user model
self.authenticate(response);
deferred.resolve(response);
}).error(function(response) {
_authenticated = false;
deferred.resolve({ error: response.message });
});
return deferred.promise;
},
signup: function(credentials) {
// var deferred = $q.defer();
// var self = this;
// $http.post('/auth/signin', credentials).success(function(response) {
// // If successful we assign the response to the global user model
// self.authenticate(response);
// deferred.resolve(response);
// }).error(function(response) {
// _authenticated = false;
// deferred.reject({ error: response.message });
// });
// return deferred.promise;
// },
// signup: function(credentials) {
var deferred = $q.defer();
// 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(response) {
// $http.post('/auth/signup', credentials).success(function(response) {
// // If successful we assign the response to the global user model
// deferred.resolve(response);
// }).error(function(response) {
deferred.resolve({ error: response.message });
});
// deferred.reject({ error: response.message });
// });
return deferred.promise;
},
signout: function() {
var deferred = $q.defer();
$http.get('/auth/signout').success(function(response) {
// If successful we assign the response to the global user model
deferred.resolve({});
}).error(function(response) {
deferred.resolve({ error: response.message });
});
// return deferred.promise;
// },
// signout: function() {
// var deferred = $q.defer();
// $http.get('/auth/signout').success(function(response) {
// // If successful we assign the response to the global user model
// deferred.resolve({});
// }).error(function(response) {
// deferred.reject({ error: response.message });
// });
_authenticated = false;
_identity = undefined;
// _authenticated = false;
// _identity = undefined;
return deferred.promise;
},
identity: function(force) {
var self = this;
// return deferred.promise;
// },
// identity: function() {
// var self = this;
var deferred = $q.defer();
// var deferred = $q.defer();
if (force === true) _identity = undefined;
// // check and see if we have retrieved the user data from the server. if we have, reuse it by immediately resolving
// if (angular.isDefined(_identity)) {
// check and see if we have retrieved the user data from the server. if we have, reuse it by immediately resolving
if (angular.isDefined(_identity)) {
// deferred.resolve(_identity);
// return deferred.promise;
// }else if($window.user){
// // console.log($window.user);
// // self.authenticate($window.user);
// // var user = $window.user;
// _identity = $window.user;
// self.authenticate(_identity);
// deferred.resolve(_identity);
deferred.resolve(_identity);
return deferred.promise;
}else if($window.user){
// console.log($window.user);
// self.authenticate($window.user);
// var user = $window.user;
_identity = $window.user;
self.authenticate(_identity);
deferred.resolve(_identity);
// return deferred.promise;
// }else {
return deferred.promise;
}else {
// otherwise, retrieve the user data from the server, update the user object, and then resolve.
$http.get('/users/me', { ignoreErrors: true })
.success(function(response) {
self.authenticate(response);
$window.user = response;
deferred.resolve(_identity);
})
.error(function() {
_identity = null;
_authenticated = false;
$window.user = null;
$state.path('signin');
deferred.resolve(_identity);
});
// // otherwise, retrieve the user data from the server, update the user object, and then resolve.
// $http.get('/users/me', { ignoreErrors: true })
// .success(function(response) {
// self.authenticate(response);
// $window.user = response;
// deferred.resolve(_identity);
// })
// .error(function() {
// _identity = null;
// _authenticated = false;
// $window.user = null;
// $state.path('signin');
// deferred.resolve(_identity);
// });
return deferred.promise;
}
},
getUser: function(){
this.identity(false).then( function(user){
return user;
});
}
};
// return deferred.promise;
// }
// },
// getUser: function(){
// this.identity(false).then( function(user){
// return user;
// });
// }
// };
}
]);
// }
// ]);

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.