Commit 3c31b22f authored by 한규민's avatar 한규민
Browse files

디버그, 전체 수정 해결

parent 731cc282
/node_modules /node_modules
.env.development .env.development
.env .env
./upload upload/
\ No newline at end of file \ No newline at end of file
...@@ -14,14 +14,14 @@ const login = async (login) => { ...@@ -14,14 +14,14 @@ const login = async (login) => {
}; };
const logout = async () => { const logout = async () => {
alert("로그아웃되었습니다.");
const { data } = await axios.get(`${baseUrl}/api/auth/logout`); const { data } = await axios.get(`${baseUrl}/api/auth/logout`);
return data return data
}; };
const signup = async (user) => { const signup = async (user) => {
const url = `${baseUrl}/api/auth/signup` const url = `${baseUrl}/api/auth/signup`;
await axios.post(url, user) const { data } = await axios.post(url, user);
return data
} }
const compareId = async (userId) => { const compareId = async (userId) => {
......
...@@ -42,8 +42,12 @@ const Login = () => { ...@@ -42,8 +42,12 @@ const Login = () => {
const requestServer = async (data) => { const requestServer = async (data) => {
if(data === user){ if(data === user){
await login(data); const success = await login(data);
}else{ if(success){
setSuccess(true);
alert('로그인이 완료되었습니다.')
}
}else{
} }
} }
...@@ -51,11 +55,8 @@ const Login = () => { ...@@ -51,11 +55,8 @@ const Login = () => {
e.preventDefault(); e.preventDefault();
try { try {
setError(""); setError("");
console.log(e.target.name);
if (e.target.name === "login") { if (e.target.name === "login") {
requestServer(user); requestServer(user);
alert('로그인이 완료되었습니다.')
setSuccess(true);
} }
else { else {
requestServer(guest); requestServer(guest);
......
...@@ -42,7 +42,6 @@ const MyInfo = () => { ...@@ -42,7 +42,6 @@ const MyInfo = () => {
errorNickName: false, errorNickName: false,
errorMbnum: false, errorMbnum: false,
errorPassword: false, errorPassword: false,
errorRePassword: false
}) })
useEffect(() => { useEffect(() => {
...@@ -83,7 +82,6 @@ const MyInfo = () => { ...@@ -83,7 +82,6 @@ const MyInfo = () => {
const formData = new FormData(); const formData = new FormData();
formData.append("image", img); formData.append("image", img);
const image = await authApi.profile(formData); const image = await authApi.profile(formData);
console.log(image.img);
setProfile(image.img); setProfile(image.img);
} catch (error) { } catch (error) {
catchErrors(error, setError); catchErrors(error, setError);
...@@ -97,7 +95,6 @@ const MyInfo = () => { ...@@ -97,7 +95,6 @@ const MyInfo = () => {
setLoading(() => (true)); setLoading(() => (true));
const pw = presentPw; const pw = presentPw;
const confirmPw = await authApi.comparePw(pw); const confirmPw = await authApi.comparePw(pw);
console.log("confirmPw : "+ confirmPw);
if (confirmPw) { if (confirmPw) {
setPage(false); setPage(false);
} else { } else {
...@@ -117,12 +114,9 @@ const MyInfo = () => { ...@@ -117,12 +114,9 @@ const MyInfo = () => {
setError(""); setError("");
setLoading(true); setLoading(true);
const phone = userRe.userMbnum; const phone = userRe.userMbnum;
console.log("phone : ", phone);
const message = await authApi.confirmMbnum(phone); const message = await authApi.confirmMbnum(phone);
console.log("message : ", message);
if(message.isSuccess){ if(message.isSuccess){
console.log("mberror: "+mbError);
setMbError("보냄"); setMbError("보냄");
setStartTime(message.startTime); setStartTime(message.startTime);
} }
...@@ -142,11 +136,8 @@ const MyInfo = () => { ...@@ -142,11 +136,8 @@ const MyInfo = () => {
try { try {
setError(""); setError("");
setLoading(true); setLoading(true);
console.log("startTime : ", startTime);
const confirmNum = {userMbnum : userRe.userMbnum, number : number, startTime : startTime}; const confirmNum = {userMbnum : userRe.userMbnum, number : number, startTime : startTime};
console.log(confirmNum);
const message = await authApi.confirmNum(confirmNum); const message = await authApi.confirmNum(confirmNum);
console.log(message);
setMbError(message); setMbError(message);
if(message === "성공"){ if(message === "성공"){
setConfirmMb(true); setConfirmMb(true);
...@@ -159,63 +150,30 @@ const MyInfo = () => { ...@@ -159,63 +150,30 @@ const MyInfo = () => {
} }
} }
//비교하여 error메세지 반환 const validationPw = () => {
const vaildationData = (text, compareValue, error) => { if(userRe.userPassword !== userRe.userRePassword){
if (text !== compareValue) { return false;
setErrorMsg(errorMsg => ({ ...errorMsg, [error]: true })); }else{return true;}
} else {
setErrorMsg(errorMsg => ({ ...errorMsg, [error]: false }));
}
}
const vaildationIdPw = (text, minValue, error) => {
if ((text < minValue)) {
setErrorMsg(errorMsg => ({ ...errorMsg, [error]: true }));
} else {
setErrorMsg(errorMsg => ({ ...errorMsg, [error]: false }));
}
} }
//유효성 검사
const validation = () => {
//이름 유효성 검사
vaildationData((userRe.userName.length === 0), false, "errorName");
//별명 유효성 검사
vaildationData((userRe.userNickName.length === 0), false, "errorNickName");
// 휴대폰 유효성 검사
vaildationData(userRe.userMbnum.length, 11, "errorMbnum");
// 비밀번호 유효성 검사
vaildationIdPw(userRe.userPassword.length, 8, "errorPassword");
// 비밀번호 확인 유효성 검사
vaildationData(userRe.userPassword, userRe.userRePassword, "errorRePassword");
// 최종 유효성 검사
if (!(Object.values(errorMsg).some((element) => (element)))) {
return true
} else {
return false
}
}
const handleOnSummit = async (e) => { const handleOnSummit = async (e) => {
e.preventDefault(); e.preventDefault();
try { try {
console.log('handle ?????')
setError(() => ("")); setError(() => (""));
//처리가 될때까지 버튼(가입하기)이 안눌리게 지정 //처리가 될때까지 버튼(가입하기)이 안눌리게 지정
setLoading(() => (true)); setLoading(() => (true));
//유효성 검사 let validPw = validationPw();
let valid = validation(); if(validPw){
console.log('handle on submit', valid)
if (valid) {
const userData = userRe; const userData = userRe;
console.log(userData);
//서버로 전송 //서버로 전송
const result = await authApi.modifyUser(userData); const error = await authApi.modifyUser(userData);
console.log("result : " + result); setErrorMsg(error);
alert("회원정보 수정 완료"); if(error === "성공"){
valid = false; alert("회원정보 수정 완료");
} else { throw new Error("유효하지 않은 데이터입니다.") } }
}else{
throw new Error("비밀번호가 일치하지 않습니다.");
}
} catch (error) { } catch (error) {
//에러전송 //에러전송
catchErrors(error, setError); catchErrors(error, setError);
...@@ -237,7 +195,7 @@ const MyInfo = () => { ...@@ -237,7 +195,7 @@ const MyInfo = () => {
<div className="d-flex justify-content-around"> <div className="d-flex justify-content-around">
<div className={`${styles.box} me-5`}> <div className={`${styles.box} me-5`}>
<p className={`${styles.hoverTxt}`}>프로필 변경</p> <p className={`${styles.hoverTxt}`}>프로필 변경</p>
<img src={`/upload/${profile}`} className={`figure-img img-fluid rounded-circle ${styles.profile}`} role="button" data-bs-toggle="modal" data-bs-target="#staticBackdrop" /> <img src={`/upload/${profile}`} className={`figure-img img-fluid rounded-circle ${styles.img} ${styles.profile}`} role="button" data-bs-toggle="modal" data-bs-target="#staticBackdrop" />
</div> </div>
<div className="d-flex flex-column py-4 justify-content-around"> <div className="d-flex flex-column py-4 justify-content-around">
<span className={`${styles.userName}`}>{`${userNickName}`} 반갑습니다!</span> <span className={`${styles.userName}`}>{`${userNickName}`} 반갑습니다!</span>
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
font-size: 3rem; font-size: 3rem;
margin: 2rem 0; margin: 2rem 0;
} }
img{ .img{
width: 40%; width: 40%;
} }
......
...@@ -3,7 +3,6 @@ import { Link } from "react-router-dom"; ...@@ -3,7 +3,6 @@ import { Link } from "react-router-dom";
import { useAuth } from "../../context/auth_context.js" import { useAuth } from "../../context/auth_context.js"
const SubNav = () => { const SubNav = () => {
const { user, setUser, logout } = useAuth(); const { user, setUser, logout } = useAuth();
console.log("user : ", user);
return ( return (
<> {(user.role !== "user") ? <> {(user.role !== "user") ?
......
...@@ -7,16 +7,16 @@ const ReservationDetails = () => { ...@@ -7,16 +7,16 @@ const ReservationDetails = () => {
<div className={`${styles.body}`}> <div className={`${styles.body}`}>
<div className={`d-flex justify-content-around align-items-center py-3`}> <div className={`d-flex justify-content-around align-items-center py-3`}>
<div className={`${styles.span} d-flex justify-content-center`}> <div className={`${styles.span} d-flex justify-content-center`}>
<span>영화 포스터</span> <span className={`${styles.layout}`}>영화 포스터</span>
</div> </div>
<div className={`${styles.span} d-flex flex-column`}> <div className={`${styles.span} d-flex flex-column`}>
<span>영화제목</span> <span className={`${styles.layout}`}>영화제목</span>
<span>예매확인번호</span> <span className={`${styles.layout}`}>예매확인번호</span>
<span>예매날짜</span> <span className={`${styles.layout}`}>예매날짜</span>
<span>상영관</span> <span className={`${styles.layout}`}>상영관</span>
<span>좌석정보</span> <span className={`${styles.layout}`}>좌석정보</span>
<span>결제금액</span> <span className={`${styles.layout}`}>결제금액</span>
<span>결제수단</span> <span className={`${styles.layout}`}>결제수단</span>
</div> </div>
</div> </div>
</div> </div>
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
border-bottom: 1px solid #FEDC00; border-bottom: 1px solid #FEDC00;
} }
.span span{ .span .layout{
color:white; color:white;
font-size: 1.5rem; font-size: 1.5rem;
} }
\ No newline at end of file
...@@ -30,7 +30,6 @@ const Signup = () => { ...@@ -30,7 +30,6 @@ const Signup = () => {
errorBirthday: false, errorBirthday: false,
errorMbnum: false, errorMbnum: false,
errorPassword: false, errorPassword: false,
errorRePassword: false
}) })
// id중복확인 여부 state와 가입하기 누르면 id 임시 저장 // id중복확인 여부 state와 가입하기 누르면 id 임시 저장
const [overlapId, setOverlapId] = useState(false); const [overlapId, setOverlapId] = useState(false);
...@@ -66,8 +65,8 @@ const Signup = () => { ...@@ -66,8 +65,8 @@ const Signup = () => {
}; };
} else { } else {
const userId = user.userId; const userId = user.userId;
await authApi.compareId(userId); const overlapId = await authApi.compareId(userId);
if (!await authApi.compareId(userId)) { if (!overlapId) {
alert("이 아이디는 사용가능합니다.") alert("이 아이디는 사용가능합니다.")
setErrorMsg(errorMsg => ({ setErrorMsg(errorMsg => ({
...errorMsg, ...errorMsg,
...@@ -93,14 +92,10 @@ const Signup = () => { ...@@ -93,14 +92,10 @@ const Signup = () => {
setError(""); setError("");
setLoading(true) setLoading(true)
const phone = user.userMbnum; const phone = user.userMbnum;
console.log("phone : ", phone);
const message = await authApi.confirmMbnum(phone); const message = await authApi.confirmMbnum(phone);
console.log("message : ", message);
if(message.isSuccess){ if(message.isSuccess){
console.log("mberror: "+mbError);
setMbError("보냄"); setMbError("보냄");
setStartTime(message.startTime); setStartTime(message.startTime);
} }
} catch (error) { } catch (error) {
console.log('error'+ error) console.log('error'+ error)
...@@ -118,11 +113,8 @@ const Signup = () => { ...@@ -118,11 +113,8 @@ const Signup = () => {
try { try {
setError(""); setError("");
setLoading(true); setLoading(true);
console.log("startTime : ", startTime);
const confirmNum = {userMbnum : user.userMbnum, number : number, startTime : startTime}; const confirmNum = {userMbnum : user.userMbnum, number : number, startTime : startTime};
console.log(confirmNum);
const message = await authApi.confirmNum(confirmNum); const message = await authApi.confirmNum(confirmNum);
console.log(message);
setMbError(message); setMbError(message);
if(message === "성공"){ if(message === "성공"){
setConfirmMb(true); setConfirmMb(true);
...@@ -134,9 +126,11 @@ const Signup = () => { ...@@ -134,9 +126,11 @@ const Signup = () => {
setLoading(false); setLoading(false);
} }
} }
const validationPw = () => {
if(user.userPassword !== user.userRePassword){
return false;
}else{return true;}
}
const handleOnSummit = async (e) => { const handleOnSummit = async (e) => {
e.preventDefault(); e.preventDefault();
...@@ -144,13 +138,18 @@ const Signup = () => { ...@@ -144,13 +138,18 @@ const Signup = () => {
setError(() => ("")); setError(() => (""));
//처리가 될때까지 버튼(가입하기)이 안눌리게 지정 //처리가 될때까지 버튼(가입하기)이 안눌리게 지정
setLoading(() => (true)); setLoading(() => (true));
//유효성 검사 let validPw = validationPw();
validation(); if(validPw){
const userData = user; const userData = user;
//서버로 전송 //서버로 전송
await authApi.signup(userData) const error = await authApi.signup(userData);
alert("가입이 완료되었습니다. 로그인 해주세요."); setErrorMsg(error);
setSuccess(true); if(error === "성공"){
setSuccess(true);
}
}else{
throw new Error("비밀번호가 일치하지 않습니다.");
}
} catch (error) { } catch (error) {
//에러전송 //에러전송
catchErrors(error, setError); catchErrors(error, setError);
...@@ -159,69 +158,10 @@ const Signup = () => { ...@@ -159,69 +158,10 @@ const Signup = () => {
} }
} }
//비교하여 error메세지 반환 if(success){
const vaildationData = (text, compareValue, error) => {
if (text !== compareValue) {
setErrorMsg(errorMsg => ({ ...errorMsg, [error]: true }));
} else {
setErrorMsg(errorMsg => ({ ...errorMsg, [error]: false }));
}
}
//아이디 비번 유효성 검사
const vaildationIdPw = (text, minValue, error) => {
if ((text < minValue)) {
setErrorMsg(errorMsg => ({ ...errorMsg, [error]: true }));
} else if (text >= minValue) {
setErrorMsg(errorMsg => ({ ...errorMsg, [error]: false }));
if (overlapId === true) {
if (preId !== user.userId) {
setOverlapId(false);
}
}
}
}
//유효성 검사
const validation = () => {
setPreId(user.userId);
//아이디 유효성 검사
vaildationIdPw(user.userId.length, 5, "errorId");
//이름 유효성 검사
vaildationData((user.userName.length === 0), false, "errorName");
//별명 유효성 검사
vaildationData((user.userNickName.length === 0), false, "errorNickName");
// 생일 유효성 검사
vaildationData(user.userBirthday.length, 6, "errorBirthday");
// 휴대폰 유효성 검사
vaildationData(user.userMbnum.length, 11, "errorMbnum");
// 비밀번호 유효성 검사
vaildationIdPw(user.userPassword.length, 8, "errorPassword");
// 비밀번호 확인 유효성 검사
vaildationData(user.userRePassword, user.userPassword, "errorRePassword");
let validation = false;
validation = (Object.values(errorMsg).some((element) => (element)) === false);
// 최종 유효성 검사
if (overlapId) {
if(confirmMb){
if(!validation){
throw new Error("유효하지 않은 데이터입니다.");
}else{
console.log("가입성공");
return true
}
}else{
throw new Error("휴대폰 인증도 해주세요");
}
}else{
setErrorMsg(errorMsg => ({ ...errorMsg, errorId: false }));
throw new Error("먼저 아이디 중복확인을 해주세요");
}
}
if (success) {
return <Redirect to="/login" />; return <Redirect to="/login" />;
} }
return ( return (
// 데이터 입력과 유효성 검사 후 보이는 경고창 // 데이터 입력과 유효성 검사 후 보이는 경고창
<form className={`d-flex col-md-6 col-12 justify-content-center`} onSubmit={handleOnSummit}> <form className={`d-flex col-md-6 col-12 justify-content-center`} onSubmit={handleOnSummit}>
...@@ -231,7 +171,7 @@ const Signup = () => { ...@@ -231,7 +171,7 @@ const Signup = () => {
<div className={styles.inputContent}> <div className={styles.inputContent}>
<label className={styles.signupLabel}>아이디</label> <label className={styles.signupLabel}>아이디</label>
<div className="d-flex col-md-auto"> <div className="d-flex col-md-auto">
<input className={styles.input} type="text" name="userId" placeholder="5~10자리 사이" onChange={handleUserOnChange} maxLength="10" required /> <input className={styles.input} type="text" name="userId" placeholder="5~10자리 사이" onChange={handleUserOnChange} maxLength="20" required />
<button type="button" disabled={loading} name="errorId" className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} onClick={handleOnClickId}>중복확인</button> <button type="button" disabled={loading} name="errorId" className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} onClick={handleOnClickId}>중복확인</button>
</div> </div>
</div> </div>
...@@ -242,21 +182,21 @@ const Signup = () => { ...@@ -242,21 +182,21 @@ const Signup = () => {
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<div className={styles.inputContent}> <div className={styles.inputContent}>
<label className={styles.signupLabel}>이름</label> <label className={styles.signupLabel}>이름</label>
<input className={`${styles.input} ${styles.inputSize}`} type="text" name="userName" placeholder="이름을 입력해주세요" onChange={handleUserOnChange} maxlength="10" required /> <input className={`${styles.input} ${styles.inputSize}`} type="text" name="userName" placeholder="이름을 입력해주세요" onChange={handleUserOnChange} maxLength="20" required />
</div> </div>
{errorMsg.errorName && <p className={styles.passwordConfirmError}>이름을 입력해주세요</p>} {errorMsg.errorName && <p className={styles.passwordConfirmError}>이름을 입력해주세요</p>}
</div> </div>
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<div className={styles.inputContent}> <div className={styles.inputContent}>
<label className={styles.signupLabel}>이메일</label> <label className={styles.signupLabel}>이메일</label>
<input className={`${styles.input} ${styles.inputSize}`} type="email" name="userEmail" placeholder="이메일을 입력해주세요" onChange={handleUserOnChange} maxlength="20" required /> <input className={`${styles.input} ${styles.inputSize}`} type="email" name="userEmail" placeholder="이메일을 입력해주세요" onChange={handleUserOnChange} maxLength="20" required />
</div> </div>
{errorMsg.errorEmail && <p className={styles.passwordConfirmError}>이메일을 입력해주세요</p>} {errorMsg.errorEmail && <p className={styles.passwordConfirmError}>이메일을 입력해주세요</p>}
</div> </div>
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<div className={styles.inputContent}> <div className={styles.inputContent}>
<label className={styles.signupLabel}>별명</label> <label className={styles.signupLabel}>별명</label>
<input className={`${styles.input} ${styles.inputSize}`} type="text" name="userNickName" placeholder="10자리 이내" onChange={handleUserOnChange} maxLength="10" required /> <input className={`${styles.input} ${styles.inputSize}`} type="text" name="userNickName" placeholder="10자리 이내" onChange={handleUserOnChange} maxLength="20" required />
</div> </div>
{errorMsg.errorNickName && <p className={styles.passwordConfirmError}>10 이내로 입력해주세요.</p>} {errorMsg.errorNickName && <p className={styles.passwordConfirmError}>10 이내로 입력해주세요.</p>}
</div> </div>
...@@ -273,7 +213,7 @@ const Signup = () => { ...@@ -273,7 +213,7 @@ const Signup = () => {
<div className={styles.inputContent}> <div className={styles.inputContent}>
<label className={styles.signupLabel}>휴대폰 번호</label> <label className={styles.signupLabel}>휴대폰 번호</label>
<div className="d-flex col-md-auto"> <div className="d-flex col-md-auto">
<input className={`${styles.input} ${styles.input2}`} type="number" name="userMbnum" placeholder="-없이 11자리 입력" onChange={handleUserOnChange} min="" max="99999999999" required /> <input className={`${styles.input} ${styles.input2}`} type="number" name="userMbnum" placeholder="-없이 11자리 입력" onChange={handleUserOnChange} min="0" max="99999999999" required />
<button type="button" disabled={loading} className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample" onClick={handleOnClickMbnum}>인증번호받기</button> <button type="button" disabled={loading} className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample" onClick={handleOnClickMbnum}>인증번호받기</button>
</div> </div>
</div> </div>
...@@ -299,17 +239,14 @@ const Signup = () => { ...@@ -299,17 +239,14 @@ const Signup = () => {
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<div className={`${styles.inputContent}`}> <div className={`${styles.inputContent}`}>
<label className={styles.signupLabel}>비밀번호</label> <label className={styles.signupLabel}>비밀번호</label>
<input className={`${styles.input} ${styles.inputSize}`} type="password" name="userPassword" placeholder="8~11자리 사이" onChange={handleUserOnChange} maxLength="11" required /> <input className={`${styles.input} ${styles.inputSize}`} type="password" name="userPassword" placeholder="8~11자리 사이" onChange={handleUserOnChange} maxLength="20" required />
</div> </div>
{errorMsg.errorPassword && <p className={styles.passwordConfirmError}>8~11자리 사이로 입력해주세요.</p>} {errorMsg.errorPassword && <p className={styles.passwordConfirmError}>8~11자리 사이로 입력해주세요.</p>}
</div> </div>
<div className="d-flex flex-column"> <div className={`d-flex ${styles.inputContent}`}>
<div className={styles.inputContent}> <label className={styles.signupLabel}>비밀번호 확인</label>
<label className={styles.signupLabel}>비밀번호 확인</label> <input className={`${styles.input} ${styles.inputSize}`} type="password" name="userRePassword" placeholder="8~11자리 사이" onChange={handleUserOnChange} maxLength="20" required />
<input className={`${styles.input} ${styles.inputSize}`} type="password" name="userRePassword" placeholder="8~11자리 사이" onChange={handleUserOnChange} maxLength="11" required />
</div>
{errorMsg.errorRePassword && <p className={styles.passwordConfirmError}>비밀번호가 일치하지 않습니다.</p>}
</div> </div>
<button className={`rounded my-3 py-2 fs-5 ${styles.butterYellowAndBtn} ${styles.btnHover}`} type="submit" disabled={loading}>가입하기</button> <button className={`rounded my-3 py-2 fs-5 ${styles.butterYellowAndBtn} ${styles.btnHover}`} type="submit" disabled={loading}>가입하기</button>
......
...@@ -33,7 +33,6 @@ const AuthProvider = ({ children }) => { ...@@ -33,7 +33,6 @@ const AuthProvider = ({ children }) => {
setError(""); setError("");
setLoading(true); setLoading(true);
const user = await authApi.login(id, password); const user = await authApi.login(id, password);
console.log("user : ", user);
setUser(user); setUser(user);
return true; return true;
} catch (error) { } catch (error) {
......
...@@ -1544,6 +1544,11 @@ ...@@ -1544,6 +1544,11 @@
"requires": { "requires": {
"lru-cache": "^6.0.0" "lru-cache": "^6.0.0"
} }
},
"validator": {
"version": "10.11.0",
"resolved": "https://registry.npmjs.org/validator/-/validator-10.11.0.tgz",
"integrity": "sha512-X/p3UZerAIsbBfN/IwahhYaBbY68EN/UQBWHtsbXGT5bfrH/p4NQzUCG1kF/rtKaNpnJ7jAu6NGTdSNtyNIXMw=="
} }
} }
}, },
...@@ -1829,9 +1834,9 @@ ...@@ -1829,9 +1834,9 @@
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
}, },
"validator": { "validator": {
"version": "10.11.0", "version": "13.6.0",
"resolved": "https://registry.npmjs.org/validator/-/validator-10.11.0.tgz", "resolved": "https://registry.npmjs.org/validator/-/validator-13.6.0.tgz",
"integrity": "sha512-X/p3UZerAIsbBfN/IwahhYaBbY68EN/UQBWHtsbXGT5bfrH/p4NQzUCG1kF/rtKaNpnJ7jAu6NGTdSNtyNIXMw==" "integrity": "sha512-gVgKbdbHgtxpRyR8K0O6oFZPhhB5tT1jeEHZR0Znr9Svg03U0+r9DXWMrnRAB+HtCStDQKlaIZm42tVsVjqtjg=="
}, },
"vary": { "vary": {
"version": "1.1.2", "version": "1.1.2",
......
...@@ -28,7 +28,8 @@ ...@@ -28,7 +28,8 @@
"nodemailer": "^6.6.3", "nodemailer": "^6.6.3",
"pg": "^8.6.0", "pg": "^8.6.0",
"pg-hstore": "^2.3.4", "pg-hstore": "^2.3.4",
"sequelize": "^6.6.4" "sequelize": "^6.6.4",
"validator": "^13.6.0"
}, },
"devDependencies": { "devDependencies": {
"nodemon": "^2.0.12" "nodemon": "^2.0.12"
......
...@@ -11,7 +11,6 @@ const findReservation = async (req,res) => { ...@@ -11,7 +11,6 @@ const findReservation = async (req,res) => {
timetable:timetable timetable:timetable
} }
}) })
console.log(reservedSeats)
res.json(reservedSeats) res.json(reservedSeats)
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "이미 예매되어있는 좌석을 찾는 중 오류발생") return res.status(500).send(error.message || "이미 예매되어있는 좌석을 찾는 중 오류발생")
......
...@@ -3,8 +3,7 @@ import config from "../config/app.config.js"; ...@@ -3,8 +3,7 @@ import config from "../config/app.config.js";
import { User, Role, ConfirmNum } from '../db/index.js'; import { User, Role, ConfirmNum } from '../db/index.js';
import fs from "fs"; import fs from "fs";
import CryptoJS from "crypto-js"; import CryptoJS from "crypto-js";
import axios from "axios"; import validator from "validator";
const getUser = async (req, res) => { const getUser = async (req, res) => {
try { try {
...@@ -41,7 +40,6 @@ const login = async (req, res) => { ...@@ -41,7 +40,6 @@ const login = async (req, res) => {
const token = jwt.sign(signData, config.jwtSecret, { const token = jwt.sign(signData, config.jwtSecret, {
expiresIn: config.jwtExpires, expiresIn: config.jwtExpires,
}); });
console.log(token);
// 4) 토큰을 쿠키에 저장 // 4) 토큰을 쿠키에 저장
res.cookie(config.cookieName, token, { res.cookie(config.cookieName, token, {
maxAge: config.cookieMaxAge, maxAge: config.cookieMaxAge,
...@@ -83,7 +81,7 @@ const compareId = async (req, res) => { ...@@ -83,7 +81,7 @@ const compareId = async (req, res) => {
try { try {
const id = req.params.userId; const id = req.params.userId;
const userid = await User.findOne({ where: { userId: id } }); const userid = await User.findOne({ where: { userId: id } });
if (userid !== null) { if (userid) {
return res.json(true); return res.json(true);
} else { } else {
return res.json(false); return res.json(false);
...@@ -129,14 +127,12 @@ const confirmMbnum = async (req, res) => { ...@@ -129,14 +127,12 @@ const confirmMbnum = async (req, res) => {
try { try {
const phoneNumber = req.params.phone; const phoneNumber = req.params.phone;
console.log(phoneNumber);
//인증번호 생성 //인증번호 생성
const verifyCode = Math.floor(Math.random() * (999999 - 100000)) + 100000; const verifyCode = Math.floor(Math.random() * (999999 - 100000)) + 100000;
console.log("verifyCode : ",verifyCode); console.log("verifyCode : ", verifyCode);
let today = new Date(); let today = new Date();
let time = String(today.getTime()); let time = String(today.getTime());
console.log("time : ", time);
// let result = await axios({ // let result = await axios({
// method: method, // method: method,
// json: true, // json: true,
...@@ -165,9 +161,8 @@ const confirmMbnum = async (req, res) => { ...@@ -165,9 +161,8 @@ const confirmMbnum = async (req, res) => {
// console.log('resultMs', resultMs); // console.log('resultMs', resultMs);
// console.log('response', res.data, res['data']); // console.log('response', res.data, res['data']);
const confirm = await ConfirmNum.findOne({ where: { phone: phoneNumber} }); const confirm = await ConfirmNum.findOne({ where: { phone: phoneNumber } });
console.log(confirm); if (confirm) {
if(confirm){
await confirm.destroy(); await confirm.destroy();
// 5분 유효시간 설정 // 5분 유효시간 설정
await ConfirmNum.create({ await ConfirmNum.create({
...@@ -175,13 +170,13 @@ const confirmMbnum = async (req, res) => { ...@@ -175,13 +170,13 @@ const confirmMbnum = async (req, res) => {
phone: phoneNumber, phone: phoneNumber,
startTime: time, startTime: time,
}); });
}else{ } else {
await ConfirmNum.create({ await ConfirmNum.create({
confirmNum: String(verifyCode), confirmNum: String(verifyCode),
phone: phoneNumber, phone: phoneNumber,
startTime: time, startTime: time,
} }
); );
} }
res.json({ startTime: time, isSuccess: true, code: 202, message: "본인인증 문자 발송 성공", result: res.data }); res.json({ startTime: time, isSuccess: true, code: 202, message: "본인인증 문자 발송 성공", result: res.data });
} catch (error) { } catch (error) {
...@@ -196,25 +191,21 @@ const confirmMbnum = async (req, res) => { ...@@ -196,25 +191,21 @@ const confirmMbnum = async (req, res) => {
// 인증번호 확인 // 인증번호 확인
const confirmNum = async (req, res) => { const confirmNum = async (req, res) => {
try { try {
const {userMbnum, number, startTime} = req.body; const { userMbnum, number, startTime } = req.body;
console.log(userMbnum, number, startTime); const confirm = await ConfirmNum.findOne({ where: { phone: userMbnum, startTime: startTime } });
const confirm = await ConfirmNum.findOne({ where: { phone: userMbnum, startTime: startTime} });
console.log(confirm);
let today = new Date(); let today = new Date();
let time = today.getTime(); let time = today.getTime();
console.log("time2 :", time);
const elapsedMSec = time - confirm.startTime; const elapsedMSec = time - confirm.startTime;
const elapsedMin = String(elapsedMSec / 1000 / 60); const elapsedMin = String(elapsedMSec / 1000 / 60);
console.log("elapsedMin : ", elapsedMin); if (elapsedMin <= 5) {
if(elapsedMin <= 5 ){
if (number !== confirm.confirmNum) { if (number !== confirm.confirmNum) {
res.send("실패"); res.send("실패");
}else { } else {
await confirm.destroy(); await confirm.destroy();
res.send("성공"); res.send("성공");
} }
}else{ } else {
res.send("재전송") res.send("재전송")
} }
} catch (error) { } catch (error) {
...@@ -223,32 +214,72 @@ const confirmNum = async (req, res) => { ...@@ -223,32 +214,72 @@ const confirmNum = async (req, res) => {
} }
}; };
//유효성 검사
const validation = (errorMsg, data, minLength, maxLength, dataType) => {
if (validator.isLength(data, minLength, maxLength)) {
errorMsg[dataType] = false;
} else {
errorMsg[dataType] = true;
}
if (dataType === "userEmail") {
if (validator.isEmail(data, minLength, maxLength)) {
errorMsg[dataType] = false;
} else {
errorMsg[dataType] = true;
}
}
};
const signup = async (req, res) => { const signup = async (req, res) => {
const { userId, userName, userEmail, userNickName, userBirthday, userMbnum, userPassword } = req.body; const { userId, userName, userEmail, userNickName, userBirthday, userMbnum, userPassword } = req.body;
try { try {
const mbnum = await User.findOne({ where: { phoneNumber: userMbnum }}); let errorMsg = {
const email = await User.findOne({ where: { email: userEmail } }); errorId: false,
errorName: false,
errorEmail: false,
errorBirthday: false,
errorNickName: false,
errorMbnum: false,
errorPassword: false,
};
//유효성 검사
validation(errorMsg, userId, 5, 10, "errorId");
validation(errorMsg, userName, 1, 10, "errorName");
validation(errorMsg, userEmail, 3, 20, "errorEmail");
validation(errorMsg, userBirthday, 6, 6, "errorBirthday");
validation(errorMsg, userNickName, 1, 10, "errorNickName");
validation(errorMsg, userMbnum, 11, 11, "errorMbnum");
validation(errorMsg, userPassword, 8, 11, "errorPassword");
let valid = !(Object.values(errorMsg).some((element) => (element)));
if (mbnum && email) { const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } });
return res.status(422).send(`이미 있는 이메일, 휴대폰번호입니다.`); const email = await User.findOne({ where: { email: userEmail } });
} else if (!mbnum && email) { if (!valid) {
return res.status(422).send(`이미 있는 이메일입니다.`); res.json(errorMsg);
} else if (mbnum && !email) {
return res.status(422).send(`이미 있는 휴대폰번호입니다.`);
} else { } else {
const role = await Role.findOne({ where: { name: "member" } }) if (mbnum && email) {
const newUser = await User.create({ return res.status(422).send(`이미 있는 이메일, 휴대폰번호입니다.`);
userId: userId, } else if (!mbnum && email) {
name: userName, return res.status(422).send(`이미 있는 이메일입니다.`);
email: userEmail, } else if (mbnum && !email) {
nickname: userNickName, return res.status(422).send(`이미 있는 휴대폰번호입니다.`);
birth: userBirthday, } else {
phoneNumber: userMbnum, const role = await Role.findOne({ where: { name: "member" } })
password: userPassword, await User.create({
img:"", userId: userId,
roleId: role.id name: userName,
}); email: userEmail,
res.json(newUser); nickname: userNickName,
birth: userBirthday,
phoneNumber: userMbnum,
password: userPassword,
img: "",
roleId: role.id
});
res.json("성공");
}
} }
} catch (error) { } catch (error) {
console.error(error.message); console.error(error.message);
...@@ -275,7 +306,6 @@ const getMember = async (req, res) => { ...@@ -275,7 +306,6 @@ const getMember = async (req, res) => {
const uploadProfile = async (req, res) => { const uploadProfile = async (req, res) => {
try { try {
const image = req.file.filename; const image = req.file.filename;
console.log(req.file);
const token = req.cookies.butterStudio; const token = req.cookies.butterStudio;
const decoded = jwt.verify(token, config.jwtSecret); const decoded = jwt.verify(token, config.jwtSecret);
...@@ -308,7 +338,6 @@ const comparePw = async (req, res) => { ...@@ -308,7 +338,6 @@ const comparePw = async (req, res) => {
const user = await User.scope("withPassword").findOne({ where: { id: decoded.id } }); const user = await User.scope("withPassword").findOne({ where: { id: decoded.id } });
//입력한 비번과 해당 행 비번을 비교 //입력한 비번과 해당 행 비번을 비교
const passwordMatch = await user.comparePassword(req.params.pw); const passwordMatch = await user.comparePassword(req.params.pw);
console.log("passwordMatch : ", passwordMatch);
//클라이언트로 동일여부를 전송 //클라이언트로 동일여부를 전송
if (passwordMatch) { if (passwordMatch) {
return res.json(true) return res.json(true)
...@@ -324,12 +353,12 @@ const comparePw = async (req, res) => { ...@@ -324,12 +353,12 @@ const comparePw = async (req, res) => {
const overlap = async (decoded, dataType, data) => { const overlap = async (decoded, dataType, data) => {
try { try {
let overlap = await User.findOne({ where: { id: decoded.id } }); let overlap = await User.findOne({ where: { id: decoded.id } });
console.log("기존 데이터 : ", overlap, "변경할 데이터 : ", data); // 변경할 데이터가 자기자신이면 true
if (overlap[dataType] === data) { if (overlap[dataType] === data) {
return true return true
} else { } else {
// 그렇지 않으면 다른 데이터들 중에서 중복되는지 검사
let overlap2 = await User.findOne({ attributes: [dataType] }); let overlap2 = await User.findOne({ attributes: [dataType] });
console.log(overlap2)
if (overlap2[dataType] === data) { if (overlap2[dataType] === data) {
return false return false
} else { } else {
...@@ -347,25 +376,43 @@ const modifyUser = async (req, res) => { ...@@ -347,25 +376,43 @@ const modifyUser = async (req, res) => {
const decoded = jwt.verify(token, config.jwtSecret); const decoded = jwt.verify(token, config.jwtSecret);
const { userName, userEmail, userNickName, userMbnum, userPassword } = req.body; const { userName, userEmail, userNickName, userMbnum, userPassword } = req.body;
let errorMsg = {
errorName: false,
errorEmail: false,
errorNickName: false,
errorMbnum: false,
errorPassword: false,
};
//유효성 검사
validation(errorMsg, userName, 1, 10, "errorName");
validation(errorMsg, userEmail, 3, 20, "errorEmail");
validation(errorMsg, userNickName, 1, 10, "errorNickName");
validation(errorMsg, userMbnum, 11, 11, "errorMbnum");
validation(errorMsg, userPassword, 8, 11, "errorPassword");
let valid = !(Object.values(errorMsg).some((element) => (element)));
const overlapEmail = await overlap(decoded, "email", userEmail); const overlapEmail = await overlap(decoded, "email", userEmail);
const overlapMbnum = await overlap(decoded, "phoneNumber", userMbnum); const overlapMbnum = await overlap(decoded, "phoneNumber", userMbnum);
if (!valid) {
if (overlapEmail && overlapMbnum) { res.json(errorMsg);
const user = await User.update({
name: userName,
email: userEmail,
nickname: userNickName,
phoneNumber: userMbnum,
password: userPassword,
}, { where: { id: decoded.id }, individualHooks: true });
console.log("user22 :", user);
res.json(user);
} else if (!overlapEmail && overlapMbnum) {
res.status(500).send("이미 있는 이메일입니다.");
} else if (overlapEmail && !overlapMbnum) {
res.status(500).send("이미 있는 핸드폰번호입니다.");
} else { } else {
res.status(500).send("이미 있는 이메일, 핸드폰번호입니다."); if (overlapEmail && overlapMbnum) {
await User.update({
name: userName,
email: userEmail,
nickname: userNickName,
phoneNumber: userMbnum,
password: userPassword,
}, { where: { id: decoded.id }, individualHooks: true });
res.json("성공");
} else if (!overlapEmail && overlapMbnum) {
res.status(500).send("이미 있는 이메일입니다.");
} else if (overlapEmail && !overlapMbnum) {
res.status(500).send("이미 있는 핸드폰번호입니다.");
} else {
res.status(500).send("이미 있는 이메일, 핸드폰번호입니다.");
}
} }
} catch (error) { } catch (error) {
console.error(error.message); console.error(error.message);
......
...@@ -54,7 +54,6 @@ const UserModel = (sequelize) => { ...@@ -54,7 +54,6 @@ const UserModel = (sequelize) => {
); );
User.beforeSave(async (user) => { User.beforeSave(async (user) => {
console.log('update before', user)
if (!user.changed("password")) { if (!user.changed("password")) {
return; return;
} }
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment