From 7af47d93b6e9e67951389aff3d18e47ec2fe6d4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=A7=80=EC=9C=A4?= Date: Thu, 19 Dec 2024 19:46:16 +0900 Subject: [PATCH] =?UTF-8?q?chore:=20=ED=86=A0=ED=81=B0=20=EC=9C=A0?= =?UTF-8?q?=EB=AC=B4=20=EB=A1=9C=EC=A7=81=20=EC=B6=94=EA=B0=80=20=EB=B0=8F?= =?UTF-8?q?=20=ED=8C=8C=EC=9D=BC=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/_api/axiosInstance.ts | 14 +++++++++++--- src/_api/constant/noTokenEndPoints.ts | 9 +++++++++ src/_api/util/isAuthRequired.ts | 19 +++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 src/_api/constant/noTokenEndPoints.ts create mode 100644 src/_api/util/isAuthRequired.ts diff --git a/src/_api/axiosInstance.ts b/src/_api/axiosInstance.ts index 908e7df..263825c 100644 --- a/src/_api/axiosInstance.ts +++ b/src/_api/axiosInstance.ts @@ -1,4 +1,6 @@ import axios from 'axios'; +import NO_TOKEN_ENDPOINTS from './constant/noTokenEndPoints'; +import isAuthRequired from './util/isAuthRequired'; import { getAccessToken, _LOGIN_NEED_MESSAGE_ } from './storage/authStorage'; const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL; @@ -12,16 +14,22 @@ const axiosInstance = axios.create({ }, }); -const NO_TOKEN_ENDPOINTS = ['/auth/signUp', '/auth/signIn', '/oauthApps']; - axiosInstance.interceptors.request.use( (config) => { - const token = getAccessToken(); //dino@gmail.com, 12341234 //임시 토큰 // const token = // 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NzMyLCJ0ZWFtSWQiOiIxMC0zIiwiaWF0IjoxNzM0NTEzNTUyLCJpc3MiOiJzcC1tb2dhem9hIn0.tbvOoiH-iTR1CZW5rhjJW5KSr2Go8cxGwqRWxLGwqZ8'; + const path = config.url || ''; + const method = config?.method || ''; + + if (!isAuthRequired(path, method)) { + return config; + } + + const token = getAccessToken(); + if (!token && config.url && !NO_TOKEN_ENDPOINTS.includes(config.url)) { throw new Error(`Failed to getAccessToken(), ${_LOGIN_NEED_MESSAGE_}`); } diff --git a/src/_api/constant/noTokenEndPoints.ts b/src/_api/constant/noTokenEndPoints.ts new file mode 100644 index 0000000..3e7d6bd --- /dev/null +++ b/src/_api/constant/noTokenEndPoints.ts @@ -0,0 +1,9 @@ +const NO_TOKEN_ENDPOINTS = [ + '/auth/', + '/categories', + '/oauthApps', + '/products', + `/users/`, +]; + +export default NO_TOKEN_ENDPOINTS; diff --git a/src/_api/util/isAuthRequired.ts b/src/_api/util/isAuthRequired.ts new file mode 100644 index 0000000..496f8fb --- /dev/null +++ b/src/_api/util/isAuthRequired.ts @@ -0,0 +1,19 @@ +import NO_TOKEN_ENDPOINTS from '../constant/noTokenEndPoints'; + +const isAuthRequired = (path: string, method: string): boolean => { + if (path === '/users/me') { + return true; + } + + if (path.startsWith('/users/')) { + return false; + } + + if (method === 'POST' && path.startsWith('/products')) { + return true; + } + + return !NO_TOKEN_ENDPOINTS.some((endpoint) => path.startsWith(endpoint)); +}; + +export default isAuthRequired;