Skip to content

Commit

Permalink
Merge pull request #150 from Step3-kakao-tech-campus/feat/#121
Browse files Browse the repository at this point in the history
로그인 api 변경으로 인한 기능 수정
  • Loading branch information
LimSumi authored Oct 30, 2023
2 parents 6b0d4e6 + c67c4ec commit d9eebc5
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 27 deletions.
10 changes: 7 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import SignupPage from 'pages/signUp/SignupPage';
import UrgentListPage from 'pages/profileList/urgentList/UrgentListPage';
import UpdatePage from 'pages/update/UpdatePage';
import HomePage from 'pages/home/HomePage';
import ValidateCheckLayout from 'layouts/ValidateCheckLayout';

const queryClient = new QueryClient({
defaultOptions: {
Expand All @@ -25,18 +26,21 @@ function App() {
<QueryClientProvider client={queryClient}>
<RecoilRoot>
<BrowserRouter>
<Routes>
<ValidateCheckLayout>
{/* 토큰 검사가 필요한 페이지에만 검사 */}
<Route path="/" element={<HomePage />} />
<Route path="/pet/:id" element={<DetailPetPage />} />
<Route path="/profile" element={<ProfileListPage />} />
<Route path="/shelter/:id/:page" element={<ShelterInfoPage />} />
<Route path="/profile/urgent/:page" element={<UrgentListPage />} />
<Route path="/profile/new/:page" element={<NewListPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/signup" element={<SignupPage />} />
<Route path="/find-shelter" element={<MapPage />} />
<Route path="/pet-update/:id" element={<UpdatePage />} />
</ValidateCheckLayout>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/signup" element={<SignupPage />} />
</Routes>
</BrowserRouter>
</RecoilRoot>
Expand Down
14 changes: 14 additions & 0 deletions src/commons/cookie/getUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@ export const getLoginState = () => {
return '로그인';
};

export const validateExpiredToken = () => {
const now = new Date();
const expiredDate = new Date(getCookie('expiredDate'));
console.log('만료 검사');

// 토큰만료 검사 후 삭제
if (now > expiredDate) {
removeCookie('loginToken');
removeCookie('expiredDate');
removeCookie('userAccountInfo');
console.log('토큰이 만료되어 삭제되었습니다.');
}
};

export const removeToken = () => {
removeCookie('loginToken');
};
20 changes: 20 additions & 0 deletions src/layouts/ValidateCheckLayout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { validateExpiredToken } from 'commons/cookie/getUser';
import React, { useEffect } from 'react';
import { Routes } from 'react-router-dom';

interface LayoutProps {
children: React.ReactNode;
}

const ValidateCheckLayout: React.FC<LayoutProps> = ({ children }) => {
useEffect(() => {
validateExpiredToken();
const intervalId = setInterval(validateExpiredToken, 60000 * 30); // 30분에 한 번

return () => clearInterval(intervalId);
}, []);

return <Routes>{children}</Routes>;
};

export default ValidateCheckLayout;
21 changes: 15 additions & 6 deletions src/pages/login/LoginInputForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,14 @@ const LoginInputForm = () => {
})

.then((data) => {
console.log('data: ', data);
if (data.success) {
const { accountInfo, tokenExpirationDateTime } = data.response;
const { id, role } = accountInfo;
const expiredDate = new Date(tokenExpirationDateTime);

setCookie('userAccountInfo', `${role} ${id}`);
setCookie('expiredDate', String(expiredDate));
navigate('/');
} else {
// 형식은 맞지만 입력된 값이 가입되지 않은 계정일 때
Expand All @@ -53,15 +60,10 @@ const LoginInputForm = () => {
});
};

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
// email, password 비었는지 확인
const validateCheck = () => {
validationSchema
.validate(userInfo, { abortEarly: false })
.then(() => {
// email, password 보내기
setIsLoading(true);
userfetch();
setErrors({});
})
.catch((err) => {
Expand All @@ -75,6 +77,13 @@ const LoginInputForm = () => {
});
};

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setIsLoading(true);
validateCheck();
userfetch();
};

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const target = event.target as HTMLInputElement;
if (target.id === 'id') {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/login/VLoginInputForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const VLoginInputForm = ({
}: LoginInputFormProps) => {
return (
<form
className="flex flex-col gap-4 w-full max-w-[400px]"
className="flex flex-col gap-3 w-full max-w-[400px]"
onSubmit={handleSubmit}
>
<InputGroup
Expand Down
14 changes: 13 additions & 1 deletion src/pages/map/TestMap.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { useState, useEffect, Dispatch, SetStateAction } from 'react';
import {
useState,
useEffect,
Dispatch,
SetStateAction,
useRef,
RefObject,
} from 'react';
import { Map, MapMarker } from 'react-kakao-maps-sdk';

type Coordinate = {
Expand Down Expand Up @@ -35,6 +42,8 @@ const TestMap = () => {
const [markers, setMarkers] = useState<Array<PlaceType>>([]);
const [searchedPlaces, setSearchedPlaces] = useState<Array<PlaceType>>([]);
const [isExecuted, setIsExecuted] = useState<boolean>(false);
const mapRef = useRef<any>();
const markerRef = useRef<any>();

// 보호소 키워드로 검색한 후 저장
const searchKeywordPlace = (
Expand Down Expand Up @@ -62,6 +71,7 @@ const TestMap = () => {
useEffect(() => {
if (!isExecuted) searchKeywordPlace(searchedPlaces, setSearchedPlaces);
console.log('filteredPlaces: ', searchedPlaces);
console.log('MapRef: ', mapRef.current);
}, [searchedPlaces]);

return (
Expand All @@ -71,6 +81,7 @@ const TestMap = () => {
center={currentPosition}
className="w-[500px] h-[500px]"
level={3}
ref={mapRef}
>
{/* <MapMarker
position={currentPosition}
Expand All @@ -82,6 +93,7 @@ const TestMap = () => {
}, // 마커이미지의 크기입니다
}}
title="현재 위치"
ref={markerRef}
/> */}
{/* Marker 표시 */}
{searchedPlaces.map((searchedPlace) => {
Expand Down
12 changes: 7 additions & 5 deletions src/pages/signUp/SignupInputForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,10 @@ const SignupInputForm = () => {
// 중복 확인이 되지 않았을 때
if (!emailConfirm.checked) {
alert('이메일 중복을 확인해주세요');
setIsLoading(false);
}
// 제대로 확인되었을 때
if (emailConfirm.isValid && passwordConfirm) {
if (emailConfirm.isValid && emailConfirm.checked) {
fetch(`${process.env.REACT_APP_URI}/account/shelter`, {
method: 'POST',
headers: {
Expand All @@ -151,10 +152,11 @@ const SignupInputForm = () => {
.then((data) => {
if (!data.success) {
alert(data.error.message); // 이 부분은 주소 받는 거 때문에 그냥 텍스트만 넣기 애매함
return;
} else {
navigate('/login');
}
navigate('/login');
});
setIsLoading(false);
}
};

Expand Down Expand Up @@ -189,8 +191,6 @@ const SignupInputForm = () => {
validationSchema
.validate(shelterInfo, { abortEarly: false })
.then(() => {
setIsLoading(true);
userfetch();
setErrors({});
})
.catch((err) => {
Expand Down Expand Up @@ -222,6 +222,8 @@ const SignupInputForm = () => {
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
validationCheck();
setIsLoading(true);
userfetch();
};

const SignupInputFormProps = {
Expand Down
20 changes: 10 additions & 10 deletions src/pages/signUp/VSignupInputForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ interface VSignupInputProps {

interface ValidationProps {
text?: string;
textColor?: string;
className: string;
}

const ValidateText = ({ text, textColor }: ValidationProps) => {
return text ? <div className={`text-${textColor}-500`}>{text}</div> : null;
const ValidateText = ({ text, className }: ValidationProps) => {
return text ? <div className={className}>{text}</div> : null;
};

const VSignupInputForm = ({
Expand All @@ -36,7 +36,7 @@ const VSignupInputForm = ({
}: VSignupInputProps) => {
return (
<form
className="flex flex-col gap-4 w-full max-w-[400px] px-2"
className="flex flex-col gap-3 w-full max-w-[400px] px-2"
onSubmit={handleSubmit}
>
<div className="email-confirm flex place-items-end justify-center">
Expand All @@ -56,9 +56,9 @@ const VSignupInputForm = ({
중복 확인
</button>
</div>
<ValidateText text={emailValidText} textColor={'green'} />
<ValidateText text={emailInValidText} textColor={'red'} />
<ValidateText text={errors.email} />
<ValidateText text={emailValidText} className={'text-green-500'} />
<ValidateText text={emailInValidText} className={'text-red-500'} />
<ValidateText text={errors.email} className={'text-red-500'} />
<InputGroup
id="password"
name="비밀번호"
Expand All @@ -67,7 +67,7 @@ const VSignupInputForm = ({
onChange={handleChange}
autocomplete="off"
/>
<ValidateText text={errors.password} />
<ValidateText text={errors.password} className={'text-red-500'} />
<InputGroup
id="password-confirm"
name="비밀번호 확인"
Expand All @@ -87,7 +87,7 @@ const VSignupInputForm = ({
onChange={handleChange}
autocomplete="off"
/>
<ValidateText text={errors.name} />
<ValidateText text={errors.name} className={'text-red-500'} />
<InputGroup
id="shelter-contact"
name="보호소 연락처"
Expand All @@ -96,7 +96,7 @@ const VSignupInputForm = ({
onChange={handleChange}
autocomplete="off"
/>
<ValidateText text={errors.contact} />
<ValidateText text={errors.contact} className={'text-red-500'} />
<AddressInputGroup />
<button className="bg-brand-color text-white w-full rounded-md p-2">
{isLoading ? (
Expand Down
2 changes: 1 addition & 1 deletion src/pages/signUp/VSignupPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const VSignupPage = ({ redirectLoginPage }: Props) => {
backgroundPosition: 'center',
}}
>
<div className="flex flex-row justify-between items-center gap-4 max-w-[400px] w-[100%]">
<div className="flex flex-row justify-between items-center gap-4 max-w-[400px] w-[100%] mt-4 mb-2">
<LogoButton
imageClassName="sm:w-8 md:w-8 lg:w-12"
logoClassName="sm:text-2xl md:text-2xl lg:text-3xl"
Expand Down

0 comments on commit d9eebc5

Please sign in to comment.