检查令牌过期并注销用户

Checking token expiration and log user out

我想根据令牌到期将用户注销。我知道 Axios 调用有问题,但我不确定哪里出了问题。此外,它似乎可以手动注销用户,但它仍然会遇到错误。

actions.js:

export const logoutUser = (history) => ({
  type: LOGOUT_USER,
  payload: { history },
});

store.js:

export const checkTokenExpiration = (next) => (action) => {
  const token =
    JSON.parse(localStorage.getItem('user')) &&
    // eslint-disable-next-line dot-notation
    JSON.parse(localStorage.getItem('user'))['token'];
  if (jwtDecode(token).exp < Date.now() / 1000) {
    next(action);
    localStorage.clear();
  }
  next(action);
};

const logoutAsync = async (history) => {
  await axios
    .logoutUser()
    .checkTokenExpiration.then((user) => user)
    .catch((error) => error);
  console.log();
  history.push(adminRoot);
};

这是错误信息:

axios__WEBPACK_IMPORTED_MODULE_3___default.a.logoutUser is not a function

The above error occurred in task logout created by takeEvery(LOGOUT_USER, logout) created by watchLogoutUser created by rootSaga created by rootSaga

原来是我查错地方了

在一些帮助下发现我可以在另一个函数下检查,代码如下:

const ProtectedRoute = ({
  component: Component,
  roles = undefined,
  ...rest
}) => {
  function isAuthActive() {
    const user = JSON.parse(localStorage.getItem('User'));
    const expiryTime = new Date(user?.expiration * 1000).toLocaleString(
      'en-sg'
    );
    const currentTime = new Date().toLocaleString('en-sg');
    if (expiryTime < currentTime) {
      setCurrentUser();
      localStorage.clear();
      return <Redirect to="/login" />;
    }
    return true;
  }
};

基本上只是根据令牌给出的到期时间检查当前时间。其余设置在后台服务器