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

[feat] refresh token 기반 토큰 재발급 #123

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
21 changes: 21 additions & 0 deletions src/apis/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import axios from 'axios';

import { localstorageKeys } from '@src/constants/localstorage';
import { Onboarding } from '@src/pages/onboarding/index.page';

import { BaseResponse } from '.';
Expand Down Expand Up @@ -54,3 +55,23 @@ export const checkNickName = async (nickName: string) => {

return res.data.data;
};

export type RefreshTokenResponse = BaseResponse<Auth['jwtTokens']>;
export const refreshToken = async () => {
const user = localStorage.getItem(localstorageKeys.user);
if (!user) return;
const { refreshToken } = JSON.parse(user) as Auth['jwtTokens'];
if (!refreshToken) return;

const res = await axios.post<RefreshTokenResponse>(`/refresh`, null, {
headers: {
'refresh-token': refreshToken,
},
});
const code = res.data.code;
if (Number(code) === 2003 || Number(code) === 2005 || Number(code) === 2006) {
localStorage.removeItem(localstorageKeys.user);
}

return res.data.data;
};
24 changes: 23 additions & 1 deletion src/configs/axios.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios, { AxiosRequestConfig } from 'axios';

import { Auth } from '@src/apis';
import { Auth, refreshToken } from '@src/apis';
import { localstorageKeys } from '@src/constants/localstorage';

export const BASE_URL = process.env.NEXT_PUBLIC_API_URL;
Expand All @@ -22,4 +22,26 @@ export const interceptorsAxiosConfig = () => {
}
return config;
});

axios.interceptors.response.use(
(res) => res,
async (err) => {
const { config, response } = err;
const code = response.data.code;

if (Number(code) !== 2002) {
return Promise.reject(err);
}

config.sent = true;
const jwtTokens = await refreshToken();
if (!jwtTokens) {
localStorage.removeItem(localstorageKeys.user);
return Promise.reject(err);
}
localStorage.setItem(localstorageKeys.user, JSON.stringify(jwtTokens));

return axios(config);
},
);
};