2020-08-03 12:04:07 +02:00
|
|
|
import { createContext, useState, useEffect } from 'react'
|
|
|
|
import Cookies from 'universal-cookie'
|
|
|
|
import api from '../utils/api'
|
2020-04-06 16:46:03 +02:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
const cookies = new Cookies()
|
2020-04-06 16:46:03 +02:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
export const UserContext = createContext()
|
2020-04-06 16:46:03 +02:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
function UserContextProvider (props) {
|
|
|
|
const [user, setUser] = useState(null)
|
|
|
|
const [isAuth, setIsAuth] = useState(false)
|
|
|
|
const [loginLoading, setLoginLoading] = useState(false)
|
|
|
|
const [messageLogin, setMessageLogin] = useState('')
|
2020-04-06 16:46:03 +02:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
useEffect(() => {
|
|
|
|
const newUser = cookies.get('user')
|
|
|
|
if (newUser != null) {
|
|
|
|
setIsAuth(true)
|
|
|
|
setUser(newUser)
|
|
|
|
}
|
|
|
|
}, [])
|
2020-04-08 15:26:18 +02:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
useEffect(() => {
|
|
|
|
if (isAuth) {
|
2020-08-03 14:14:45 +02:00
|
|
|
setMessageLogin(
|
|
|
|
'<p class="form-error"><b>Erreur:</b> Vous devez être déconnecter avant de vous connecter.</p>'
|
|
|
|
)
|
2020-08-03 12:04:07 +02:00
|
|
|
} else {
|
|
|
|
setMessageLogin('')
|
|
|
|
}
|
|
|
|
}, [isAuth])
|
|
|
|
|
|
|
|
const logoutUser = () => {
|
|
|
|
cookies.remove('user', { path: '/' })
|
|
|
|
setUser(null)
|
|
|
|
setIsAuth(false)
|
|
|
|
}
|
|
|
|
|
|
|
|
const loginUser = async ({ email, password }) => {
|
|
|
|
setLoginLoading(true)
|
|
|
|
try {
|
|
|
|
const response = await api.post('/users/login', { email, password })
|
|
|
|
const newUser = response.data
|
|
|
|
cookies.remove('user', { path: '/' })
|
|
|
|
cookies.set('user', newUser, { path: '/', maxAge: newUser.expiresIn })
|
|
|
|
setUser(newUser)
|
|
|
|
setIsAuth(true)
|
2020-08-03 14:14:45 +02:00
|
|
|
setMessageLogin(
|
|
|
|
'<p class="form-success"><b>Succès:</b> Connexion réussi!</p>'
|
|
|
|
)
|
2020-08-03 12:04:07 +02:00
|
|
|
setLoginLoading(false)
|
|
|
|
} catch (error) {
|
2020-08-03 14:14:45 +02:00
|
|
|
setMessageLogin(
|
|
|
|
`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`
|
|
|
|
)
|
2020-08-03 12:04:07 +02:00
|
|
|
setLoginLoading(false)
|
|
|
|
setIsAuth(false)
|
|
|
|
setUser(null)
|
2020-04-08 00:47:24 +02:00
|
|
|
}
|
2020-08-03 12:04:07 +02:00
|
|
|
}
|
2020-04-08 00:47:24 +02:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
return (
|
2020-08-03 14:14:45 +02:00
|
|
|
<UserContext.Provider
|
|
|
|
value={{
|
|
|
|
user,
|
|
|
|
loginUser,
|
|
|
|
logoutUser,
|
|
|
|
loginLoading,
|
|
|
|
messageLogin,
|
|
|
|
isAuth,
|
|
|
|
setMessageLogin
|
|
|
|
}}
|
|
|
|
>
|
2020-08-03 12:04:07 +02:00
|
|
|
{props.children}
|
|
|
|
</UserContext.Provider>
|
|
|
|
)
|
2020-04-06 16:46:03 +02:00
|
|
|
}
|
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
export default UserContextProvider
|