I have a AngularJs user authencation built by myself and its working. Everything is working fine. I can login, can check if user has access to a specific page, etc.. Except for the fact the token authentication i's running only on the second interaction i make with the WebApp.
For example, if I change some data on the localStorage (where i'm saving user data) and try to go the an admin page, for example, I'll be able to access that page, but on the next interaction, then I'll get kicked from the page and back to the login process.
What may be happening? This is the code I'm using:
app.js
function getUser() {
userinfo = JSON.parse(localStorageService.get("user")); //convert string to json
$scope.userData = userinfo; //Display purpouso 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 loggedin");
}
else if (userinfo && !userToken) {
e.preventDefault();
userInfo = false;
$state.go('login');
localStorageService.clearAll();
alert('Authentication failed');
}
}
});
Same thing happens to an individual function
. Let's say i have an important function on the page, so only an admin can execute that function. I'm also checking the authentication on that proccess, but it's happening the same thing, only on the second interaction.
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);
});
}
}