我想在AWS.config.credentials过期时刷新-仅在用户在页面上处于活动状态时刷新。
如果用户不活动超过30分钟,我将自动注销该用户。 如果用户在页面上处于活动状态,我想在后台刷新凭据,以便用户可以继续执行操作而不必再次登录。
我要做的是:用户登录后,会保存一个表明用户已登录的变量。我有一个函数一旦登录便会执行:
$scope.refreshSession = function() {
// Check if user variable is true (user is logged in)
if ($scope.getLoggedin() == "true") {
// Check if you need to refresh the session - function code below
checkRefresh();
// Set a timer that calls function Timedout() if the user was inactive for 30 minutes
var timeoutTime = 1800000; // Timeout time is 30 minutes
var timeoutTimer = setTimeout(Timedout, timeoutTime);
// Watch for mousedown and keydown actions
$('body').bind('mousedown keydown', function(event) {
// Cancel timer because person is active on page
clearTimeout(timeoutTimer);
// Check if you need to refresh the session - function code below
checkRefresh();
// Restart timer
timeoutTimer = setTimeout(Timedout, timeoutTime);
});
};
function Timedout() {
$('body').unbind('mousedown keydown');
if ($scope.getLoggedin() == "true") {
// Log user out (after 30 minutes of inactivity)
$scope.forcelogout();
}
};
};
这里是检查凭据是否需要刷新的功能:
function checkRefresh() {
var userPool = cognitoService.getUserPool();
var currentUser = userPool.getCurrentUser();
if (currentUser != null) {
currentUser.getSession(function(err, session) {
if (err) {
console.log(err);
}
var refresh_token = session.getRefreshToken();
console.log(AWS.config.credentials.needsRefresh());
if (AWS.config.credentials.needsRefresh()) {
currentUser.refreshSession(refresh_token, (err, session) => {
if (err) {
console.log(err);
}
AWS.config.credentials.refresh((err) => {
if (err) {
console.log(err);
} else {
console.log("TOKEN SUCCESSFULLY UPDATED");
AWSCognito.config.region = 'eu-west-1';
AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: ''
});
}
});
});
}
});
}
};
在此,我将在用户返回页面后立即检查是否需要刷新凭据:
window.addEventListener('focus', function() {
checkRefresh();
});
问题/问题
我遇到的问题是,刷新页面后console.log(AWS.config.credentials.needsRefresh());
每次都会显示true(而只有在需要刷新凭据的情况下才应该显示true,而每小时应该只刷新一次)。虽然,返回到页面时或捕获鼠标按下或击键动作时调用该函数时,它显示为false(按预期)。