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'),
fs = require('fs-extra'),
async = require('async'),
path = require('path'),
_ = require('lodash');
/**
@ -38,39 +39,53 @@ exports.create = function(req, res) {
/**
* Upload PDF
*/
exports.uploadPDF = function(req, res) {
var parser = new PDFParser(),
pdfFile = req.files.file;
var upload_count = 0;
exports.uploadPDF = function(files, user, cb) {
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) {
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) {
//If file exists move to user's tmp directory
if(exists) {
// console.log('UPLOADING FILE \N\N');
return res.status(200).send({
message: 'Got your file!'
});
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 "' + 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 {
return res.status(400).send({
message: 'Did NOT get your file!'
});
throw new Error('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);
app.route('/forms')
.get(users.requiresLogin, forms.hasAuthorization, forms.list)
.get(users.requiresLogin, forms.list)
.post(users.requiresLogin, forms.create);
app.route('/forms/:formId/submissions')

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

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

View file

@ -96,33 +96,28 @@ 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) {
console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path);
// done=true;
onFileUploadComplete: function (file, req, res) {
console.log('\n\nheadersSent in onFileUploadComplete: ', res.headersSent);
// 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('!');
}
]);
angular.module(ApplicationConfiguration.applicationModuleName).run(['$rootScope',
function($rootScope) {
$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

@ -1,13 +1,41 @@
'use strict';
angular.module('core').controller('HeaderController', ['$rootScope','$scope','Menus', '$state',
function($rootScope, $scope, Menus, $state) {
// $rootScope.authentication = Auth;
// $rootScope.user = {},
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');
$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){
// $rootScope.user = user;
// 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';
angular.module('core').controller('HomeController', ['$rootScope', '$scope',
function($rootScope, $scope) {
// This provides Principal context.
// $scope.authentication = Principal;
// $scope.user = {};
angular.module('core').controller('HomeController', ['$rootScope', '$scope', 'User', 'Auth', '$state',
function($rootScope, $scope, User, Auth, $state) {
$scope = $rootScope;
// $rootScope.user = $window.user;
console.log($rootScope.user);
$scope.user = Auth.ensureHasCurrentUser(User);
$scope.authentication = Auth;
// Principal.identity().then(function(user){
// console.log(user);
// $scope.user = user;
// }, function(){
// console.log('error');
// });
// console.log("user.displayName: "+Principal.user()._id);
if($scope.authentication.isAuthenticated()){
$state.go('listForms');
}
}
]);

View file

@ -1,73 +1,25 @@
'use strict';
// '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.authorization = Auth;
// /**
// * @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();
// });
// };
$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 {
text-decoration: underline;
}
.nav.navbar-nav.navbar-right li {
padding-right: 20px;
}
.content {
/*margin-top: 50px;*/
margin-top: 100px;
}
.undecorated-link:hover {
text-decoration: none;

View file

@ -13,7 +13,7 @@
</a>
</div>
<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'">
<a ng-switch-when="dropdown" class="dropdown-toggle" dropdown-toggle>
<span data-ng-bind="item.title"></span>

View file

@ -18,91 +18,9 @@
</a>
</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>
<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,7 +1,7 @@
'use strict';
angular.module('forms').controller('EditFormController', ['$scope', '$state', 'Upload', '$stateParams', 'FormFields', 'Forms', 'CurrentForm', '$modal', '$location',
function ($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, $rootScope, Upload, $stateParams, FormFields, Forms, CurrentForm, $modal, $location) {
// Principal.identity().then(function(user){
// $scope.authentication.user = user;
// }).then(function(){
@ -9,6 +9,8 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
// console.log('isAuthenticated(): '+Principal.isAuthenticated());\
$scope.isNewForm = false;
$scope.pdfLoading = false;
var _current_upload = null;
$scope.log = '';
// Get current form if it exists, or create new one
@ -28,46 +30,52 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
}
//PDF Functions
$scope.cancelUpload = function(){
//TBD
_current_upload.abort();
$scope.pdfLoading = false;
};
$scope.removePDF = function(){
$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) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
Upload.upload({
url: '/upload/pdf',
fields: {
'user': $scope.form.admin,
'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;
}).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;
// 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;
if(!$scope.$$phase) {
$scope.$apply();
}
console.log($scope.log);
console.log('$scope.pdf: '+$scope.pdf.name);
});
}
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);
});
// }
}
};
@ -82,7 +90,6 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
// Create new Form object
var form = new Forms($scope.form);
form.$save(function(response) {
console.log('form created');
@ -92,7 +99,8 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', 'U
$scope.form = {};
// Redirect after save
$location.path('forms/' + response._id + '/admin');
$scope.goToWithId('viewForm', response._id);
// $location.path('forms/' + response._id + '/admin');
}, function(errorResponse) {
console.log(errorResponse.data.message);

View file

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

View file

@ -133,7 +133,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>

View file

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

View file

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

View file

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

View file

@ -19,8 +19,11 @@
</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-3 col-md-6">
<form class="signin form-horizontal" ng-submit="signin()" autocomplete="off">
<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>