Skip to content

Commit

Permalink
Merge pull request #239 from hhbb0081/test
Browse files Browse the repository at this point in the history
Feat: Auth 추가
  • Loading branch information
hhbb0081 authored Mar 8, 2024
2 parents f432a13 + 399fd70 commit a196298
Show file tree
Hide file tree
Showing 42 changed files with 553 additions and 344 deletions.
9 changes: 7 additions & 2 deletions .idea/workspace.xml

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

57 changes: 37 additions & 20 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ 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 } from "recoil";
import { RecoilRoot, useSetRecoilState } 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";
import HomePage from "./pages/HomePage/Homepage";
Expand All @@ -36,7 +38,8 @@ import Splash from "./pages/Splash/Splash";
import StoreSearchPage from "./pages/StoreSearch/StoreSearch";

function App() {
const [cookies, , removeCookies] = useCookies();
const [, , removeCookies] = useCookies(["accessToken"]);
const setIsAuth = useSetRecoilState(isAuthenticatedState);
const navigate = useNavigate();
const apiRoot = process.env.REACT_APP_API_ROOT;
const apiVer = "api/v1";
Expand All @@ -52,45 +55,57 @@ function App() {
const NewLoginPage = Auth(LoginPage, false); // 로그인 페이지

//true : 로그인 한 유저 들어감
const NewHomePage = Auth(HomePage, true);
const NewOrderHistory = Auth(OrderHistory, true);
const NewOrderDetail = Auth(OrderDetail, true);
const NewMyprofilePage = Auth(MyprofilePage, true);
const NewAuthentication = Auth(AuthenticationPage, true, 1);
// const NewHomePage = Auth(HomePage, true, 2);
const NewOrderHistory = Auth(OrderHistory, true, 2);
const NewOrderDetail = Auth(OrderDetail, true, 2);
const NewMyprofilePage = Auth(MyprofilePage, true, 2);

const NewOrderProcessPage = Auth(OrderProcessPage, true);
const NewMembershipPage = Auth(MembershipPage, true);
const NewCouponPage = Auth(CouponPage, true);
const NewCartPage = Auth(CartPage, true);
const NewPaymentPage = Auth(PaymentPage, true);
const NewPaymentLoadingPage = Auth(PaymentLoadingPage, true);
const NewPaymentFailPage = Auth(PaymentFailPage, true);
const NewOrderProcessPage = Auth(OrderProcessPage, true, 2);
const NewMembershipPage = Auth(MembershipPage, true, 2);
const NewCouponPage = Auth(CouponPage, true, 2);
const NewCartPage = Auth(CartPage, true, 2);
const NewPaymentPage = Auth(PaymentPage, true, 2);
const NewPaymentLoadingPage = Auth(PaymentLoadingPage, true, 2);
const NewPaymentFailPage = Auth(PaymentFailPage, true, 2);
// const NewPackagingStatusPage = Auth(PackagingStatusPage, true);

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 (
cookies.refreshToken !== "undefined" &&
cookies.refreshToken !== undefined &&
cookies.refreshToken
) {
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.data) {
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");
});
Expand All @@ -114,13 +129,15 @@ function App() {
{/* 로그인 하지 않아도 볼 수 있는 페이지 */}
<Route path="/splash" element={<Splash />} />
{/* 메인페이지 */}
<Route path="/" element={<NewHomePage />} />
<Route path="/" element={<HomePage />} />
{/* 없는 경로로 갈 경우 메인페이지로 강제 이동 */}
<Route path="/*" element={<Navigate to="/"></Navigate>}></Route>
{/* 카페검색*/}
<Route path="/search" element={<StoreSearchPage />} />
{/* 로그인*/}
<Route path="/login" element={<NewLoginPage />} />
{/* 번호인증 페이지 */}
<Route path="/authentication" element={<NewAuthentication/>} />
{/* 쿠폰 및 포인트 faq페이지*/}
<Route path="/faq" element={<FrequentlyAskedQuestionPage />} />
{/* 마이페이지-약관정책 페이지 */}
Expand Down
26 changes: 15 additions & 11 deletions src/components/views/CartItemCount/CartItemCount.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,27 @@ import { useEffect, useState } from "react";
import "./CartItemCount.css";
const CartItemCount = () => {
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`

useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(`${apiRoot}/api/v1/order/cart/count`, {
withCredentials: true,
});
setCount(response.data.count);
} catch (error) {
if (axios.isAxiosError(error)) {
const err = error.response?.data.status;
if (err === 404) {
if(token){
try {
const response = await axios.get(apiUrl, {
withCredentials: true,
headers: {
Authorization: `Bearer ${token}`
}
});
setCount(response.data.count);
} catch (error) {
if(error.response.status === 404){
setCount(0);
} else {
console.error(error);
}
console.log(error);
}
}
};
Expand Down
13 changes: 6 additions & 7 deletions src/components/views/PageComponent/OrderStorage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,20 @@ import useFetchOldOrderHistory from "../../../hooks/useFetchOldOrderHistory";
import Header from "../Header/Header";
import NavBar from "../NavBar/NavBar";
import StateBox from "../StateBox/StateBox";
import "./OrderStorage.css";
import Empty from "./Empty";
import "./OrderStorage.css";

function OrderStorage() {
const navigate = useNavigate();
const newStorageList = useFetchNewOrderHistory();
const oldStorageList = useFetchOldOrderHistory();

const progressList = {
ORDER: 0,
MAKE: 1,
COMPLETE: 2,
PICKUP: 3,
CANCEL: 4,
FAIL: 5,
ORDER: 0, // 진행중
MAKE: 1, // 제조중
COMPLETE: 2, // 제조완료
CANCEL: 4, // 주문취소
FAIL: 5, // 결제실패
};

const handleNavigation = (e, orderId, progress) => {
Expand Down
93 changes: 69 additions & 24 deletions src/hoc/auth.jsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,82 @@
import { message } from "antd";
import React, { useEffect } from "react";
import { useCookies } from "react-cookie";
import { useLocation, useNavigate } from "react-router-dom";
import { useRecoilState } from "recoil";
import { useNavigate } from "react-router-dom";
import { useSetRecoilState } from "recoil";
import { isAuthenticatedState } from "../Atom/status";
import commonApis from "../utils/commonApis";

function Auth(SpecificComponent, option) {
function Auth(SpecificComponent, option, adminRoute = null) {
function AuthenticationCheck(props) {
const navigate = useNavigate();
const location = useLocation();
const [isAuth, setIsAuth] = useRecoilState(isAuthenticatedState);
//const userInfo = useRecoilValue(getUserSelector);
const [cookies] = useCookies(["accessToken"]);
const [cookies, , removeCookie] = useCookies(["accessToken"]);
const setIsAuth = useSetRecoilState(isAuthenticatedState)
const token = localStorage.getItem("accessToken");

useEffect(() => {
console.log(cookies?.accessToken);
console.log("isAuth" + isAuth);
if (!isAuth && cookies?.accessToken) {
setIsAuth(true);
message.success("로그인에 성공하셨습니다.");
function fetchAuth() {
commonApis.get("/auth", {
// headers: {
// Authorization: `Bearer ${token.accessToken}`
// },
withCredentials: true
}).then((response) => {
console.log(response);
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 쿠키 삭제
}
if (!auth) {
// 로그인 안 되어 있는 경우
setIsAuth(false);
if(option){
navigate('/login');
return;
}
}
else {
// 로그인이 된 경우
if(!option){
// 로그인하면 갈 수 없는 페이지
navigate('/');
return;
}
if(role === 'GUEST'){
// 번호인증 안 한 유저
if(adminRoute !== 1){
navigate('/authentication');
}
return;
} else if (role === 'USER'){
// 번호인증 한 유저
if(adminRoute !== 2){
navigate('/');
}
}
}}).catch((error) => {
console.log(error);
if (
error.response &&
error.response?.status >= 400 &&
error.response?.status < 500
) {
// 클라이언트 오류 발생 (400번대 오류)
// 로그인 페이지로 되돌아가는 조건문 추가
navigate('/login');
} else {
// 서버 오류 또는 네트워크 오류 등의 다른 오류 처리
}
})
}
if (!cookies?.accessToken) {
if (option && location.pathname !== "/") {
navigate("/login");
}
// 로그인이 필요한 페이지
} else {
// 로그인 안해도 보이는 페이지
if (option === false) {
navigate("/");
}
}

fetchAuth();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Expand Down
17 changes: 10 additions & 7 deletions src/hooks/useCancelOrder.jsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import axios from "axios";
import { message } from "antd";
import commonApis from "../utils/commonApis";

const apiRoot = process.env.REACT_APP_API_ROOT;
const apiVer = "api/v1";
const apiUrl = `${apiRoot}/${apiVer}/order/toss/cancel`;
const apiUrl = `/order/toss/cancel`;

const useCancelOrder = () => {
const token = localStorage.getItem("accessToken");

const cancelOrder = async (orderId) => {
try {
const response = await axios.post(
const response = await commonApis.post(
apiUrl,
{ orderId },
{ withCredentials: true }
{ orderId }, {
headers: {
Authorization: `Bearer ${token}`
}
}
);
if (response.status === 200 && response.data.message === "취소 성공") {
message.success("주문 취소되었습니다.");
Expand Down
Loading

0 comments on commit a196298

Please sign in to comment.