gpt4 book ai didi

javascript - Angular : Dealing with reload page and User Authentication

转载 作者:行者123 更新时间:2023-11-30 00:10:22 24 4
gpt4 key购买 nike

我一直在开发一个记录用户的应用程序。用户登录后,用户的信息将存储在服务中,cookie 将与身份验证 token 一起存储。像这样:

angular
.module('MyModule')
.service('AuthService', service);

service.$inject = ['$cookieStore', '$resource'];

function service($cookieStore, $resource){
var self = this,
user = null;

self.loginResource = $resource('my_path_to_login_resource');

self.login = login;
self.getUser = getUser;
self.reloadUser = reloadUser;


function login(_userCredentials){
var userResource = new self.loginResource(_userCredentials);
return userResource.$save()
.then(setUser);
}

function setUser(_userResponse){
user = _userResponse.toJSON();
}

function getUser(){
return user;
}

function reloadUser(_token){
return self.loginResource()
.get(_token)
.then(setUser);
}

}

当我需要处理应用程序的路由时使用 ui-router 我这样做: Angular .module('MyModule') .run(runFn);

  runFn.$inject = ['$state', '$rootScope', 'AuthService', '$cookieStore'];
function runFn($state, $rootScope, AuthService, $cookieStore) {

$rootScope.$on('$stateChangeSuccess', stateTransitioned);

function stateTransitioned(e, toState, toParams, fromState, fromParams) {
var pageRealoaded = fromState.name? false : true;
if(AuthService.getUser()){
//DEALING WITH STATES TRANSITIONS
}
else{
if($cookieStore.get('auth_token') && pageRealoaded){

//ENSURE THAT THE USER IS LOGGED WHEN THE STATE IS CHANGED
AuthService.reloadUser.then(function(){
$state.go(toState.name);
})
.catch($state.go.bind(null,'login'));


//I DON'T KNOW HOW AVOID THAT THE STATE IS LOADED UNTIL THE USER
//HAVE BEEN LOGGED
}
else{
$state.go('login');
}
}

}
}

当页面重新加载时,使用存储的 token ,我尝试等待该用户已登录,然后,如果成功,则重定向到状态 toState.name,如果错误,则重定向登录。我的问题:

<强>1。如何避免在用户登录之前加载状态?

<强>2。我处理这种情况的架构是否正确?有关更好结构的建议?

最佳答案

我建议您使用 ui-router 的解析功能来确保用户在进入某个状态之前始终经过身份验证。

请在此处查看 ui-router wiki: https://github.com/angular-ui/ui-router/wiki#resolve

像这样的东西应该在身份验证之前阻止状态进入。

.state('secure', {
resolve: {
user: function(AuthService, $state) {
// State will only be entered if this resolves.
return AuthService.resolveUser()
.catch(function(error) {
$state.go('login');
})
}
},
template: '<div>Secret Page</div>
})

我还把这支笔和一个工作示例放在一起: http://codepen.io/marcus-r/pen/eZKbYV?editors=1010

关于javascript - Angular : Dealing with reload page and User Authentication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36752802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com