angular js returning user autologin

只愿长相守 提交于 2019-12-08 12:20:41

问题


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.



来源:https://stackoverflow.com/questions/22732170/angular-js-returning-user-autologin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!