Commit 9ad05544 authored by Kim, Subin's avatar Kim, Subin
Browse files

context 사용 PrivateRouter 적용

parent 8165ef72
......@@ -8,7 +8,7 @@ const PrivateRoute = ({ component: Component, ...rest }) => {
<Route
{...rest}
render={(props) => {
if (user) {
if (user.id !== "") {
if (rest.role) {
if (rest.role === user.role) {
return <Component {...props} />;
......
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { useHistory, useLocation } from "react-router-dom";
import ErrorPage from "../pages/ErrorPage";
import authApi from "../apis/auth.api";
import catchErrors from './catchErrors';
......@@ -19,10 +20,14 @@ const AuthProvider = ({ children }) => {
const { pathname } = useLocation()
const getUser = async () => {
try {
console.log("context getUser")
const resUser = await authApi.getUser();
setUser({ ...user, ...resUser });
// console.log("context use")
// if (pathname === "/admin" && user.role !== "admin") history.push('/home')
setUser({ ...user, ...resUser })
if (pathname === "/admin" && user.role !== "admin") {
await logout()
return <ErrorPage />
} else if (user.role === "admin") history.push("/admin")
else history.push("/home")
} catch (error) {
catchErrorAuth(error, setError);
}
......@@ -37,8 +42,7 @@ const AuthProvider = ({ children }) => {
setError("");
const user = await authApi.login(data);
localStorage.setItem("login", true)
setUser(user);
console.log('setUser 결과', user)
setUser(user)
return true;
} catch (error) {
catchErrors(error, setError);
......@@ -80,6 +84,7 @@ const AuthProvider = ({ children }) => {
console.log("Error message:", errMsg)
}
displayError(errMsg);
alert(errMsg)
}, []);
return (
......
......@@ -9,7 +9,6 @@ const getUser = async (req, res) => {
const { id, role, name } = jwt.verify(token, config.jwtSecret);
return res.json({ id, role, name });
} else {
// res.json({ id: "", role: "user", name: "" });
throw new Error("유효기간이 만료되었습니다. 다시 로그인해주세요.")
}
} catch (error) {
......
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