Skip to content

Commit 0956f50

Browse files
authored
Merge pull request #85 from wafflestudio/bug/refresh
refresh 시 로그인 풀리는 이슈 수정
2 parents 36898eb + b5a56c4 commit 0956f50

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

src/api/axios.ts

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@ import { TokenService } from "./tokenService";
33

44
const API_URL = import.meta.env.VITE_API_URL || "";
55

6+
let isRefreshing = false;
7+
let refreshSubscribers: ((token: string) => void)[] = [];
8+
9+
const onRefreshed = (accessToken: string) => {
10+
refreshSubscribers.forEach((callback) => callback(accessToken));
11+
refreshSubscribers = [];
12+
};
13+
14+
const addRefreshSubscriber = (callback: (token: string) => void) => {
15+
refreshSubscribers.push(callback);
16+
};
17+
618
const api = axios.create({
719
baseURL: API_URL,
820
withCredentials: true,
@@ -54,7 +66,17 @@ api.interceptors.response.use(
5466
}
5567

5668
if (error.response?.status === 401 && !originalRequest._retry) {
69+
if (isRefreshing) {
70+
return new Promise((resolve) => {
71+
addRefreshSubscriber((token: string) => {
72+
originalRequest.headers.Authorization = `Bearer ${token}`;
73+
resolve(api(originalRequest));
74+
});
75+
});
76+
}
77+
5778
originalRequest._retry = true;
79+
isRefreshing = true;
5880

5981
try {
6082
const { data } = await axios.post<{ accessToken: string }>(
@@ -65,14 +87,19 @@ api.interceptors.response.use(
6587

6688
// update storage
6789
TokenService.setToken(data.accessToken);
68-
90+
91+
isRefreshing = false;
92+
onRefreshed(data.accessToken);
93+
6994
// update header
7095
originalRequest.headers.Authorization = `Bearer ${data.accessToken}`;
7196

7297
// retry original request
7398
return api(originalRequest);
7499
} catch (refreshError) {
75100
// refresh failed :
101+
isRefreshing = false;
102+
refreshSubscribers = [];
76103
TokenService.clearTokens();
77104
console.error("Session expired. Please sign in again");
78105
return Promise.reject(refreshError);

src/contexts/AuthProvider.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,15 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
5757
/**
5858
* INIT : check for existing session on page load
5959
*/
60+
const isInitRunning = useRef(false);
6061
useEffect(() => {
6162
if (window.location.pathname === '/auth/callback') {
6263
setIsLoading(false);
6364
return;
6465
}
6566
const initAuth = async () => {
67+
if (isInitRunning.current) return;
68+
isInitRunning.current = true;
6669
try {
6770
const restoredUser = await auth.refresh();
6871

0 commit comments

Comments
 (0)