Skip to content

Commit

Permalink
feat(auth): improve auth service and route protection
Browse files Browse the repository at this point in the history
  • Loading branch information
balthazar committed May 1, 2015
1 parent bc6b532 commit 8dfb37c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
10 changes: 9 additions & 1 deletion app/templates/client/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,16 @@ angular.module('<%= appname %>', [
};
})

.run(function ($rootScope, Auth) {
.run(function ($rootScope, $location, Auth) {

$rootScope.Auth = Auth;

$rootScope.$on('$routeChangeStart', function (event, next) {
Auth.isReadyLogged().catch(function () {
if (next.authenticate) {
$location.path('/');
}
});
});

})<% } %>;
28 changes: 24 additions & 4 deletions app/templates/client/services/auth(auth)/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@ angular.module('<%= appname %>')
.service('Auth', function ($rootScope, $cookieStore, $q, $http) {

var _user = {};
var _ready = $q.defer();

if ($cookieStore.get('token')) {
$http.get('/api/users/me')
.then(function (res) {
_user = res.data;
})
.catch(function (err) {
console.log(err);
.finally(function (err) {
_ready.resolve();
});
} else {
_ready.resolve();
}

/**
Expand Down Expand Up @@ -64,12 +67,29 @@ angular.module('<%= appname %>')
};

/**
* Check if user is logged
* Check if the user is logged
*
* @returns {boolean}
*/
this.isLogged = function () {
return _user.hasOwnProperty('email');
return _user.hasOwnProperty('_id');
};

/**
* Check if the user is logged after the ready state
*
* @returns {Promise}
*/
this.isReadyLogged = function () {
var def = $q.defer();
_ready.promise.then(function () {
if (_user.hasOwnProperty('_id')) {
def.resolve();
} else {
def.reject();
}
});
return def.promise;
};

/**
Expand Down

0 comments on commit 8dfb37c

Please sign in to comment.