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

인증인가 코드 리팩토링 #436

Merged
merged 8 commits into from
Aug 14, 2023
4 changes: 2 additions & 2 deletions frontend/cypress/e2e/trip.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ describe('여행 아이템 추가', () => {
cy.get('select[aria-label="비용 카테고리"]').select('문화').should('have.value', '200');

cy.get('select[aria-label="통화"')
.select('€    (EUR)')
.select('€     (EUR)')
.should('have.value', 'EUR');

cy.get('input[aria-label="비용"]').type('400').should('have.value', '400');
Expand Down Expand Up @@ -312,7 +312,7 @@ describe('여행 아이템 추가', () => {
cy.get('#title').type('샹젤리제 거리 -> 에펠탑 지하철');
cy.get('.star-box > div').eq(6).click();
cy.get('select[aria-label="비용 카테고리"]').select('문화');
cy.get('select[aria-label="통화"').select('€    (EUR)');
cy.get('select[aria-label="통화"').select('€     (EUR)');
cy.get('input[aria-label="비용"]').type('400');
cy.findByPlaceholderText('메모를 입력해 주세요').type('즐거운 여행');
cy.get('input[type=file]')
Expand Down
14 changes: 7 additions & 7 deletions frontend/package-lock.json

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

2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"@tanstack/react-query": "^4.29.19",
"axios": "^1.4.0",
"dotenv": "^16.3.1",
"hang-log-design-system": "^1.2.19",
"hang-log-design-system": "^1.2.20",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.14.1",
Expand Down
28 changes: 8 additions & 20 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { useLayoutEffect } from 'react';
import { Outlet } from 'react-router-dom';

import { useSetRecoilState } from 'recoil';

import Error from '@components/common/Error/Error';
import ErrorBoundary from '@components/common/ErrorBoundary/ErrorBoundary';
import LogIn from '@components/common/LogIn/LogIn';
import ScrollTop from '@components/common/ScrollTop/ScrollTop';
import ToastContainer from '@components/common/ToastContainer/ToastContainer';
import Footer from '@components/layout/Footer/Footer';
Expand All @@ -13,30 +11,20 @@ import Header from '@components/layout/Header/Header';
import { useMediaQuery } from '@hooks/common/useMediaQuery';
import { useResetError } from '@hooks/common/useResetError';

import { isLoggedInState } from '@store/auth';

import { ACCESS_TOKEN_KEY } from '@constants/api';

const App = () => {
const { handleErrorReset } = useResetError();
useMediaQuery();

const setIsLoggedIn = useSetRecoilState(isLoggedInState);

useLayoutEffect(() => {
if (localStorage.getItem(ACCESS_TOKEN_KEY)) {
setIsLoggedIn(true);
}
}, [setIsLoggedIn]);

return (
<ErrorBoundary Fallback={Error} onReset={handleErrorReset}>
<ScrollTop />
<Header />
<main>
<Outlet />
</main>
<Footer />
<LogIn>
<Header />
<main>
<Outlet />
</main>
<Footer />
</LogIn>
<ToastContainer />
</ErrorBoundary>
);
Expand Down
24 changes: 9 additions & 15 deletions frontend/src/api/interceptors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface ErrorResponseData {
}

export const checkAndSetToken = (config: InternalAxiosRequestConfig) => {
if (!config.headers || config.headers.Authorization || !config.useAuth) return config;
if (!config.useAuth || !config.headers || config.headers.Authorization) return config;

const accessToken = localStorage.getItem(ACCESS_TOKEN_KEY);

Expand All @@ -34,11 +34,9 @@ export const handleTokenError = async (error: AxiosError<ErrorResponseData>) =>

if (!error.response || !originalRequest) throw new Error('에러가 발생했습니다.');

// ! 토큰 에러 처리!
if (
error.response.status === HTTP_STATUS_CODE.BAD_REQUEST &&
error.response.data.code === ERROR_CODE.EXPIRED_ACCESS_TOKEN
) {
const { data, status } = error.response;

if (status === HTTP_STATUS_CODE.BAD_REQUEST && data.code === ERROR_CODE.EXPIRED_ACCESS_TOKEN) {
const { accessToken } = await postNewToken();
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
Expand All @@ -47,16 +45,12 @@ export const handleTokenError = async (error: AxiosError<ErrorResponseData>) =>
}

if (
error.response.status === HTTP_STATUS_CODE.BAD_REQUEST &&
(error.response.data.code === ERROR_CODE.INVALID_ACCESS_TOKEN ||
error.response.data.code === ERROR_CODE.INVALID_REFRESH_TOKEN ||
error.response.data.code === ERROR_CODE.EXPIRED_REFRESH_TOKEN)
status === HTTP_STATUS_CODE.BAD_REQUEST &&
(data.code === ERROR_CODE.INVALID_ACCESS_TOKEN ||
data.code === ERROR_CODE.INVALID_REFRESH_TOKEN ||
data.code === ERROR_CODE.EXPIRED_REFRESH_TOKEN)
) {
throw new HTTPError(
error.response.status,
error.response.data.message,
error.response.data.code
);
throw new HTTPError(status, data.message, data.code);
}

throw error;
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/api/member/putUserInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ import type { UserData } from '@type/member';
import { END_POINTS } from '@constants/api';

export const putUserInfo = (data: UserData) => {
return axiosInstance.put<UserData>(END_POINTS.MY_PAGE, { ...data });
return axiosInstance.put<UserData>(END_POINTS.MY_PAGE, data);
};
26 changes: 26 additions & 0 deletions frontend/src/components/common/LogIn/LogIn.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { ReactNode } from 'react';
import { useLayoutEffect } from 'react';

import { useSetRecoilState } from 'recoil';

import { isLoggedInState } from '@store/auth';

import { ACCESS_TOKEN_KEY } from '@constants/api';

interface LogInProps {
children: ReactNode;
}

const LogIn = ({ children }: LogInProps) => {
const setIsLoggedIn = useSetRecoilState(isLoggedInState);

useLayoutEffect(() => {
if (localStorage.getItem(ACCESS_TOKEN_KEY)) {
setIsLoggedIn(true);
}
}, [setIsLoggedIn]);

return children;
};

export default LogIn;
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const EditUserProfileForm = ({ initialData }: EditUserProfileForm) => {
<form css={formStyling} onSubmit={handleSubmit} noValidate>
<ProfileImageInput
css={imageInputStyling}
initialImageUrl={userInfo.imageUrl}
initialImageUrl={initialData.imageUrl}
updateInputValue={updateInputValue}
/>
<NicknameInput
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type ChangeEvent, useCallback } from 'react';
import { type ChangeEvent, memo, useCallback } from 'react';

import { Input } from 'hang-log-design-system';

Expand Down Expand Up @@ -41,4 +41,4 @@ const NicknameInput = ({ value, isError, updateInputValue, disableError }: Nickn
);
};

export default NicknameInput;
export default memo(NicknameInput);
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
wrapperStyling,
} from '@components/myPage/EditUserProfileForm/ProfileImageInput/ProfileImageInput.style';

import { useImageUpload } from '@hooks/common/useImageUpload';
import { useSingleImageUpload } from '@hooks/common/useSingleImageUpload';

import type { UserData } from '@type/member';

Expand All @@ -31,14 +31,14 @@ const ProfileImageInput = ({
};

const handleImageUrlsChange = useCallback(
(imageUrls: string[]) => {
updateInputValue('imageUrl', imageUrls[0]);
(imageUrl: string) => {
updateInputValue('imageUrl', imageUrl);
},
[updateInputValue]
);

const { uploadedImageUrls, handleImageUpload } = useImageUpload({
initialImageUrls: [initialImageUrl],
const { uploadedImageUrl, handleImageUpload } = useSingleImageUpload({
initialImageUrl,
onSuccess: handleImageUrlsChange,
});

Expand All @@ -61,7 +61,7 @@ const ProfileImageInput = ({
ref={inputRef}
onChange={handleImageUpload}
/>
<img css={imageStyling} src={uploadedImageUrls[0]} alt="사용자 프로필 이미지" />
<img css={imageStyling} src={uploadedImageUrl!} alt="사용자 프로필 이미지" />
</Box>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useCallback } from 'react';

import { ImageUploadInput } from 'hang-log-design-system';

import { useImageUpload } from '@hooks/common/useImageUpload';
import { useMultipleImageUpload } from '@hooks/common/useMultipleImageUpload';

interface ImageInputProps {
initialImage: string | null;
Expand All @@ -21,7 +21,7 @@ const ImageInput = ({ initialImage, updateCoverImage }: ImageInputProps) => {
uploadedImageUrls: uploadedImageUrl,
handleImageUpload,
handleImageRemoval,
} = useImageUpload({
} = useMultipleImageUpload({
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useSingleImageUpload가 있으면 여기도 그거 쓰면 될 듯?! 얘도 하나만 올릴 수 있으니까용~~

initialImageUrls: initialImage === null ? [] : [initialImage],
onSuccess: handleImageUrlsChange,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const ExpenseInput = ({ initialExpenseValue, updateInputValue }: ExpenseInputPro
>
{Object.entries(CURRENCY_ICON).map(([key, value]) => (
<option key={key} value={key}>
{value}&nbsp;&nbsp;&nbsp;&nbsp;({key})
{value}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;({key})
</option>
))}
</Select>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useCallback } from 'react';

import { ImageUploadInput } from 'hang-log-design-system';

import { useImageUpload } from '@hooks/common/useImageUpload';
import { useMultipleImageUpload } from '@hooks/common/useMultipleImageUpload';
import { useToast } from '@hooks/common/useToast';

import type { TripItemFormData } from '@type/tripItem';
Expand All @@ -28,7 +28,7 @@ const ImageInput = ({ initialImageUrls, updateInputValue }: ImageInputProps) =>
createToast('이미지는 최대 5개 업로드할 수 있습니다.');
};

const { uploadedImageUrls, handleImageUpload, handleImageRemoval } = useImageUpload({
const { uploadedImageUrls, handleImageUpload, handleImageRemoval } = useMultipleImageUpload({
initialImageUrls,
onSuccess: handleImageUrlsChange,
onError: handleImageUploadError,
Expand Down
70 changes: 0 additions & 70 deletions frontend/src/hooks/common/useImageUpload.ts

This file was deleted.

Loading