Skip to content

Commit 9e477e5

Browse files
committed
Added redirection if the refresh token expires
1 parent cd7dc04 commit 9e477e5

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

frontend/src/APIClients/BaseAPIClient.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1-
import axios, { AxiosRequestConfig } from "axios";
1+
import axios, {
2+
AxiosRequestConfig,
3+
type AxiosResponse,
4+
type AxiosError,
5+
} from "axios";
26
import { jwtDecode } from "jwt-decode";
37
import { DecodedJWT } from "../types/AuthTypes";
48
import {
59
refreshAccessToken,
610
validateAccessToken,
711
getAccessToken,
12+
clearAccessToken,
813
} from "../utils/AuthUtils";
914

1015
const API_BASE = process.env.REACT_APP_BACKEND_URL || "";
@@ -48,4 +53,21 @@ baseAPIClient.interceptors.request.use(async (config: AxiosRequestConfig) => {
4853
return newConfig;
4954
});
5055

56+
// If the user tries to access restricted endpoints then redirect them
57+
// We should be careful with the error codes since now 401 and 403 will cause redirects
58+
// TODO: Handle permissions
59+
baseAPIClient.interceptors.response.use(
60+
(response: AxiosResponse) => response,
61+
(error: AxiosError) => {
62+
if (error.response?.status === 401 || error.response?.status === 403) {
63+
// clear user data
64+
clearAccessToken();
65+
66+
// redirect to login page
67+
window.location.href = "/login";
68+
}
69+
return Promise.reject(error);
70+
},
71+
);
72+
5173
export default baseAPIClient;

frontend/src/utils/AuthUtils.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,6 @@ export const getAccessToken = (): string | null => {
4646
}
4747
};
4848

49-
// TODO: Add a clearAccessToken here too
50-
5149
// Checks if the access token has expired or not
5250
export const validateAccessToken = (decodedToken: DecodedJWT): boolean => {
5351
// Check if expired
@@ -60,3 +58,7 @@ export const validateAccessToken = (decodedToken: DecodedJWT): boolean => {
6058
return !result;
6159
};
6260

61+
// Removes the access token
62+
export const clearAccessToken = (): void => {
63+
clearLocalStorageKey(AUTHENTICATED_USER_KEY);
64+
};

0 commit comments

Comments
 (0)