Skip to content

Commit

Permalink
Update tokenMiddleware.js
Browse files Browse the repository at this point in the history
  • Loading branch information
nz-m authored Sep 11, 2023
1 parent b972334 commit 4dc6c78
Showing 1 changed file with 14 additions and 22 deletions.
36 changes: 14 additions & 22 deletions client/src/middlewares/tokenMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,25 @@
import jwt_decode from "jwt-decode";
import { refreshTokenAction } from "../redux/actions/refreshTokenAction";

const TOKEN_REFRESH_THRESHOLD = 1800000; // 30 minutes in ms

const shouldRefreshToken = (token) => {
if (!token) return false;

const expiresIn = jwt_decode(token).exp * 1000 - Date.now();
return expiresIn < TOKEN_REFRESH_THRESHOLD;
};

export const tokenMiddleware = (store) => (next) => async (action) => {
if (action.meta && action.meta.requiresAuth) {
const state = store?.getState();
const state = store.getState();
const token = state.auth?.accessToken;

if (shouldRefreshToken(token)) {
const refreshToken = state.auth.refreshToken;
try {
await store.dispatch(refreshTokenAction(refreshToken));
const newToken = store?.getState().auth.accessToken;

if (!newToken) {
throw new Error("Access token not found after refresh");
if (token) {
const expiresIn = jwt_decode(token).exp * 1000 - Date.now();
if (expiresIn < 1800000) {
const refreshToken = state.auth.refreshToken;
try {
await store.dispatch(refreshTokenAction(refreshToken));
const newToken = store.getState().auth.accessToken;
if (!newToken) {
throw new Error("Access token not found after refresh");
}
} catch (error) {
store.dispatch({ type: "LOGOUT" });
}
} catch (error) {
store.dispatch({ type: "LOGOUT" });
}
} else if (!token) {
} else {
store.dispatch({ type: "LOGOUT" });
}
}
Expand Down

0 comments on commit 4dc6c78

Please sign in to comment.