angular.module('authentication',[]) .service('AuthService',['$http','TokenStorage','$rootScope', function($http, TokenStorage, $rootScope) { var that = this; var authenticated = false; var userId = null; var username = {}; that.getAuthenticated = function () { if(TokenStorage.retrieve()!== null) return true; else return false; }; that.getUserId = function () { return userId; }; that.init = function () { return $http.get(urlBase +'user/current').success(function (user) { if(user.username !== 'anonymousUser'){ username = user.username; userId = user.id; communeId = user.communeId; authenticated = true; $rootScope.$broadcast('auth.loggedin'); } else { username = {}; userId = null; authenticated = false; communeId = null; TokenStorage.clear(); $rootScope.$broadcast('auth.loggedout'); } }); }; that.login = function (logdata) { return $http.post(urlBase +'login',logdata) .success(function (data, status, headers, config) { authenticated = true; $rootScope.$broadcast('auth.loggedin'); console.log(headers('X-AUTH-TOKEN')); TokenStorage.store(headers('X-AUTH-TOKEN')); }).error(function () { authenticated = false; userId = null; communeId = null; $rootScope.$broadcast('auth.loggedout'); }); }; that.logout = function () { TokenStorage.clear(); authenticated = false; userId = null; communeId = null; $rootScope.$broadcast('auth.loggedout'); }; }]) .factory('TokenStorage', function() { var storageKey = 'auth_token'; return { store : function(token) { return localStorage.setItem(storageKey, token); }, retrieve : function() { return localStorage.getItem(storageKey); }, clear : function() { return localStorage.removeItem(storageKey); } }; });