How do I get the authCheck factory to fire before the "Check Login state of user" function?
I'm trying to check the state of the $rootScope
on routing and http requests:
//Global Logout Function
myApp.run(function($rootScope, $http) {
$rootScope.logout = function() {
$http.post('/api/auth/logout');
};
});
//Check Login state of user
myApp.run(function($rootScope, $http, $window) {
$rootScope.$on('$routeChangeStart', function () {
$http.get('/api/auth')
.then(function successCallback(response) {
$rootScope.logStatus = response.data.data.loggedIn;
console.log('initial ' + $rootScope.logStatus);
}, function errorCallback(response) {
$rootScope.logStatus = response.data.data.loggedIn;
});
return $rootScope.logStatus;
});
});
//Check for authenticated users on http requests (API calls and Routing changes) and redirect to login if logged out
myBirkman.factory('authCheck', ['$rootScope','$window', function($rootScope, $window) {
var authCheck = {
'request': function(config) {
if ($rootScope.logStatus == true) {
//do nothing
console.log('redirect ' + $rootScope.logStatus);
} else if ($rootScope.logStatus == false) {
$window.location.href = '/login.php';
}
},
'response': function(response) {
return response;
}
};
return authCheck;
}]);
// Define routing within the app
myApp.config(['$httpProvider', '$routeProvider', function($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('authCheck');
I've tried to convert the $rootScope element to a constant, but the same issue is cropping up. The factory runs before the run function so the constant isn't updated until after the factory runs.