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