Skip to content

Instantly share code, notes, and snippets.

@bioball
Last active August 29, 2015 14:15
Show Gist options
  • Save bioball/29025680643786c4bd82 to your computer and use it in GitHub Desktop.
Save bioball/29025680643786c4bd82 to your computer and use it in GitHub Desktop.
Angular AUTH example
angular.module('app')
.factory('authentication', [
'user',
'$state',
function(user, $state){
return {
authenticate: function(protect){
return user.identify()
.then(function(){
return true;
})
.catch(function(){
if (protect){
$state.go('login');
}
return false;
});
}
};
}
]);
angular.module('app')
.controller('homeController', [
'isLoggedIn',
'user'
function(isLoggedIn, user){
// here, isLoggedIn is a boolean of whether the user is logged in or not.
}
])
angular.module('app')
.config([
'$stateProvider',
function($stateProvider){
$stateProvider
.state('home', {
url: '/',
controller: 'homeController',
// add this to any route that you'd like to protect.
resolve: {
isLoggedIn: [
'authentication',
function(authentication){
return authentication.authenticate();
}
]
}
})
.state('login', {
url: '/login'
})
}
])
angular.module('app')
.factory('user', [
'$http',
'$q',
function($http, $q){
var User = function(){
this.name = null;
};
User.prototype.isLoggedIn = function(){
// however this is done. You can a "loggedIn" variable in closure or something.
};
User.prototype.identify = function(){
if(this.isLoggedIn()){
return $q.when(true)
}
return $http.get("/auth", cookie) // this can be a cookie, or whatever token is used
};
return new User()
}
]);
@appmux
Copy link

appmux commented Feb 13, 2015

Check out the demo of ngAuth module see if you can make it work for what you need.

https://github.com/appmux/adhesive.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment