JWTAuthContext.js 6.47 KB
Newer Older
Giang Tran committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
import React, { createContext, useEffect, useReducer } from 'react'
import jwtDecode from 'jwt-decode'
import axios from 'axios.js'
import { MatxLoading } from 'app/components'
import localStorageService from '../services/localStorageService'
import { apiLogin, apiGetInfor, apiLogout } from 'app/apis/Functions/users'
import { toast } from 'react-toastify'
import { SET_USER_NAVIGATION_LOGIN } from 'app/redux/actions/NavigationAction'

const initialState = {
    isAuthenticated: false,
    isInitialised: false,
    user: null,
}

const isValidToken = (accessToken) => {
    if (!accessToken) {
        return false
    }

    const decodedToken = jwtDecode(accessToken)
    const currentTime = Date.now() / 1000
    console.log(decodedToken)
    return decodedToken.exp > currentTime
}

const setSession = (accessToken) => {
    if (accessToken) {
        localStorage.setItem('accessToken', accessToken)
        axios.defaults.headers.common.Authorization = `Bearer ${accessToken}`
    } else {
        localStorage.removeItem('accessToken')
        delete axios.defaults.headers.common.Authorization
    }
}

const reducer = (state, action) => {
    switch (action.type) {
        case 'INIT': {
            const { isAuthenticated, user } = action.payload

            return {
                ...state,
                isAuthenticated,
                isInitialised: true,
                user,
            }
        }
        case 'LOGIN': {
            const { user } = action.payload
            return {
                ...state,
                isAuthenticated: true,
                user,
            }
        }
        case 'LOGOUT': {
            return {
                ...state,
                isAuthenticated: false,
                user: null,
            }
        }
        case 'REGISTER': {
            const { user } = action.payload

            return {
                ...state,
                isAuthenticated: true,
                user,
            }
        }
        default: {
            return { ...state }
        }
    }
}

const AuthContext = createContext({
    ...initialState,
    method: 'JWT',
    login: () => Promise.resolve(),
    logout: () => {},
    register: () => Promise.resolve(),
})

export const AuthProvider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, initialState)
    const login = async (username, password) => {
        const res = await apiLogin({
            username,
            password,
        })
        if (res.status === 200) {
            if (res.data.code == 200 && res.data.data) {
                localStorageService.setItem('accessToken', res.data.data.token)
                let listPath = []
                res.data.data.user_permissions.map((item) => {
                    if (item.actions) {
                        item.actions.map((e) => listPath.push(e.path))
                    }
                })
                dispatch({
                    type: 'LOGIN',
                    payload: {
                        user: { ...res.data.data, listPath },
                    },
                })
            } else {
                toast.error('Tài khoản hoặc mật khẩu không chính xác!', {
                    theme: 'colored',
                })
            }
        } else {
            toast.error('Hệ thống đang bảo trì!', {
                theme: 'colored',
            })
        }

        console.log(res.data)
    }

    const register = async (email, username, password) => {
        const response = await axios.post('/api/auth/register', {
            email,
            username,
            password,
        })

        const { accessToken, user } = response.data

        setSession(accessToken)

        dispatch({
            type: 'REGISTER',
            payload: {
                user,
            },
        })
    }

    const logout = async () => {
        setSession(null)
        const res = await apiLogout({})

        dispatch({ type: 'LOGOUT' })
    }

    useEffect(() => {
        ;(async () => {
            try {
                const accessToken = window.localStorage.getItem('accessToken')
tdgiang committed
153
                console.log('accessToken', accessToken)
Giang Tran committed
154 155 156 157 158
                // if (accessToken && isValidToken(accessToken))
                if (accessToken) {
                    // setSession(accessToken)
                    const res = await apiGetInfor({})

tdgiang committed
159 160
                    console.log('res', res)

Giang Tran committed
161 162
                    if (res.data.code == 200 && res.data.data) {
                        const user = res.data.data
tdgiang committed
163
                        console.log('res.data.data', res.data.data)
Giang Tran committed
164
                        let listPath = []
tdgiang committed
165 166 167 168 169
                        user.user_permissions.map((item) => {
                            if (item.actions) {
                                item.actions.map((e) => listPath.push(e.path))
                            }
                        })
Giang Tran committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
                        dispatch({
                            type: 'INIT',
                            payload: {
                                isAuthenticated: true,
                                user: { ...res.data.data, listPath },
                            },
                        })
                    } else {
                        localStorageService.setItem('accessToken', null)
                        dispatch({
                            type: 'INIT',
                            payload: {
                                isAuthenticated: false,
                                user: null,
                            },
                        })
                    }
                } else {
                    dispatch({
                        type: 'INIT',
                        payload: {
                            isAuthenticated: false,
                            user: null,
                        },
                    })
                }
            } catch (err) {
                console.error(err)
                dispatch({
                    type: 'INIT',
                    payload: {
                        isAuthenticated: false,
                        user: null,
                    },
                })
            }
        })()
    }, [])

    if (!state.isInitialised) {
        return <MatxLoading />
    }

    return (
        <AuthContext.Provider
            value={{
                ...state,
                method: 'JWT',
                login,
                logout,
                register,
            }}
        >
            {children}
        </AuthContext.Provider>
    )
}

export default AuthContext