-
Notifications
You must be signed in to change notification settings - Fork 79
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #738 from codefug/React-이승현-Sprint12
- Loading branch information
Showing
14 changed files
with
221 additions
and
139 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,25 @@ | ||
import { create } from "zustand"; | ||
import { create, StateCreator } from "zustand"; | ||
import { persist } from "zustand/middleware"; | ||
|
||
type User = { | ||
accessToken: string; | ||
}; | ||
|
||
type Store = { | ||
type UserState = { | ||
user: User | null; | ||
login: (accessToken: string) => void; | ||
logout: () => void; | ||
}; | ||
|
||
export const useStore = create<Store>()((set) => ({ | ||
export const useStoreSlice: StateCreator<UserState> = (set) => ({ | ||
user: null, | ||
login: (accessToken: string) => { | ||
localStorage.setItem("accessToken", accessToken); | ||
document.cookie = `accessToken=${localStorage.getItem("accessToken")}`; | ||
return set(() => ({ user: { accessToken } })); | ||
}, | ||
login: (accessToken: string) => set(() => ({ user: { accessToken } })), | ||
logout: () => set(() => ({ user: null })), | ||
})); | ||
}); | ||
|
||
const persistedUserStore = persist<UserState>(useStoreSlice, { | ||
name: "user", | ||
getStorage: () => localStorage, | ||
}); | ||
|
||
export const useUserStore = create(persistedUserStore); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,90 @@ | ||
import axios from "axios"; | ||
import { useUserStore } from "@/app/store"; | ||
import { BASE_URL } from "../constants/constants"; | ||
import { refreshTokenRotation } from "../util/RTR"; | ||
|
||
const instance = axios.create({ baseURL: BASE_URL }); | ||
import axios, { | ||
AxiosError, | ||
CreateAxiosDefaults, | ||
InternalAxiosRequestConfig, | ||
} from "axios"; | ||
import { postAuthRefreshToken } from "./api"; | ||
|
||
const authInstance = axios.create({ baseURL: BASE_URL }); | ||
// 재시도 확인 프로퍼티 설정 | ||
interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig { | ||
_retry?: boolean; | ||
} | ||
|
||
const { setAuthHeader } = refreshTokenRotation(); | ||
// 기본 설정 | ||
const baseConfig: CreateAxiosDefaults = { | ||
baseURL: `${BASE_URL}`, | ||
}; | ||
|
||
authInstance.interceptors.request.use(setAuthHeader); | ||
// 쿠키 드러내고 인증 필요없는 인스턴스 | ||
export const instanceWithoutInterceptors = axios.create(baseConfig); | ||
|
||
export { authInstance, instance }; | ||
// 인증 필요한 인스턴스 | ||
export const instance = axios.create({ ...baseConfig, withCredentials: true }); | ||
|
||
instance.interceptors.request.use( | ||
// 요청 전에 실행 | ||
function (config) { | ||
// 토큰 가져오기 | ||
const accessToken = useUserStore.getState().user?.accessToken; | ||
|
||
// 헤더에 토큰 추가 | ||
if (accessToken) { | ||
config.headers.Authorization = `Bearer ${accessToken}`; | ||
} | ||
|
||
// 설정 반환 | ||
return config; | ||
}, | ||
// 요청 에러 발생 시 실행 | ||
function (error) { | ||
return Promise.reject(error); | ||
} | ||
); | ||
|
||
instance.interceptors.response.use( | ||
// 응답 성공 시 실행 | ||
function (response) { | ||
return response; | ||
}, | ||
// 응답 에러 발생 시 실행 | ||
async function (error: AxiosError) { | ||
// 에러 정보 가져오기 | ||
const originalRequest: CustomAxiosRequestConfig | undefined = error.config; | ||
|
||
// 토큰 만료 시 재시도 | ||
if ( | ||
error.response?.status === 401 && | ||
originalRequest && | ||
!originalRequest._retry | ||
) { | ||
originalRequest._retry = true; | ||
try { | ||
// 토큰 재발급 | ||
const response = await postAuthRefreshToken(); | ||
|
||
// 토큰 갱신 | ||
useUserStore.setState({ | ||
user: { accessToken: response.accessToken }, | ||
}); | ||
|
||
// 헤더에 토큰 추가 | ||
originalRequest.headers.Authorization = `Bearer ${response.accessToken}`; | ||
|
||
// 재시도 | ||
return instance(originalRequest); | ||
} catch (error) { | ||
// 토큰이 만료되었을 때 | ||
if (error instanceof AxiosError && error.response?.status === 403) { | ||
// 로그아웃 | ||
useUserStore.getState().logout(); | ||
return; | ||
} | ||
} | ||
} | ||
|
||
return Promise.reject(error); | ||
} | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.