Skip to content

Commit

Permalink
refactor: axisos interceptor 토큰 재발급 기능 추가 (#180)
Browse files Browse the repository at this point in the history
* refactor: 토큰 쿠키에서 관리하도록 수정

* chore: react-cookie 설치

* refactor: 기존 localToken 사용하던 부분 쿠키로 수정

* chore: 쿠키 key값 상수화

* feat: token 데이터에 currentUser도 추가

* chore: moment 라이브러리 추가

* feat: 토큰 유효기간 10분 기준으로 재발급 유무를 결정하는 checkToken 함수 생성

* fix: 쿠키가 전체 path에서 사용가능하도록 수정

* chore: 불필요한 코드 제거
  • Loading branch information
bellasimi authored Aug 11, 2022
1 parent 2044ae7 commit 2b4a0a2
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 16 deletions.
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@emotion/styled": "^11.9.3",
"@tanstack/react-query": "^4.0.10",
"axios": "^0.27.2",
"moment": "^2.29.4",
"next": "12.2.2",
"react": "18.2.0",
"react-cookie": "^4.1.1",
Expand Down
4 changes: 2 additions & 2 deletions src/components/Layout/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { FiLogIn, FiUser } from 'react-icons/fi'
import Link from 'next/link'
import { useEffect, useState, useCallback } from 'react'
import { MYINFO_URL, LOGIN_URL, USER_URL, HOME_URL } from '@constants/pageUrl'
import { getLocalToken } from '@utils/localToken'
import { getToken } from '@utils/cookie'

const MYINFO = '내정보'
const USER = '메뉴판'
Expand All @@ -22,7 +22,7 @@ export const Header = () => {

useEffect(() => {
if (pathname === LOGIN_URL || pathname === HOME_URL) {
setToken(getLocalToken() || '')
setToken(getToken() || '')
}
}, [token, pathname])

Expand Down
15 changes: 3 additions & 12 deletions src/lib/axios/interceptors.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import { getToken } from '@utils/cookie'
import { checkToken } from '@utils/checkToken'

export const handleRequest = (
config: AxiosRequestConfig
): AxiosRequestConfig => {
const token = getToken()
if (!config?.headers) {
throw new Error(`Axios config headers must be provided`)
}
if (token) {
config.headers.Authorization = token
}
return config
export const handleRequest = async (config: AxiosRequestConfig) => {
return checkToken(config)
}

export const handleRequestError = (error: AxiosError): Promise<AxiosError> => {
Expand Down
32 changes: 32 additions & 0 deletions src/utils/checkToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { AxiosRequestConfig } from 'axios'
import { getTokenData, setToken } from '@utils/cookie'
import moment from 'moment'
import axios from 'axios'

export const checkToken = async (config: AxiosRequestConfig) => {
const { currentUser, tastyToken, tastyToken_expire, tastyRefreshToken } =
getTokenData()

if (!config?.headers) {
throw new Error(`Axios config headers must be provided`)
}

if (
moment(tastyToken_expire).diff(moment(), 'minutes') < 10 &&
tastyRefreshToken
) {
const { data } = await axios.post(
`${process.env.NEXT_PUBLIC_API_URL}/re-issue`,
{
email: currentUser.email,
accessToken: tastyToken,
refreshToken: tastyRefreshToken
}
)
setToken(data)
config.headers.Authorization = data.token
} else {
config.headers.Authorization = tastyToken
}
return config
}
15 changes: 13 additions & 2 deletions src/utils/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,14 @@ export const removeCookie = (name: string) => {
}

export const setToken = ({ token, expirationDate }: Token) => {
setCookie(TOKEN_KEY, token)
setCookie(TOKEN_EXPIRE_DATE, expirationDate)
setCookie(TOKEN_KEY, token, {
path: '/',
expires: new Date(expirationDate)
})
setCookie(TOKEN_EXPIRE_DATE, expirationDate, {
path: '/',
expires: new Date(expirationDate)
})
}

export const getToken = () => {
Expand All @@ -55,18 +61,23 @@ export const getTokenData = () => {

export const setTokenData = ({ accessToken, account, refreshToken }: Data) => {
setCookie(TOKEN_KEY, accessToken.token, {
path: '/',
expires: new Date(accessToken.expirationDate)
})
setCookie(TOKEN_EXPIRE_DATE, accessToken.expirationDate, {
path: '/',
expires: new Date(accessToken.expirationDate)
})
setCookie(REFRESH_TOKEN_KEY, refreshToken.token, {
path: '/',
expires: new Date(refreshToken.expirationDate)
})
setCookie(REFRESH_TOKEN_EXPIRE_DATE, refreshToken.expirationDate, {
path: '/',
expires: new Date(refreshToken.expirationDate)
})
setCookie(CURRENT_USER, JSON.stringify(account), {
path: '/',
expires: new Date(accessToken.expirationDate)
})
}
Expand Down

0 comments on commit 2b4a0a2

Please sign in to comment.