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] 로그아웃 api 연결 #181

Merged
merged 3 commits into from
Jul 18, 2024
Merged
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
60 changes: 33 additions & 27 deletions src/apis/instance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import axios from 'axios';
import axios, { isAxiosError } from 'axios';

import { LoginResponse } from '@/apis/login/loginInterface';
import MESSAGES from '@/apis/messages';
Expand All @@ -24,17 +24,22 @@ export const privateInstance = axios.create({

// refresh token api
export async function postRefreshToken() {
const response = await axios.post<LoginResponse>(
`${API_URL}/api/auth/re-issue`,
{},
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('refreshToken')}`,
},
}
);
return response;
try {
const response = await axios.post<LoginResponse>(
`${API_URL}/api/auth/re-issue`,
{},
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('refreshToken')}`,
},
}
);
return response;
} catch (error) {
if (isAxiosError(error)) throw error;
else throw new Error(MESSAGES.UNKNOWN_ERROR);
}
}

privateInstance.interceptors.response.use(
Expand All @@ -49,23 +54,24 @@ privateInstance.interceptors.response.use(
// 토큰이 만료되을 때
if (status === 401) {
const originRequest = config;
const response = await postRefreshToken();

// 리프레시 토큰 요청이 성공할 때
if (response.status === 200) {
const newAccessToken = response.data.data.accessToken;
localStorage.setItem('accessToken', newAccessToken);
localStorage.setItem('refreshToken', response.data.data.refreshToken);
axios.defaults.headers.common.Authorization = `Bearer ${newAccessToken}`;
// 진행중이던 요청 이어서하기
originRequest.headers.Authorization = `Bearer ${newAccessToken}`;
return axios(originRequest);
}
if (response.status === 401) {
try {
const response = await postRefreshToken();
// 리프레시 토큰 요청이 성공할 때
if (response.status === 200) {
const newAccessToken = response.data.data.accessToken;
localStorage.setItem('accessToken', newAccessToken);
localStorage.setItem('refreshToken', response.data.data.refreshToken);
axios.defaults.headers.common.Authorization = `Bearer ${newAccessToken}`;
// 진행중이던 요청 이어서하기
originRequest.headers.Authorization = `Bearer ${newAccessToken}`;
return await axios(originRequest);
}
} catch (err) {
// 리프레시 토큰 요청이 실패할 때
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
alert(MESSAGES.LOGIN.EXPIRED);
window.location.replace('/');
} else {
alert(MESSAGES.UNKNOWN_ERROR);
}
}
return Promise.reject(error);
Expand Down
20 changes: 20 additions & 0 deletions src/apis/logout/logoutAxios.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { isAxiosError } from 'axios';

import { privateInstance } from '@/apis/instance';
import MESSAGES from '@/apis/messages';

const AUTH_URL = {
LOGOUT: '/api/auth/logout',
};

const userLogout = async () => {
try {
const response = await privateInstance.delete(AUTH_URL.LOGOUT);
return response.data;
} catch (error) {
if (isAxiosError(error)) throw error;
else throw new Error(MESSAGES.UNKNOWN_ERROR);
}
};

export default userLogout;
18 changes: 17 additions & 1 deletion src/components/SettingPage/LogOutBtn.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
import styled from '@emotion/styled';
import { useNavigate } from 'react-router-dom';

import userLogout from '@/apis/logout/logoutAxios';

function LogOutBtn() {
return <LogOutBox>로그아웃</LogOutBox>;
const navigate = useNavigate();

const handleLogoutButton = async () => {
try {
await userLogout();
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
navigate('/');
} catch (error) {
console.error(error);
}
};

return <LogOutBox onClick={handleLogoutButton}>로그아웃</LogOutBox>;
}

export default LogOutBtn;
Expand Down
Loading