Skip to content

Commit

Permalink
Merge pull request #191 from KKangHHee/test
Browse files Browse the repository at this point in the history
Feat: 인증번호 전송 훅 분리
  • Loading branch information
choiyoubin authored Mar 24, 2024
2 parents 8db4556 + 65081a9 commit 4fb4468
Show file tree
Hide file tree
Showing 15 changed files with 378 additions and 272 deletions.
Original file line number Diff line number Diff line change
@@ -1,100 +1,85 @@
import { message } from "antd";
import axios from "axios";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import useFindId from "../../../../hooks/useFindId";
import useSendVerifySms from "../../../../hooks/useSendVerifySms";
import RedButton from "../../redButton/RedButton";
import CertificationNumInput from "../CertificationNumInput/CertificationNumInput";
import "./CertificationInput.css";
const TIMER_DURATION = 600; //타이머 시간 설정(600초)

// 아이디찾기 및 회원가입 번호인증에 사용
function CertificationInput({ type, buttonText }) {
const navigate = useNavigate();
const [inputNum, setInputNum] = useState(false); //전화번호 입력상태
const [chkButton, setChkButton] = useState(false); // 인증버튼 클릭 여부
const [hyphenPhonenumber, setHyphenPhonenumber] = useState(""); // 전화번호 상태
const [phonenumber, setPhonenumber] = useState(""); // 전화번호 상태
const [postmessage, setPostmessage] = useState(false); // 인증 번호 발송 성공 여부
const [verifyState, setVerifyState] = useState(false); //전화번호 인증 상태
const apiUrl = process.env.REACT_APP_API_ROOT;

const { handleSendVerifySms } = useSendVerifySms(); //번호인증
const { findIdResult } = useFindId();
const handleButtonClick = () => {
const PhoneNumber = hyphenPhonenumber.replace(/\D/g, "");
if (/^\d+$/.test(PhoneNumber) && PhoneNumber.length === 11) {
setInputNum(true);
handlePostmessage();
// 전체가 숫자인지, 000-0000-0000 총 11자리인지 확인
if (/^\d+$/.test(phonenumber) && phonenumber.length === 11) {
// 11자리 입력 후에
if (!postmessage) {
handlePostmessage();
} else {
//타이머 초기화용
setPostmessage(false);
handlePostmessage();
}
} else {
setInputNum(false);
setHyphenPhonenumber("");
setPhonenumber("");
message.info("전화번호를 올바르게 입력해주세요.");
}
};
const handlePostmessage = async () => {
const apiRoot = process.env.REACT_APP_API_ROOT;
const apiVer = "api/v1";
const apiUrl = `${apiRoot}/${apiVer}/sms/send`;
const PhoneNumber = hyphenPhonenumber.replace(/\D/g, "");
try {
const response = await axios.post(`${apiUrl}`, {
phoneNumber: PhoneNumber,
});
if (response.data.success) {
setChkButton(true);
message.success("인증 번호를 발송했습니다.");
} else {
message.error("인증 번호를 발송에 실패했습니다.");
console.log("아이디 찾기 인증번호 발송 실패:", response.data);
}
} catch (error) {
console.error(error);
message.error("인증 번호를 발송에 실패했습니다.");
}

// 인증 문자 발신 성공 여부 확인
const handlePostSuccess = (success) => {
setPostmessage(success);
};
// 번호 인증
const handlePostmessage = () => {
setChkButton(true);
handleSendVerifySms({
userPhonenumber: phonenumber,
onPostSuccess: handlePostSuccess,
});
};

// 아이디 찾기 결과
const handleFindIdClick = () => {
findIdResult({ userPhonenumber: phonenumber });
};

// 번호 인증 성공 여부 확인
const handleAuthSuccess = (success) => {
setVerifyState(success);
};
const renderCertificationNumInput = () => {
if (type === "tel" && chkButton && inputNum) {
if (type === "tel" && chkButton && postmessage) {
return (
<CertificationNumInput
phoneNumber={hyphenPhonenumber.replace(/\D/g, "")}
phoneNumber={phonenumber}
onAuthSuccess={handleAuthSuccess}
initialTimer={TIMER_DURATION}
/>
);
}
return null;
};

const handlePhoneChange = (event) => {
const HyphenNumber = event.target.value
.replace(/[^0-9]/g, "")
.replace(/(\d{3})(\d{1,4})(\d{1,4})/, "$1-$2-$3");
setHyphenPhonenumber(HyphenNumber);
const HyphenNumber = event.target.value.replace(/[^0-9]/g, "");
setPhonenumber(HyphenNumber);
};

const handleFindIdClick = async () => {
const PhoneNumber = hyphenPhonenumber.replace(/\D/g, "");
try {
const response = await axios.post(`${apiUrl}/api/v1/ceo/find/email`, {
phoneNumber: PhoneNumber,
});
console.log(response);

if (response.data.success) {
console.log(response.data.message);
navigate("/find/id/search", {
state: { message: response.data.message },
});
}
} catch (error) {
// 404에러 처리(사용자 id가 db에 없을 경우)
if (axios.isAxiosError(error)) {
if (error.response && error.response.status === 404) {
navigate("/find/id/none");
}
}
// 다른 오류 처리
else {
message.error("아이디 조회 요청에 실패했습니다.");
}
const displayFormattedPhoneNumber = (numbers) => {
if (numbers.length <= 3) {
return numbers;
} else if (numbers.length <= 7) {
return `${numbers.slice(0, 3)}-${numbers.slice(3)}`;
} else {
return `${numbers.slice(0, 3)}-${numbers.slice(3, 7)}-${numbers.slice(
7
)}`;
}
};

Expand All @@ -114,7 +99,7 @@ function CertificationInput({ type, buttonText }) {
inputmode="numeric"
pattern="[0-9]*"
placeholder="전화번호"
value={hyphenPhonenumber}
value={displayFormattedPhoneNumber(phonenumber)}
onChange={handlePhoneChange}
maxLength="13"
className="loginpage-findId-input"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,23 @@
import axios from "axios";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import useTimer from "../../../../hooks/useTimer";
import LoginChkAlrm from "../../LoginChkAlrm/LoginChkAlrm";
import "./CertificationInputCheck.css";

// const AUTH_CODE = "1234";//서버에서 받아오는 값
const TIMER_DURATION = 600; //타이머 시간 설정(600초)

const Timer = ({ minutes, seconds }) => (
<div className="timer">
{minutes}:{seconds < 10 ? `0${seconds}` : seconds}
</div>
);
// 비밀번호 변경 번호 인증_인증번호 확인
// 추후 아이디 찾기 및 회원가입 번호인증과 비교 후 수정 필요
function CertificationInputCheck({ phoneNumber, onAuthSuccess }) {
function CertificationInputCheck({ phoneNumber, onAuthSuccess, initialTimer }) {
const [chkNum, setChkNum] = useState("");
const [timer, setTimer] = useState(TIMER_DURATION);
const { timer } = useTimer(initialTimer);
const [isAuth, setIsAuth] = useState();
const apiUrl = process.env.REACT_APP_API_ROOT;

useEffect(() => {
const interval = setInterval(() => {
setTimer((prevTimer) => prevTimer - 1);
}, 1000);

return () => clearInterval(interval);
}, [setTimer]);

const handleInputText = async (e) => {
const apiUrl = process.env.REACT_APP_API_ROOT;
const newChkNum = e.target.value;
setChkNum(newChkNum);
if (newChkNum.length === 6) {
Expand All @@ -46,12 +36,15 @@ function CertificationInputCheck({ phoneNumber, onAuthSuccess }) {
onAuthSuccess(true);
} else {
console.log("인증실패", response.data);
onAuthSuccess(true);
onAuthSuccess(false);
setIsAuth(false);
}
} catch (error) {
console.log("통신에러", error);
}
} else {
onAuthSuccess(false);
setIsAuth(false);
}
};

Expand Down Expand Up @@ -85,6 +78,7 @@ function CertificationInputCheck({ phoneNumber, onAuthSuccess }) {
type="text"
placeholder="인증번호"
value={chkNum}
maxLength="6"
autocomplete="off" //자동완성 없애기
onChange={handleInputText}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,92 +1,83 @@
import { message } from "antd";
import axios from "axios";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useSetRecoilState } from "recoil";
import { getPhoneNumber } from "../../../../Atom/status";
import useSendPasswordVerifySms from "../../../../hooks/useSendPasswordVerifySms";
import RedButton from "../../redButton/RedButton";
import "../CertificationInput/CertificationInput.css";
import CertificationInputCheck from "./CertificationInputCheck";

const TIMER_DURATION = 600; //타이머 시간 설정(600초)

// 비밀번호 변경 번호 인증_번호입력
// 추후 아이디 찾기 및 회원가입 번호인증과 비교 후 수정 필요
function CertificationInputPhoneNumber(userInfo) {
const navigate = useNavigate();
const [inputNum, setInputNum] = useState(false); //전화번호 입력상태
const [chkButton, setChkButton] = useState(false); // 인증버튼 클릭 여부
const [hyphenPhonenumber, setHyphenPhonenumber] = useState(""); // 전화번호 상태
const [phonenumber, setPhonenumber] = useState(""); // 전화번호 상태
const [postmessage, setPostmessage] = useState(false); // 인증 번호 발송 성공 여부
const [verifyState, setVerifyState] = useState(false); //전화번호 인증 상태
const setPhoneNumberState = useSetRecoilState(getPhoneNumber);
const { handleSendPasswordVerifySms } = useSendPasswordVerifySms();
const handleButtonClick = () => {
// 전체가 숫자인지, 000-0000-0000 총 11자리인지 확인
const PhoneNumber = hyphenPhonenumber.replace(/\D/g, "");
if (/^\d+$/.test(PhoneNumber) && PhoneNumber.length === 11) {
setInputNum(true);
handlePostmessage();
if (/^\d+$/.test(phonenumber) && phonenumber.length === 11) {
// 11자리 입력 후에
if (!postmessage) {
handlePostmessage();
} else { //타이머 초기화용
setPostmessage(false);
handlePostmessage();
}
} else {
setInputNum(false);
setHyphenPhonenumber("");
setPhonenumber("");
message.info("전화번호를 올바르게 입력해주세요.");
}
};
const handlePostmessage = async () => {
const apiRoot = process.env.REACT_APP_API_ROOT;
const apiVer = "api/v1";
const apiUrl = `${apiRoot}/${apiVer}/sms/send/find-email`;
const PhoneNumber = hyphenPhonenumber.replace(/\D/g, "");
try {
setChkButton(true);
const response = await axios.post(`${apiUrl}`, {
email: userInfo.userEmail,
phoneNumber: PhoneNumber,
name: userInfo.userName,
});
console.log(response);

if (response.data.success) {
message.success("인증번호가 발송되었습니다.");
setPhoneNumberState({
phoneNumber: PhoneNumber,
});
setPostmessage(true);
} else {
console.log("인증번호 발송 실패:", response.data);
}
} catch (error) {
console.error(error);
// 올바르지 않은 유저정보 전송 시,
if (axios.isAxiosError(error)) {
if (error.response && error.response.status === 400) {
message.error("올바른 정보를 입력해주세요.");
}
}
// 다른 오류 처리
else {
message.error("인증 번호 전송이 실패했습니다.");
}
}
const handlePostSuccess = (success) => {
setPostmessage(success);
};

const handlePostmessage = () => {
setChkButton(true);
handleSendPasswordVerifySms({
userPhonenumber: phonenumber,
onPostSuccess: handlePostSuccess,
info: userInfo,
});
};

const handleAuthSuccess = (success) => {
setVerifyState(success);
};
const renderCertificationNumInput = () => {
return (
<CertificationInputCheck
phoneNumber={hyphenPhonenumber.replace(/\D/g, "")}
onAuthSuccess={handleAuthSuccess}
/>
);
if (postmessage) {
return (
<CertificationInputCheck
phoneNumber={phonenumber}
onAuthSuccess={handleAuthSuccess}
initialTimer={TIMER_DURATION}
/>
);
}
return null;
};

const handlePhoneChange = (event) => {
const HyphenNumber = event.target.value
.replace(/[^0-9]/g, "")
.replace(/(\d{3})(\d{1,4})(\d{1,4})/, "$1-$2-$3");
setHyphenPhonenumber(HyphenNumber);
const HyphenNumber = event.target.value.replace(/[^0-9]/g, "");
setPhonenumber(HyphenNumber);
};
// 전화번호 입력에 '-' 넣는 함수
const displayFormattedPhoneNumber = (numbers) => {
if (numbers.length <= 3) {
return numbers;
} else if (numbers.length <= 7) {
return `${numbers.slice(0, 3)}-${numbers.slice(3)}`;
} else {
return `${numbers.slice(0, 3)}-${numbers.slice(3, 7)}-${numbers.slice(
7
)}`;
}
};

// 인증성공 시,
const handleFindClick = () => {
if (verifyState) {
Expand All @@ -100,11 +91,11 @@ function CertificationInputPhoneNumber(userInfo) {
<>
<div className="loginpage-find-form-input-div">
<input
type="tel"
inputmode="numeric"
pattern="[0-9]*"
type="tel"
inputmode="numeric"
pattern="[0-9]*"
placeholder="전화번호"
value={hyphenPhonenumber}
value={displayFormattedPhoneNumber(phonenumber)}
maxLength="13"
onChange={handlePhoneChange}
className="loginpage-findId-input"
Expand All @@ -120,7 +111,7 @@ function CertificationInputPhoneNumber(userInfo) {
</button>
</div>

{postmessage && inputNum && renderCertificationNumInput()}
{renderCertificationNumInput()}

<div className="loginpage-form-submit-button-position">
<RedButton type="submit" onClick={handleFindClick}>
Expand Down
Loading

0 comments on commit 4fb4468

Please sign in to comment.