Skip to content

Instantly share code, notes, and snippets.

@pntrivedy
Last active April 8, 2016 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pntrivedy/78cf1104206bda5cb39bbabc5cd0be43 to your computer and use it in GitHub Desktop.
Save pntrivedy/78cf1104206bda5cb39bbabc5cd0be43 to your computer and use it in GitHub Desktop.
Angular js state authentication
//config.js
for every state you want to check if user has logged in or not set requireLogin to true.
...,
data : {
requireLogin : true
},
.....
// app.js
app.run(function ($rootScope) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
if (requireLogin && typeof $rootScope.currentUser === 'undefined') {
console.log('login required');
event.preventDefault();
}
});
});
// services.js
.service('Auth', function ($modal, $rootScope) {
function assignCurrentUser (user) {
$rootScope.currentUser = user;
return user;
}
return function() {
var instance = $modal.open({
templateUrl: 'views/loginModalTemplate.html',
controller: 'LoginModalCtrl',
controllerAs: 'LoginModalCtrl'
})
return instance.result.then(assignCurrentUser);
};
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment