Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Race Condition in Axios Interceptor for Refresh Token #356

Merged
merged 4 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 1 addition & 38 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as Sentry from "@sentry/react";
import { QueryCache, QueryClient, QueryClientProvider } from "@tanstack/react-query";
import axios from "axios";
import { useEffect, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useSelector } from "react-redux";
import {
RouterProvider,
createBrowserRouter,
Expand All @@ -21,10 +21,7 @@ import { useGetSettingsQuery } from "./hooks/api/settings";
import { useErrorHandler } from "./hooks/useErrorHandler";
import AuthProvider from "./providers/AuthProvider";
import { routes } from "./routes";
import { logout, setAccessToken } from "./store/authSlice";
import { selectConfig } from "./store/configSlice";
import { store } from "./store/store";
import { setUserData } from "./store/userSlice";
import { isAxios404Error, isAxios500Error } from "./utils/axios.default";

if (import.meta.env.PROD) {
Expand Down Expand Up @@ -61,7 +58,6 @@ function SettingLoader() {

function App() {
const config = useSelector(selectConfig);
const dispatch = useDispatch();
const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
const theme = useMemo(() => {
const defaultMode = prefersDarkMode ? "dark" : "light";
Expand Down Expand Up @@ -108,39 +104,6 @@ function App() {
});
}, [handleError]);

useEffect(() => {
const handleRefreshTokenExpiration = () => {
dispatch(logout());
dispatch(setUserData(null));
};

const interceptor = axios.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401 && !error.config._retry) {
if (error.config.url === "/auth/refresh") {
handleRefreshTokenExpiration();
return Promise.reject(error);
} else {
error.config._retry = true;
const refreshToken = store.getState().auth.refreshToken;
const response = await axios.post("/auth/refresh", { refreshToken });
const newAccessToken = response.data.newAccessToken;
dispatch(setAccessToken(newAccessToken));
axios.defaults.headers.common["Authorization"] = `Bearer ${newAccessToken}`;
error.config.headers["Authorization"] = `Bearer ${newAccessToken}`;
return axios(error.config);
}
}
return Promise.reject(error);
}
);

return () => {
axios.interceptors.response.eject(interceptor);
};
}, [dispatch]);

return (
<QueryClientProvider client={queryClient}>
<AuthProvider>
Expand Down
39 changes: 36 additions & 3 deletions frontend/src/hooks/api/user.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { logout, selectAuth } from "../../store/authSlice";
import { logout, selectAuth, setAccessToken } from "../../store/authSlice";
import { User, setUserData } from "../../store/userSlice";
import { GetUserResponse, UpdateUserRequest } from "./types/user";

Expand All @@ -13,10 +13,43 @@ export const generateGetUserQueryKey = (accessToken: string) => {
export const useGetUserQuery = () => {
const dispatch = useDispatch();
const authStore = useSelector(selectAuth);
const [axiosIntercepterAdded, setAxiosIntercepterAdded] = useState(false);
devleejb marked this conversation as resolved.
Show resolved Hide resolved

useEffect(() => {
const interceptor = axios.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401 && !error.config._retry) {
if (error.config.url === "/auth/refresh") {
dispatch(logout());
dispatch(setUserData(null));
return Promise.reject(error);
} else {
error.config._retry = true;
const { refreshToken } = authStore;
const response = await axios.post("/auth/refresh", { refreshToken });
const newAccessToken = response.data.newAccessToken;
dispatch(setAccessToken(newAccessToken));
axios.defaults.headers.common["Authorization"] = `Bearer ${newAccessToken}`;
error.config.headers["Authorization"] = `Bearer ${newAccessToken}`;
return axios(error.config);
devleejb marked this conversation as resolved.
Show resolved Hide resolved
}
}
return Promise.reject(error);
}
);

setAxiosIntercepterAdded(true);

return () => {
setAxiosIntercepterAdded(false);
axios.interceptors.response.eject(interceptor);
};
}, [authStore, dispatch]);
devleejb marked this conversation as resolved.
Show resolved Hide resolved

const query = useQuery({
queryKey: generateGetUserQueryKey(authStore.accessToken || ""),
enabled: Boolean(authStore.accessToken),
enabled: Boolean(axiosIntercepterAdded && authStore.accessToken),
queryFn: async () => {
axios.defaults.headers.common["Authorization"] = `Bearer ${authStore.accessToken}`;
const res = await axios.get<GetUserResponse>("/users");
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/providers/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ interface AuthProviderProps {

function AuthProvider(props: AuthProviderProps) {
const { children } = props;
const { data: user, isSuccess, isLoading } = useGetUserQuery();
const { data: user, isSuccess, isLoading, isPending } = useGetUserQuery();
const shouldChangeNickname = useMemo(
() => isSuccess && !user.nickname,
[isSuccess, user?.nickname]
);

return (
<AuthContext.Provider value={{ isLoggedIn: isSuccess, isLoading }}>
<AuthContext.Provider value={{ isLoggedIn: isSuccess, isLoading: isPending || isLoading }}>
devleejb marked this conversation as resolved.
Show resolved Hide resolved
{shouldChangeNickname ? <ChangeNicknameModal open /> : children}
</AuthContext.Provider>
);
Expand Down