fixed angularjs authentication

This commit is contained in:
David Baldwynn 2015-07-01 16:14:39 -07:00
parent d6b64187ab
commit 0cd8fca8e6
20 changed files with 337 additions and 359 deletions

View file

@ -12,6 +12,7 @@ var mongoose = require('mongoose'),
config = require('../../config/config'), config = require('../../config/config'),
fs = require('fs-extra'), fs = require('fs-extra'),
async = require('async'), async = require('async'),
path = require('path'),
_ = require('lodash'); _ = require('lodash');
/** /**
@ -38,39 +39,53 @@ exports.create = function(req, res) {
/** /**
* Upload PDF * Upload PDF
*/ */
exports.uploadPDF = function(req, res) { var upload_count = 0;
var parser = new PDFParser(), exports.uploadPDF = function(files, user, cb) {
pdfFile = req.files.file; var parser = new PDFParser();
console.log("upload count: "+upload_count);
upload_count++;
if(files) {
console.log(pdfFile); console.log('inside uploadPDF');
console.log(files.file[0]);
var pdfFile = files.file[0];
var form = Form.findById(req.body.form._id);
console.log(req.files);
if (req.files) {
if (pdfFile.size === 0) { if (pdfFile.size === 0) {
return res.status(400).send({ throw new Error('Files uploaded are EMPTY');
message: 'Hey, first would you select a file?'
});
} }
fs.exists(pdfFile.path, function(exists) { fs.exists(pdfFile.path, function(exists) {
//If file exists move to user's tmp directory
if(exists) { if(exists) {
// console.log('UPLOADING FILE \N\N');
return res.status(200).send({ var newDestination = path.join(config.tmpUploadPath, user.username);
message: 'Got your file!' 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 + '"');
}
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 { } else {
return res.status(400).send({ throw new Error('Did NOT get your file!');
message: 'Did NOT get your file!'
});
} }
}); });
} }else {
throw new Error('File NOT uploaded');
}
return res.status(400).send({
message: 'FILE NOT UPLOADED'
});
}; };
/** /**

View file

@ -12,7 +12,7 @@ module.exports = function(app) {
.post(forms.uploadPDF); .post(forms.uploadPDF);
app.route('/forms') app.route('/forms')
.get(users.requiresLogin, forms.hasAuthorization, forms.list) .get(users.requiresLogin, forms.list)
.post(users.requiresLogin, forms.create); .post(users.requiresLogin, forms.create);
app.route('/forms/:formId/submissions') app.route('/forms/:formId/submissions')

View file

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

View file

@ -47,7 +47,7 @@
<![endif]--> <![endif]-->
</head> </head>
<body ng-app="medform" ng-controller="IndexCtrl"> <body ng-cloak>
<header data-ng-include="'/modules/core/views/header.client.view.html'"></header> <header data-ng-include="'/modules/core/views/header.client.view.html'"></header>
<section class="content"> <section class="content">
<!-- <section class="container"> --> <!-- <section class="container"> -->

View file

@ -96,33 +96,28 @@ module.exports = function(db) {
// Setting the app router and static folder // Setting the app router and static folder
app.use(express.static(path.resolve('./public'))); app.use(express.static(path.resolve('./public')));
var formCtrl = require('../app/controllers/forms.server.controller');
// Setting the pdf upload route and folder // Setting the pdf upload route and folder
app.use(multer({ dest: config.tmpUploadPath, app.use(multer({ dest: config.tmpUploadPath,
rename: function (fieldname, filename) { rename: function (fieldname, filename) {
return Date.now(); 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) { onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...'); console.log(file.originalname + ' is starting ...');
}, },
onFileUploadComplete: function (file) { onFileUploadComplete: function (file, req, res) {
console.log(file.fieldname + ' uploaded to ' + file.path); console.log('\n\nheadersSent in onFileUploadComplete: ', res.headersSent);
// done=true; // console.log(req.files.file[0]);
try{
formCtrl.uploadPDF(req.files, function(_file){
console.log(_file.filename + ' uploaded to ' + _file.path);
res.status(200).send(_file);
});
}catch(err) {
res.status(500).send({
message: err.message
});
}
} }
})); }));

View file

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

View file

@ -1,13 +1,41 @@
'use strict'; 'use strict';
angular.module('core').controller('HeaderController', ['$rootScope','$scope','Menus', '$state', angular.module('core').controller('HeaderController', ['$rootScope','$scope','Menus', '$state', 'Auth', 'User',
function($rootScope, $scope, Menus, $state) { function($rootScope, $scope, Menus, $state, Auth, User) {
// $rootScope.authentication = Auth; $scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User);
// $rootScope.user = {}, $scope.authentication = $rootScope.authentication = Auth;
console.log('isAuthenticated(): '+$scope.authentication.isAuthenticated());
$scope.isCollapsed = false; $scope.isCollapsed = false;
$scope.hideNav = false; $scope.hideNav = false;
$scope.menu = Menus.getMenu('topbar'); $scope.menu = Menus.getMenu('topbar');
$scope.signout = function() {
User.logout(function() {
Auth.logout();
$rootScope.user = null;
$state.go('home');
});
};
$scope.toggleCollapsibleMenu = function() {
$scope.isCollapsed = !$scope.isCollapsed;
};
// 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){ // Principal.identity().then(function(user){
// $rootScope.user = user; // $rootScope.user = user;
// console.log('topbar') // console.log('topbar')
@ -39,21 +67,6 @@ angular.module('core').controller('HeaderController', ['$rootScope','$scope','Me
// }; // };
$scope.toggleCollapsibleMenu = function() {
$scope.isCollapsed = !$scope.isCollapsed;
};
// 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;
}
}
});
// }); // });
} }

View file

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

View file

@ -1,73 +1,25 @@
'use strict'; // 'use strict';
/** // /**
* @ngdoc function // * @ngdoc function
* @name medform.controller:IndexCtrl // * @name medform.controller:IndexCtrl
* @description // * @description
* # IndexCtrl // * # IndexCtrl
* Controller of core // * Controller of core
*/ // */
angular.module('medform').controller('IndexCtrl', function ($scope, $rootScope, $location, User, Auth, $state) { // angular.module('medform').controller('IndexCtrl', function ($scope, $rootScope, $location, User, Auth, $state) {
$rootScope.user = Auth.ensureHasCurrentUser(User); // $rootScope.user = Auth.ensureHasCurrentUser(User);
// $rootScope.user = Auth.getUserState(User).user; // // $rootScope.user = Auth.getUserState(User).user;
$rootScope.authorization = Auth; // $rootScope.authentication = Auth;
// $scope.signout = function() {
// User.logout(function() {
// Auth.logout();
// $rootScope.user = null;
// $state.go('home');
// // $scope.$apply();
// });
// };
$scope.signin = function() { // });
Auth.currentUser = User.login($scope.credentials,
function(response) {
// console.log(response);
// Auth.currentUser = $rootScope.loginResult.user;
Auth.login();
$rootScope.user = Auth.ensureHasCurrentUser(User);
// console.log( $rootScope.loginResult.user);
$location.path('listForms');
},
function(res) {
$scope.loginError = res.data.error;
console.log('loginError: '+res.data.error);
$rootScope.user = Auth.ensureHasCurrentUser(User);
// if(!$scope.loginError){
// Auth.currentUser = rootScope.loginResult.user;
// console.log(Auth.currentUser );
// }
// Auth.currentUser = $rootScope.loginResult.user;
}
);
console.log(Auth.currentUser);
// Auth.currentUser = $rootScope.loginResult;
};
$scope.signup = function() {
$scope.user = User.save($scope.registration,
function() {
},
function(res) {
if(res && res.data) {
$scope.registerError = res.data.error;
}else {
console.log('No response received');
}
}
);
};
$scope.signout = function() {
User.logout(function() {
Auth.logout();
$rootScope.user = null;
$state.go('home');
// $scope.$apply();
});
};
});

View file

@ -7,9 +7,12 @@
.navbar .navbar-brand span { .navbar .navbar-brand span {
text-decoration: underline; text-decoration: underline;
} }
.nav.navbar-nav.navbar-right li {
padding-right: 20px;
}
.content { .content {
/*margin-top: 50px;*/ margin-top: 100px;
} }
.undecorated-link:hover { .undecorated-link:hover {
text-decoration: none; text-decoration: none;

View file

@ -13,7 +13,7 @@
</a> </a>
</div> </div>
<nav class="collapse navbar-collapse" collapse="!isCollapsed" role="navigation"> <nav class="collapse navbar-collapse" collapse="!isCollapsed" role="navigation">
<ul class="nav navbar-nav" data-ng-if="menu.shouldRender(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'"> <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> <a ng-switch-when="dropdown" class="dropdown-toggle" dropdown-toggle>
<span data-ng-bind="item.title"></span> <span data-ng-bind="item.title"></span>

View file

@ -18,91 +18,9 @@
</a> </a>
</div> </div>
<div class="row" data-ng-if="authentication.isAuthenticated()">
<p class="lead">
Hi there {{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>
</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>Enjoy &amp; Keep Us Updated,
<br>The MedForms Team. <br>The MedForms Team.
</section> </section>

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
angular.module('forms').controller('EditFormController', ['$scope', '$state', 'Upload', '$stateParams', 'FormFields', 'Forms', 'CurrentForm', '$modal', '$location', angular.module('forms').controller('EditFormController', ['$scope', '$rootScope', '$state', 'Upload', '$stateParams', 'FormFields', 'Forms', 'CurrentForm', '$modal', '$location',
function ($scope, $state, Upload, $stateParams, FormFields, Forms, CurrentForm, $modal, $location) { function ($scope, $state, $rootScope, Upload, $stateParams, FormFields, Forms, CurrentForm, $modal, $location) {
// Principal.identity().then(function(user){ // Principal.identity().then(function(user){
// $scope.authentication.user = user; // $scope.authentication.user = user;
// }).then(function(){ // }).then(function(){
@ -9,6 +9,8 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
// console.log('isAuthenticated(): '+Principal.isAuthenticated());\ // console.log('isAuthenticated(): '+Principal.isAuthenticated());\
$scope.isNewForm = false; $scope.isNewForm = false;
$scope.pdfLoading = false;
var _current_upload = null;
$scope.log = ''; $scope.log = '';
// Get current form if it exists, or create new one // Get current form if it exists, or create new one
@ -28,46 +30,52 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
} }
//PDF Functions //PDF Functions
$scope.cancelUpload = function(){ $scope.cancelUpload = function(){
//TBD _current_upload.abort();
$scope.pdfLoading = false;
}; };
$scope.removePDF = function(){ $scope.removePDF = function(){
$scope.form.pdf = null; $scope.form.pdf = null;
$scope.isGenerated = false;
$scope.autofillPDFs = false;
console.log('form.pdf exists: '+!!$scope.form.pdf); console.log('form.pdf: '+$scope.form.pdf+' REMOVED');
}; };
$scope.uploadPDF = function(files) { $scope.uploadPDF = function(files) {
if (files && files.length) { if (files && files.length) {
for (var i = 0; i < files.length; i++) { // for (var i = 0; i < files.length; i++) {
var file = files[i]; var file = files[0];
Upload.upload({ _current_upload = Upload.upload({
url: '/upload/pdf', url: '/upload/pdf',
fields: { fields: {
'user': $scope.form.admin, 'user': $scope.user,
'form': $scope.form 'form': $scope.form
}, },
file: file file: file
}).progress(function (evt) { }).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$scope.log = 'progress: ' + progressPercentage + '% ' + $scope.log = 'progress: ' + progressPercentage + '% ' +
evt.config.file.name + '\n' + $scope.log; evt.config.file.name + '\n' + $scope.log;
}).success(function (data, status, headers, config) { $scope.pdfLoading = true;
$scope.log = 'file ' + data.originalname + 'uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log; }).success(function (data, status, headers, config) {
$scope.pdf = data; $scope.log = 'file ' + data.originalname + 'uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log;
$scope.form.pdf = data; $scope.form.pdf = data;
$scope.pdfLoading = false;
if(!$scope.$$phase) { console.log($scope.log);
$scope.$apply(); console.log('$scope.pdf: '+$scope.form.pdf.name);
} if(!$scope.$$phase) {
$scope.$apply();
console.log($scope.log); }
console.log('$scope.pdf: '+$scope.pdf.name); }).error(function(err){
}); $scope.pdfLoading = false;
} console.log('Error occured during upload.\n');
console.log(err);
});
// }
} }
}; };
@ -82,7 +90,6 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
// Create new Form object // Create new Form object
var form = new Forms($scope.form); var form = new Forms($scope.form);
form.$save(function(response) { form.$save(function(response) {
console.log('form created'); console.log('form created');
@ -92,7 +99,8 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
$scope.form = {}; $scope.form = {};
// Redirect after save // Redirect after save
$location.path('forms/' + response._id + '/admin'); $scope.goToWithId('viewForm', response._id);
// $location.path('forms/' + response._id + '/admin');
}, function(errorResponse) { }, function(errorResponse) {
console.log(errorResponse.data.message); console.log(errorResponse.data.message);

View file

@ -10,7 +10,7 @@
.form-item.row.create-new { .form-item.row.create-new {
border-bottom: 4px inset #ccc; border-bottom: 4px inset #ccc;
background-color: rgb(51,51,51); background-color: rgb(131,131,131);
color: white; color: white;
} }

View file

@ -133,7 +133,7 @@
Delete Delete
</button> </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> <i class="glyphicon glyphicon-ban-circle"></i>
Cancel Cancel
</button> </button>

View file

@ -6,11 +6,17 @@ angular.module('users').config(['$httpProvider',
$httpProvider.interceptors.push(function($q, $location) { $httpProvider.interceptors.push(function($q, $location) {
return { return {
responseError: function(response) { responseError: function(response) {
console.log('intercepted rejection of ', response.config.url, response.status); if( $location.path() !== '/users/me' ){
if (response.status === 401 || response.status === 403) {
// save the current location so that login can redirect back console.log('intercepted rejection of ', response.config.url, response.status);
$location.nextAfterLogin = $location.path(); if (response.status === 401) {
$location.path('/login'); // 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); return $q.reject(response);
} }

View file

@ -1,63 +1,115 @@
// 'use strict'; 'use strict';
// angular.module('users').controller('AuthenticationController', ['$scope', '$location', '$state', angular.module('users').controller('AuthenticationController', ['$scope', '$location', '$state', '$rootScope', 'User', 'Auth',
// function($scope, $location, $state) { function($scope, $location, $state, $rootScope, User, Auth) {
// // $scope.authentication = Principal; $scope = $rootScope;
$scope.credentials = {};
// // If user is signed in then redirect back home // $scope.authentication = Principal;
// if ($scope.authentication.isAuthenticated()) $state.go('home');
// $scope.signup = function() { // If user is signed in then redirect back home
// Principal.signup($scope.credentials).then( if ($scope.authentication.isAuthenticated()) $state.go('home');
// 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 $scope.signin = function() {
// // $location.path('/'); // console.log("signin");
// // }).error(function(response) { // console.log($scope.credentials);
// // $scope.error = response.message; Auth.currentUser = User.login($scope.credentials).then(
// // }); function(response) {
// }; Auth.login();
$rootScope.user = Auth.ensureHasCurrentUser(User);
$scope = $rootScope;
// $scope.signin = function() { if($state.previous !== 'home'){
// console.log('signin'); $state.go($state.previous);
}else{
$state.go('home');
}
},
function(error) {
$scope.error = error;
console.log('loginError: '+error);
$rootScope.user = Auth.ensureHasCurrentUser(User);
$scope = $rootScope;
// if(!$scope.loginError){
// Auth.currentUser = rootScope.loginResult.user;
// console.log(Auth.currentUser );
// }
// Principal.signin($scope.credentials).then( // Auth.currentUser = $rootScope.loginResult.user;
// 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 $scope.signup = function() {
// // $location.path('/'); $scope.user = User.save($scope.registration,
// // }).error(function(response) { function() {
// // Principal.authenticate(null); $state.go('signup-success');
// // $scope.error = response.message; },
// // }); function(error) {
// }; if(error) {
// } $scope.error = error;
// ]); }else {
console.log('No response received');
}
}
);
};
// $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,12 +1,10 @@
'use strict'; 'use strict';
angular.module('users') angular.module('users')
.factory('Auth', function() { .factory('Auth', function($window) {
var userState = var userState =
{ {
// isLoggedIn: $cookies.get('isLoggedIn')
isLoggedIn: false isLoggedIn: false
// user: null
}; };
return { return {
@ -16,39 +14,52 @@ angular.module('users')
// because that would create a circular dependency // because that would create a circular dependency
// Auth <- $http <- $resource <- LoopBackResource <- User <- Auth // Auth <- $http <- $resource <- LoopBackResource <- User <- Auth
ensureHasCurrentUser: function(User) { ensureHasCurrentUser: function(User) {
if (this.currentUser) { if (this.currentUser && this.currentUser.displayName) {
console.log('Using cached current user.'); console.log('Using local current user.');
console.log(this.currentUser); console.log(this.currentUser);
return this.currentUser; return this.currentUser;
} else{ }
else if ($window.user){
console.log('Using cached current user.');
console.log($window.user);
this.currentUser = $window.user;
return this.currentUser;
}
else{
console.log('Fetching current user from the server.'); console.log('Fetching current user from the server.');
this.currentUser = User.getCurrent(function() { User.getCurrent().then(function(user) {
// success // success
this.currentUser = user;
userState.isLoggedIn = true; userState.isLoggedIn = true;
// $cookies.put('isLoggedIn', 'true'); $window.user = this.currentUser;
return this.currentUser; return this.currentUser;
}, },
function(response) { function(response) {
userState.isLoggedIn = false; userState.isLoggedIn = false;
// $cookies.put('isLoggedIn', 'false'); this.currentUser = null;
$window.user = null;
console.log('User.getCurrent() err', response); console.log('User.getCurrent() err', response);
return null; return null;
}); });
} }
}, },
getUserState: function(user) { isAuthenticated: function() {
// userState.user = ensureHasCurrentUser(user); return !!this.currentUser;
},
getUserState: function() {
return userState; return userState;
}, },
login: function(user) { login: function() {
// userState.isLoggedIn = true; userState.isLoggedIn = true;
// $cookies.put('isLoggedIn', 'true');
this.ensureHasCurrentUser(user);
}, },
logout: function() { logout: function() {
$window.user = null;
userState.isLoggedIn = false;
this.currentUser = null;
this.ensureHasCurrentUser(null); this.ensureHasCurrentUser(null);
}, },
}; };

View file

@ -13,7 +13,7 @@ angular.module('users').factory('User', ['$window', '$q', '$timeout', '$http', '
deferred.resolve(response); deferred.resolve(response);
}) })
.error(function() { .error(function() {
deferred.reject("User's session has expired"); deferred.reject('User\'s session has expired');
}); });
return deferred.promise; return deferred.promise;
@ -22,7 +22,7 @@ angular.module('users').factory('User', ['$window', '$q', '$timeout', '$http', '
var deferred = $q.defer(); var deferred = $q.defer();
$http.post('/auth/signin', credentials).success(function(response) { $http.post('/auth/signin', credentials).success(function(response) {
console.log(response); // console.log(response);
deferred.resolve(response); deferred.resolve(response);
}).error(function(error) { }).error(function(error) {

View file

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