Skip to content

Commit

Permalink
Merge pull request #256 from readyvery/test
Browse files Browse the repository at this point in the history
3/25 배포 2차 수정
  • Loading branch information
marinesnow34 authored Mar 23, 2024
2 parents b1345be + 072f618 commit 8a5ab67
Show file tree
Hide file tree
Showing 14 changed files with 263 additions and 129 deletions.
109 changes: 51 additions & 58 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import { message } from "antd";
import axios from "axios";
import React, { Suspense } from "react";
import { useCookies } from "react-cookie";
import { Navigate, Route, Routes, useNavigate } from "react-router-dom";
import { RecoilRoot, useSetRecoilState } from "recoil";
import { Navigate, Route, Routes } from "react-router-dom";
import { RecoilRoot } from "recoil";
import MyPage from "../src/pages/MyPage/MyPage";
import StoreDetailPage from "../src/pages/StoreDetailPage/StoreDetailPage";
import "./App.css";
// import loading from "./assets/animation/loading.json";
import MembershipPage from "../src/pages/MembershipPage/MembershipPage";
import { isAuthenticatedState } from "./Atom/status";
import ic_berry from "./assets/images/ic_berry.png";
import Auth from "./hoc/auth";
import useInterval from "./hooks/useInterval";
import AuthenticationPage from "./pages/Authentication/AuthenticationPage";
import CartPage from "./pages/CartPage/CartPage";
import CouponPage from "./pages/CouponPage/CouponPage";
Expand All @@ -38,18 +33,13 @@ import Splash from "./pages/Splash/Splash";
import StoreSearchPage from "./pages/StoreSearch/StoreSearch";

