Within my application, I have an authService
that manages the isAuthenticated
flag when a user is logged in. Each time there is a route change, a listener is triggered by the $routeChangeStart
event to verify if the user is authenticated using authService.isAuthenticated()
. If not, the user should be redirected to the login route.
The issue arises when a user performs a page refresh and all the settings from authService
are cleared, leading them back to the login screen despite having a valid session on the server. This behavior is not desired.
My goal is to delay the route change until I can determine if the user is authenticated - either through immediate verification with authService
, or by retrieving the information from the server if it's not available in authService
(e.g. after a refresh). The authService
includes a function for this:
// returns promise
currentUser: function() {
if (authService.isAuthenticated()) {
return $q.when(authService.loggedUser);
}
return $http.get('/session').then(function(response) {
authService.loggedUser = response.user;
return $q.when(authService.loggedUser);
});
}
I intend to utilize this function within the event listener:
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if(isRouteRestricted(next)) {
authService.currentUser().then(null, function() {
$location.path('/login');
});
}
});
However, the implementation does not behave as expected. The target route is still briefly visible before the redirection occurs. I suspect this is related to the asynchronous nature of promises, but how can I prevent this "blink" effect?