My personally built AngularJs user authentication system is experiencing an unusual issue. While everything seems to be working fine - I can login, check access for specific pages, etc. - there is a strange behavior with the token authentication. It seems to only run properly on the second interaction with the WebApp.
For instance, if I modify some data in localStorage (where user data is stored) and then try to access an admin page, it allows me to enter. But during the next interaction, I suddenly get redirected back to the login process.
I'm puzzled by this situation. The code I am using is as follows:
app.js
function getUser() {
userinfo = JSON.parse(localStorageService.get("user")); //convert string to json
$scope.userData = userinfo; //Display purpose only;
};
function checkToken() {
var userCheckToken = JSON.parse(localStorageService.get("user"));
$http.post('dist/php/db.php?action=token', userCheckToken)
.success(function(res){
userToken = res;
}).error(function(err){
alert(feedbackError);
});
};
$rootScope.$on('$stateChangeStart', function(e, to) {
if (to.data && to.data.requireLogin) {
getUser();
checkToken();
if (!userinfo) {
e.preventDefault();
$state.go('login');
alert("You need to be logged in");
}
else if (userinfo && !userToken) {
e.preventDefault();
userInfo = false;
$state.go('login');
localStorageService.clearAll();
alert('Authentication failed');
}
}
});
The same issue also arises with individual functions. For example, when trying to execute an important function that requires admin privileges, the authentication process behaves similarly, failing on the first attempt.
Function:
$scope.debugTk = function() {
checkToken();
if (!userToken) {
alert('Authentication failed');
} else {
$http.get('dist/php/db.php?action=debugTk')
.success(function(res){
$scope.resultDebug = res;
}).error(function(err){
alert(feedbackError);
});
}
}