context.js 2.73 KB
Newer Older
1
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
Kim, Subin's avatar
context    
Kim, Subin committed
2
import { useHistory, useLocation } from "react-router-dom";
3
import ErrorPage from "../pages/ErrorPage";
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import authApi from "../apis/auth.api";
import catchErrors from './catchErrors';

const AuthContext = createContext({
  error: "",
  user: { id: "", role: "user", name: "" },
  setUser: () => { },
  login: () => Promise.resolve(false),
  logout: () => { },
  catchErrorAuth: (error, displayError) => { },
});

const AuthProvider = ({ children }) => {
  const [user, setUser] = useState({ id: "", role: "user", name: "" });
Kim, Subin's avatar
context    
Kim, Subin committed
18
19
20
  const [error, setError] = useState("");
  const history = useHistory()
  const { pathname } = useLocation()
21
  const getUser = async () => {
Kim, Subin's avatar
context    
Kim, Subin committed
22
    try {
23
      console.log("context getUser")
Kim, Subin's avatar
context    
Kim, Subin committed
24
      const resUser = await authApi.getUser();
25
26
27
28
29
30
      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")
Kim, Subin's avatar
context    
Kim, Subin committed
31
32
33
    } catch (error) {
      catchErrorAuth(error, setError);
    }
34
  }
Kim, Subin's avatar
context    
Kim, Subin committed
35

36
37
38
39
40
41
42
43
  useEffect(() => {
    getUser();
  }, []);

  const login = useCallback(async (data) => {
    try {
      setError("");
      const user = await authApi.login(data);
44
      localStorage.setItem("login", true)
45
      setUser(user)
46
47
48
49
50
51
52
53
54
55
56
      return true;
    } catch (error) {
      catchErrors(error, setError);
      return false;
    }
  }, []);

  const logout = useCallback(async () => {
    try {
      setError("");
      const user = await authApi.logout();
57
      localStorage.removeItem("login")
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
      setUser(user);
      alert("로그아웃 되었습니다.");
    } catch (error) {
      catchErrors(error, setError);
    }
  }, []);

  const catchErrorAuth = useCallback(async (error, displayError) => {
    let errMsg;
    if (error.response) {
      if (typeof error.response.data === "string") {
        errMsg = error.response.data;
        console.log('Error response:', errMsg);
      } else {
        const { data } = error.response;
        if (data.redirectUrl) {
          errMsg = data.message;
          console.log('Error response with redirected message:', errMsg);
          return await logout();
        }
      }
    } else if (error.request) {
      errMsg = error.request;
      console.log('Error request:', errMsg);
    } else {
      errMsg = error.message;
      console.log("Error message:", errMsg)
    }
    displayError(errMsg);
87
    alert(errMsg)
88
89
90
91
92
93
94
95
96
97
98
  }, []);

  return (
    <AuthContext.Provider value={{ error, user, setUser, login, logout, catchErrorAuth }} >
      {children}
    </AuthContext.Provider>
  );
};

const useAuth = () => useContext(AuthContext);

Kim, Subin's avatar
context    
Kim, Subin committed
99
export { AuthProvider, useAuth };