function App() {
const [, , removeCookies] = useCookies(["accessToken"]);
const setIsAuth = useSetRecoilState(isAuthenticatedState);
const navigate = useNavigate();
const apiRoot = process.env.REACT_APP_API_ROOT;
const apiVer = "api/v1";
const apiUrl = `${apiRoot}/${apiVer}/refresh/token`;
// const [cookies, , removeCookies] = useCookies();
// const [isAuth, setIsAuth] = useRecoilState(isAuthenticatedState);
// const navigate = useNavigate();
// // const [isLoggedIn, setisLoggedIn] = useRecoilState(isAuthenticatedState); // 인증 상태 (로그인이 되어있으면 true, 아니면 false)
// // 토큰 받아서 시간관리
// const [cookies, setCookie, removeCookies] = useCookies([
// "refreshAccessToken",
// ]);
// const apiRoot = process.env.REACT_APP_API_ROOT;
// const apiVer = "api/v1";
// const apiUrl = `${apiRoot}/${apiVer}/refresh/token`;


//false : 로그인 한 유저 못들어감
const NewLoginPage = Auth(LoginPage, false); // 로그인 페이지
Expand All @@ -70,47 +60,50 @@ function App() {
const NewPaymentFailPage = Auth(PaymentFailPage, true, 2);
// const NewPackagingStatusPage = Auth(PackagingStatusPage, true);

const minute = 1000 * 60 * 60 * 24; // 24시간
// const minute = 1000 * 60 * 60 * 24; // 24시간
//const minute = 1000 * 60 * 10; // 10분
// const minute = 1000 * 60;
// 주기적으로 실행되는 함수
useInterval(() => {
const token = localStorage.getItem("accessToken");
console.log('cookie: ', token);
// 리프레시 토큰이 존재하고, 비어 있지 않은 경우
if (token) {
// http 요청에 사용될 헤더 설정과 함께 서버에 토큰 갱신 요청
let config = {
withCredentials: true,
headers: {
Authorization: `Bearer ${token}`
}
};
console.log('AT 재발급');
axios
.get(apiUrl, config)
.then((response) => {
console.log(response);
// 현재 쿠키 삭제
if (response.status !== 200 ) {
message.info("다시 로그인해주세요.");
removeCookies();
localStorage.clear();
setIsAuth(false);
navigate("/login");
} else {
console.log("AT 재발급 성공! ");
// localStorage.setItem("accessToken", cookies.accessToken);
// removeCookies();
}
})
.catch((error) => {
console.error(error);
message.info("다시 로그인해주세요.");
navigate("/login");
});
}
}, minute - 60000); // 24시간 주기에서 1분을 뺀 주기로 주기적 실행
// const minute = 1000 * 10; // 10초
// // 주기적으로 실행되는 함수
// useInterval(() => {
// const token = localStorage.getItem("accessToken");
// console.log('local token: ', token);
// console.log('isAuth: ', isAuth);
// // 리프레시 토큰이 존재하고, 비어 있지 않은 경우
// if (token) {
// // http 요청에 사용될 헤더 설정과 함께 서버에 토큰 갱신 요청
// let config = {
// withCredentials: true,
// headers: {
// Authorization: `Bearer ${token ? token : cookies?.accessToken}`
// }
// };
// console.log('AT 재발급');
// axios
// .get(apiUrl, config)
// .then((response) => {
// console.log(response);
// // 현재 쿠키 삭제
// if (response.status !== 200 ) {
// message.info("다시 로그인해주세요.");
// removeCookies();
// localStorage.clear();
// setIsAuth(false);
// navigate("/login");
// } else {
// console.log("AT 재발급 성공! ");
// console.log(cookies);
// debugger;
// cookies?.accessToken && localStorage.setItem("accessToken", cookies?.accessToken); // 로컬 스토리지에 AT 저장
// removeCookies("accessToken"); // AT 쿠키 삭제
// }
// })
// .catch((error) => {
// console.error(error);
// message.info("다시 로그인해주세요.");
// navigate("/login");
// });
// }
// }, minute - 1000); // 24시간 주기에서 1분을 뺀 주기로 주기적 실행

return (
<div className="App">
Expand Down
5 changes: 2 additions & 3 deletions src/Atom/status.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@ export const getAuthenticatedSelector = selector({
});

// 사용자의 로그인 상태 및 토큰 정보를 저장하는 상태
export const loginState = atom({
key: "loginState",
export const tokenState = atom({
key: "tokenState",
default: {
accessToken: null,
expiredTime: null,
},
effects_UNSTABLE: [persistAtom],
Expand Down
25 changes: 12 additions & 13 deletions src/components/views/CartItemCount/CartItemCount.jsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,30 @@
import axios from "axios";
import { useEffect, useState } from "react";
import "./CartItemCount.css";
import { useNavigate } from "react-router-dom";
import commonApis from "../../../utils/commonApis";
import "./CartItemCount.css";
const CartItemCount = () => {
const navigate = useNavigate();
const [count, setCount] = useState(0); // 장바구니 개수
const token = localStorage.getItem("accessToken");
const apiRoot = process.env.REACT_APP_API_ROOT;
const apiVer = "api/v1";
const apiUrl = `${apiRoot}/${apiVer}/order/cart/count`;
const navigate = useNavigate();
const apiUrl = `/order/cart/count`;

useEffect(() => {
const fetchData = async () => {
if (token) {
try {
const response = await axios.get(apiUrl, {
withCredentials: true,
headers: {
Authorization: `Bearer ${token}`,
},
});
const response = await commonApis.get(
apiUrl,
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
setCount(response.data.count);
} catch (error) {
if (error.response.status === 404) {
setCount(0);
}
console.log(error);
}
}
};
Expand Down
5 changes: 2 additions & 3 deletions src/components/views/PageComponent/OrderProgress.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@ const OrderProgress = () => {
const [degree, setDegree] = useState(0);
const [isOpen, setIsOpen] = useState(false);
const [refreshKey, setRefreshKey] = useState(0);
const { estimatedTime, orderNum, progress } = useFetchCurrentOrder(
const { estimatedTime, orderNum, progress, expectPoint } = useFetchCurrentOrder(
orderId,
refreshKey
);
const cancelOrder = useCancelOrder();
const point = 175;
const [rotate, setRotate] = useState(false); //새로고침 클릭시 회전용
const [debounceTimeout, setDebounceTimeout] = useState(null); // 디바운싱 상태
const progressList = useMemo(
Expand Down Expand Up @@ -238,7 +237,7 @@ const OrderProgress = () => {
{degree === 3 ? (
<div className="order_progress__point">
<span className="order_progress__point_text">
<span>{point}</span>원 적립되었습니다
<span>{expectPoint}</span>원 적립되었습니다
</span>
</div>
) : null}
Expand Down
39 changes: 28 additions & 11 deletions src/hoc/auth.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { message } from "antd";
import moment from "moment";
import React, { useEffect } from "react";
import { useCookies } from "react-cookie";
import { useLocation, useNavigate } from "react-router-dom";
import { useRecoilState } from "recoil";
import { isAuthenticatedState } from "../Atom/status";
import commonApis from "../utils/commonApis";
import authApi from "../utils/authApi";

function Auth(SpecificComponent, option, adminRoute = null) {
function AuthenticationCheck(props) {
Expand All @@ -16,31 +17,47 @@ function Auth(SpecificComponent, option, adminRoute = null) {

useEffect(() => {
function fetchAuth() {
commonApis.get("/auth", {
authApi.get("/auth", {
withCredentials: true,
headers: {
Authorization: `Bearer ${token ? token : cookies?.accessToken}`
}
}).then((response) => {
console.log(response);
// debugger;
const { auth } = response.data; // 로그인 여부
const { role } = response.data; // GUEST, USER, CEO
console.log(auth, role, option);
console.log(cookies?.accessToken);
if (cookies.accessToken && auth && !token) {
// 로그인 후 첫 접속
console.log('auth에서 첫 접속: ', cookies.accessToken);
localStorage.setItem("accessToken", cookies.accessToken); // 로컬 스토리지에 AT 저장
// setIsAuth(true); // 로그인 여부 변경
message.success("로그인에 성공하셨습니다.");
removeCookie("accessToken"); // AT 쿠키 삭제
return;
console.log(cookies);
if (cookies.accessToken) {
if(!token && auth) {
// 로그인 후 첫 접속
console.log('auth에서 첫 접속: ', cookies.accessToken);
localStorage.setItem("accessToken", cookies.accessToken); // 로컬 스토리지에 AT 저장
localStorage.setItem("expiredTime", moment().add(1, "minutes").format("yyyy-MM-DD HH:mm:ss")); // 만료시간 저장
setIsAuth(true); // 로그인 여부 변경
message.success("로그인에 성공하셨습니다.");
removeCookie("accessToken"); // AT 쿠키 삭제
return;
} else if(token) {
localStorage.clear();
localStorage.setItem("accessToken", cookies.accessToken); // 로컬 스토리지에 AT 저장
localStorage.setItem("expiredTime", moment().add(1, "minutes").format("yyyy-MM-DD HH:mm:ss")); // 만료시간 저장
setIsAuth(true); // 로그인 여부 변경
removeCookie("accessToken"); // AT 쿠키 삭제
return;
}
}
if (!auth) {
// 로그인 안 되어 있는 경우
if(isAuth){
setIsAuth(false);
}
if(cookies?.accessToken){
// 로그인 안 되어 있는데 쿠키 담겨있는 경우
localStorage.setItem("accessToken", cookies.accessToken);
removeCookie("accessToken");
}
if(option && location.pathname !== '/'){
navigate('/login');
return;
Expand Down
4 changes: 3 additions & 1 deletion src/hooks/useFetchCurrentOrder.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const useFetchCurrentOrder = (orderId, refreshKey) => {
// const [orderName, setOrderName] = useState("");
const [orderNum, setOrderNum] = useState("");
const [progress, setProgress] = useState("");
const [expectPoint, setExpectPoint] = useState(0);

const token = localStorage.getItem("accessToken");

Expand All @@ -29,6 +30,7 @@ const useFetchCurrentOrder = (orderId, refreshKey) => {
// setOrderName(response.data.orderName);
setOrderNum(response.data.orderNum);
setProgress(response.data.progress);
setExpectPoint(response.data.expectPoint);
} catch (error) {
console.error("Error fetching current order status:", error);
}
Expand All @@ -38,7 +40,7 @@ const useFetchCurrentOrder = (orderId, refreshKey) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [orderId, refreshKey]); // refreshKey를 의존성 배열에 추가

return { estimatedTime, orderNum, progress };
return { estimatedTime, orderNum, progress, expectPoint };
};

export default useFetchCurrentOrder;
1 change: 1 addition & 0 deletions src/hooks/useFetchFoodOptionInfo.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const useFetchFoodOptionInfo = (storeId, foodieId, inout) => {
setImgUrl(response.data?.imgUrl);
setName(response.data?.name);
setPrice(response.data?.price);
console.log("메뉴 데이터: ", response.data);
} catch (error) {
console.error("Error fetching food option info:", error);
}
Expand Down
6 changes: 4 additions & 2 deletions src/hooks/useFetchQuickOrder.jsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { useEffect, useState } from "react";
import { useCookies } from "react-cookie";
import commonApis from "../utils/commonApis";

const apiUrl = `/order/history/fast`;

const useFetchQuickOrder = () => {
const [cookies, , ] = useCookies(["accessToken"]);
const [quickOrder, setQuickOrder] = useState([]);
const token = localStorage.getItem("accessToken");

useEffect(() => {
const fetchData = async () => {
if (token) {
if (token || cookies?.accessToken) {
try {
const response = await commonApis.get(apiUrl, {
headers: {
Authorization: `Bearer ${token}`
Authorization: `Bearer ${token ? token : cookies?.accessToken}`
}
});
setQuickOrder(response.data.receipts?.reverse());
Expand Down
7 changes: 5 additions & 2 deletions src/hooks/useFetchUserInfo.jsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import { useEffect, useState } from "react";
import { useCookies } from "react-cookie";
import commonApis from "../utils/commonApis";

const apiUrl = `/user/info`;

const useFetchUserInfo = () => {
const token = localStorage.getItem("accessToken");
const [cookies, , ] = useCookies(["accessToken"]);
// const [userInfo, setUserInfo] = useState({ name: "", phone: "", email: "" });
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [phone, setPhone] = useState("");

useEffect(() => {
const fetchData = async () => {
if(token){
console.log(token, cookies);
if(token || cookies?.accessToken){
try {
const response = await commonApis.get(apiUrl, {
headers: {
Authorization: `Bearer ${token}`
Authorization: `Bearer ${token ? token : cookies?.accessToken}`
}
});
setEmail(response.data.email);
Expand Down
6 changes: 4 additions & 2 deletions src/hooks/useGetPoint.jsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { useEffect, useState } from "react";
import { useCookies } from "react-cookie";
import commonApis from "../utils/commonApis";

const apiUrl = `/point/`;

const useGetPoint = () => {
const token = localStorage.getItem("accessToken");
const [cookies, , ] = useCookies(["accessToken"]);
const [point, setPoint] = useState(0);
useEffect(() => {
const getPoint = async () => {
if (token){
if (token || cookies?.accessToken){
try {
const response = await commonApis.get(apiUrl, {
headers: {
Authorization: `Bearer ${token}`
Authorization: `Bearer ${token ? token : cookies?.accessToken}`
}
});
const pointValue =
Expand Down
Loading

0 comments on commit 8a5ab67

Please sign in to comment.