angular js returning user autologin

2019-06-14 14:52发布

问题:

I have an authentication system via tokens. The user logs in with email and password and the token is returned and saved in a cookie. Now if the user closes the browser or tab and returns to the site, then the user is authenticated with the token in the cookie, however, that can take a quite a few milliseconds and if they return to a secure site such as their user profile, and the app is not fast enough to load the initial user data and marks them as logged in, then they are redirected to the login page.

My first idea was just to put the user data in the response for every request, where the token is valid, but that would create lots of unnecessary data traffic.

Is there a better solution?

回答1:

Use resolves on routes to wait till user info is loaded. So whether to redirect to log in page or allow the route access depends on handler of your load user handler. For example:

function requiresLogin(){
return ["$auth",function($auth){
return $auth.verifiedUser();
}];
}

$routeProvider.when("...",{
....,
resolve:{
user:requiresLogin()
}
});

In your $auth service:

angular.module("app").factory("$auth", ["$q", "$http", function($q,$http){
var loaded, loggedIn = false;

//load user 
loaded = $http.get(....).then(function(result){
loggedIn = result.loggedIn;
});

return {
verifiedUser:function(){
return loaded.then(function(){
    if(loggedIn)
return true;
else
return $q.reject();
});
}
};
}]);

Untested code, just to give an idea on how to go about this.

We can not provide an explicit answer with out more code.