Last active
April 8, 2016 07:37
-
-
Save pntrivedy/78cf1104206bda5cb39bbabc5cd0be43 to your computer and use it in GitHub Desktop.
Angular js state authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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