File tree Expand file tree Collapse file tree 2 files changed +27
-3
lines changed
Expand file tree Collapse file tree 2 files changed +27
-3
lines changed Original file line number Diff line number Diff line change 1- import axios , { AxiosRequestConfig } from "axios" ;
1+ import axios , {
2+ AxiosRequestConfig ,
3+ type AxiosResponse ,
4+ type AxiosError ,
5+ } from "axios" ;
26import { jwtDecode } from "jwt-decode" ;
37import { DecodedJWT } from "../types/AuthTypes" ;
48import {
59 refreshAccessToken ,
610 validateAccessToken ,
711 getAccessToken ,
12+ clearAccessToken ,
813} from "../utils/AuthUtils" ;
914
1015const 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+
5173export default baseAPIClient ;
Original file line number Diff line number Diff 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
5250export 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+ } ;
You can’t perform that action at this time.
0 commit comments