问题描述
我最初尝试解决的问题是,如果用户未登录,则将用户重定向到登录页面,反之亦然.
The problem I was initially trying to solve was to redirect a user to the login page if they are not logged in and vice versa.
我用下面的代码做到了这一点
I did this with the following code
.run(function($rootScope, $http, AppService, $state) {
$rootScope.$on('application:refreshtoken', function(rootScope, token) {
if(token) {
$http.defaults.headers.common['X-Auth-Token'] = token;
AppService.setAuthToken(token);
AppService.resetLoginTimeout();
}
});
$rootScope.$on('$stateChangeSuccess', function() {
$http.get('/api/heartbeat');
});
// This is the really pertinent bit...
$rootScope.$on('$stateChangeStart', function(e, toState) {
if(toState.name === 'login') {
if(AppService.getIsLoggedIn()) {
e.preventDefault();
$state.go(AppService.getRedirectPage());
}
} else {
if(!AppService.getIsLoggedIn()) {
e.preventDefault();
$state.go('login');
}
}
});
});
应用服务
.factory('AppService', ['$rootScope', 'locker', '$http', '$state',
function ($rootScope, locker, $http, $state) {
var _isLoggedIn = locker.get('loggedIn', false),
_authToken = locker.get('authtoken', null),
_roles = locker.get('roles', null),
_permissions = locker.get('permissions', null),
_user = locker.get('user', null),
_userid = locker.get('userid', null),
_userprefs = locker.get('userprefs', null),
_timedout,
_timeoutId,
service = {};
if (_authToken) {
$http.defaults.headers.common['X-Auth-Token'] = _authToken;
}
service.setIsLoggedIn = function (isLoggedIn) {
_isLoggedIn = isLoggedIn;
this.doLogin();
broadcastLogin();
};
service.doLogin = function () {
if (_isLoggedIn) {
locker.put({
loggedIn: _isLoggedIn,
authtoken: _authToken,
roles: _roles,
permissions: _permissions,
user: _user,
userprefs: _userprefs
});
}
};
service.doLogout = function (cb) {
_isLoggedIn = false;
_authToken = null;
_roles = null;
_permissions = null;
_user = null;
_userid = null;
_userprefs = null;
delete $http.defaults.headers.common['X-Auth-Token'];
locker.clean();
cb();
};
service.getIsLoggedIn = function () {
return _isLoggedIn;
};
service.setAuthToken = function (authToken) {
_authToken = authToken;
locker.put({
authtoken: _authToken
});
};
service.getAuthToken = function () {
return _authToken;
};
service.setUserid = function (userid) {
locker.put('userid', userid);
_userid = userid;
};
service.getUserid = function () {
return _userid;
};
service.setUser = function (user) {
_user = user;
};
service.getUser = function () {
return _user;
};
service.setRoles = function (roles) {
_roles = roles;
};
service.getRoles = function () {
return _roles;
};
service.setPermissions = function (permissions) {
_permissions = permissions;
};
service.getPermissions = function () {
return _permissions;
};
service.setUserPreferences = function (prefs) {
_userprefs = prefs;
};
service.getUserPreferences = function () {
return _userprefs;
};
service.resetLoginTimeout = function () {
if (_timeoutId) {
clearTimeout(_timeoutId);
}
_timeoutId = setTimeout(function () {
$rootScope.$broadcast('application:logintimeoutwarn');
}, 1000 * 60 * 4);
};
service.setTimedOut = function (timedout) {
_timedout = timedout;
};
service.getTimedOut = function () {
return _timedout;
};
service.extendSession = function () {
$http.get('/api/heartbeat');
};
service.goDefaultUserPage = function () {
var success = false;
if (_userprefs.landingPage) {
$state.go(_userprefs.landingPage);
success = true;
} else {
var permissionRoutes = {
'regimens': 'regimens.do',
'pathways': 'pathways',
'manage.users': 'manageusers.do',
'manage.practices': 'managepractices.do',
'patients': 'patients'
};
_.some(_permissions, function (el) {
var state = $state.get(permissionRoutes[el]);
if (!state.abstract) {
$state.go(state.name);
success = true;
return true;
}
});
}
return success;
};
service.getRedirectPage = function () {
var page = false;
if (_userprefs.landingPage) {
page = _userprefs.landingPage;
} else {
var permissionRoutes = {
'regimens': 'regimens.do',
'pathways': 'pathways',
'manage.users': 'manageusers.do',
'manage.practices': 'managepractices.do',
'patients': 'patients'
};
_.some(_permissions, function (el) {
var state = $state.get(permissionRoutes[el]);
if (!state.abstract) {
page = state.name;
return true;
}
});
}
return page;
};
function broadcastLogin() {
$rootScope.$broadcast('application:loggedinstatus');
}
broadcastLogin();
return service;
}
])
此代码运行良好,直到我采取一组非常具体的操作:
This code works great until I take a very specific set of actions:
- 登录
- 关闭打开的标签页或窗口
- 打开一个新标签并转到应用程序
因为我仍然登录到应用程序,所以我有一个用户对象和一个有效的令牌,但我收到 error:infdig Infinite $digest Loop
.它最终会解决并进入正确的状态,但需要一段时间并且路径闪烁(如果需要,我可以发布视频).
Since I am still logged in to the application, I have a user object and a valid token, but I am getting error:infdig Infinite $digest Loop
. It eventually resolves and goes to the correct state, but it takes a while and the path flickers (I can post a video if needed).
我尝试在 $rootScope.$on('$stateChangeSuccess')
中使用 $location.path
而不是 $state.go
回调,但问题仍然存在.
I tried using $location.path
instead of $state.go
in the $rootScope.$on('$stateChangeSuccess')
callback, but the issue persists.
这并不会真正影响应用程序的功能,但是很烦人.我也不想将我的储物柜存储更改为会话存储,因为我希望用户在关闭选项卡并重新打开时保持登录状态.
This doesn't really affect the functioning of the application, but it is annoying. I also don't really want to change my locker storage to session storage because I want the user to stay logged in if they close the tab and reopen.
推荐答案
我想说,问题隐藏在 中不正确的
检查一下:if
语句中>$rootScope.$on('$stateChangeStart'...
I would say, that the issue is hidden in the improper if
statements inside of the $rootScope.$on('$stateChangeStart'...
Check this:
一般建议:
让我们重定向 ($state.go()) 仅在需要时 - 否则退出事件侦听器
$rootScope.$on('$stateChangeStart' ...
if (toState.name === 'login' ){
// going to login ... do not solve it at all
return;
}
第二次检查应该是:用户是否经过身份验证(并且不打算登录)?
Second check should be: is user authenticated (and NOT going to login)?
if(AppService.getIsLoggedIn()) {
// do not redirect, let him go... he is AUTHENTICATED
return;
}
现在我们有了状态,即未登录,未验证用户,我们可以明确调用:
Now we have state, which is not login, user is not authenticated, we can clearly call:
// this is a must - stop current flow
e.preventDefault();
$state.go('login'); // go to login
一切都会如我们所愿
非常详细的解释和工作示例也可以在这里找到...
Very detailed explanation and working example could be also found here...
这篇关于带有 ui-router 的 Angular 无限摘要循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!