auth_context.js 2.87 KB
Newer Older
한규민's avatar
push    
한규민 committed
1
2
3
4
5
6
7
8
9
10
11
import axios from "axios";
import { createContext,  useCallback, useContext, useState } from "react";
import authApi from "../apis/auth.api";
import { getLocalUser } from "../utils/auth";
import {baseUrl} from "../utils/baseUrl";
import catchErrors from "../utils/catchErrors";
import config from "../utils/clientConfig";

const AuthContext = createContext({
    error: "",
    loading: false,
한규민's avatar
한규민 committed
12
    user: {id:0, role:"user"},
한규민's avatar
push    
한규민 committed
13
14
15
16
17
18
19
20
21
22
23
    setUser: () => { },
    login: () => Promise.resolve(false),
    logout: () => { },
    catchErrorAuth: (error, displayError) => { },
});

const AuthProvider = ({ children }) => {
    const [error, setError] = useState("");
    const [loading, setLoading] = useState(false);
    const [user, setUser] = useState(getLocalUser());

한규민's avatar
한규민 committed
24
    const login = useCallback(async (id, password) => {
한규민's avatar
push    
한규민 committed
25
26
27
        try {
            setError("");
            setLoading(true);
한규민's avatar
한규민 committed
28
            const user = await authApi.login(id, password);
한규민's avatar
push    
한규민 committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
87
88
89
90
91
92
93
            localStorage.setItem(config.loginUser, JSON.stringify(user));
            setUser(user);

            return true;
        } catch (error) {
            catchErrors(error, setError);
            return false;
        } finally {
            setLoading(false);
        }
    }, []);

    const logout = useCallback(async () => {
        try {
            setError("");
            setUser(null);
            alert("로그아웃되었습니다.");
            localStorage.removeItem(config.loginUser);
            setLoading(true);
            await axios.get(`${baseUrl}/api/auth/logout`);
        } catch (error) {
            catchErrors(error, setError);
        } finally {
            setLoading(false);
        }
    }, []);

    const catchErrorAuth = useCallback(async (error, displayError) => {
        let errorMsg;
        if (error.response) {
            if (typeof error.response.data === "string") {
                errorMsg = error.response.data;
                console.log("Error response:", errorMsg);
            } else {
                const { data } = error.response;
                if (data.redirectUrl) {
                    errorMsg = data.message;
                    console.log("Error response with redirected message:", errorMsg);
                    console.log("redirect url", data.redirectUrl);
                    return await logout();
                }
            }
        } else if (error.request) {
            errorMsg = error.request;
            console.log("Error request:", errorMsg);
        } else {
            errorMsg = error.message;
            console.log("Error message:", errorMsg);
        }

        displayError(errorMsg);
    }, []);

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

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

export { AuthProvider, useAuth };