angular.module('hello', ['ngRoute']).config(function($routeProvider, $httpProvider) { $routeProvider.when('/', { templateUrl: 'home.html', controller: 'home', controllerAs: 'controller', resolve: { check:function(userService,$location){ if(userService.getUser()){ //check if the user has permission -- This happens before the page loads }else{ //redirect user to login if it does not have permission. $location.path('/login'); console.log("need be authentificate to acces to /"); } } } }).when('/login', { templateUrl: 'login.html', controller: 'navigation', controllerAs: 'controller' }).when('/user', { templateUrl: 'users.html', }).otherwise('/'); $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; }).factory("userService", function($rootScope) { return { getUser: function(){ console.log('in getUser: ' + $rootScope.authenticated); console.dir($rootScope); console.dir($rootScope.authenticated); console.log('in getUser2: ' + $rootScope.authenticated); if ($rootScope.authenticated == true) { return true; } else { return false; } } }; }).controller('navigation', function($rootScope, $http, $location, $route) { var self = this; self.tab = function(route) { return $route.current && route === $route.current.controller; }; var authenticate = function(credentials, callback) { var headers = credentials ? { authorization: "Basic " + btoa(credentials.username + ":" + credentials.password) } : {}; $http.get('user', { headers: headers }).success(function(data) { if (data.name) { $rootScope.authenticated = true; } else { $rootScope.authenticated = false; } callback && callback($rootScope.authenticated); }).error(function() { $rootScope.authenticated = false; callback && callback(false); }); } authenticate(); self.credentials = {}; self.login = function() { authenticate(self.credentials, function(authenticated) { if (authenticated) { console.log("Login succeeded") $location.path("/"); self.error = false; $rootScope.authenticated = true; } else { console.log("Login failed") $location.path("/login"); self.error = true; $rootScope.authenticated = false; } }) }; self.logout = function() { $http.post('logout', {}).finally(function() { $rootScope.authenticated = false; $location.path("/"); }); } }) .controller('home', function($http) { var self = this; $http.get('/resource/').success(function(data) { self.greeting = data; }) });