Skip to content

Commit

Permalink
Merge pull request #148 from Tietokilta/fix/renewing-expired-tokens
Browse files Browse the repository at this point in the history
fix: improve expired token handling
  • Loading branch information
PurkkaKoodari authored Sep 17, 2024
2 parents 82cb977 + 79ae870 commit 599fed2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 16 deletions.
11 changes: 3 additions & 8 deletions packages/ilmomasiina-frontend/src/containers/requireAuth.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import React, { ComponentType, useEffect } from "react";

import { toast } from "react-toastify";

import { redirectToLogin } from "../modules/auth/actions";
import { loginExpired, redirectToLogin } from "../modules/auth/actions";
import { useTypedDispatch, useTypedSelector } from "../store/reducers";

export default function requireAuth<P extends {}>(WrappedComponent: ComponentType<P>) {
Expand All @@ -16,11 +14,8 @@ export default function requireAuth<P extends {}>(WrappedComponent: ComponentTyp

useEffect(() => {
if (expired) {
toast.error("Sisäänkirjautumisesi on vanhentunut. Kirjaudu sisään uudelleen.", {
autoClose: 10000,
});
}
if (needLogin) {
dispatch(loginExpired());
} else if (needLogin) {
dispatch(redirectToLogin());
}
}, [needLogin, expired, dispatch]);
Expand Down
13 changes: 5 additions & 8 deletions packages/ilmomasiina-frontend/src/modules/auth/actions.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { push } from "connected-react-router";
import { toast } from "react-toastify";

import { ApiError, apiFetch } from "@tietokilta/ilmomasiina-components";
import { AdminLoginResponse, ErrorCode } from "@tietokilta/ilmomasiina-models";
import { apiFetch } from "@tietokilta/ilmomasiina-components";
import { AdminLoginResponse } from "@tietokilta/ilmomasiina-models";
import i18n from "../../i18n";
import appPaths from "../../paths";
import type { DispatchAction, GetState } from "../../store/types";
Expand Down Expand Up @@ -87,7 +87,8 @@ const RENEW_LOGIN_THRESHOLD = 5 * 60 * 1000;

export const renewLogin = () => async (dispatch: DispatchAction, getState: GetState) => {
const { accessToken } = getState().auth;
if (!accessToken || Date.now() < accessToken.expiresAt - RENEW_LOGIN_THRESHOLD) return;
if (!accessToken || Date.now() < accessToken.expiresAt - RENEW_LOGIN_THRESHOLD || Date.now() > accessToken.expiresAt)
return;

try {
if (accessToken) {
Expand All @@ -101,10 +102,6 @@ export const renewLogin = () => async (dispatch: DispatchAction, getState: GetSt
}
}
} catch (err) {
if (err instanceof ApiError && err.code === ErrorCode.BAD_SESSION) {
dispatch(loginExpired());
} else {
throw err;
}
// Ignore errors from login renewal - loginExpired() will trigger via requireAuth.
}
};

0 comments on commit 599fed2

Please sign in to comment.