Generateurv2/frontend/context/session.context.js

95 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-06-11 23:39:03 +02:00
import { useRouter } from "next/router";
2022-06-24 13:42:16 +02:00
import { createContext, useContext, useEffect, useRef, useState } from "react";
2022-06-11 23:39:03 +02:00
import ReconnectingWebSocket from "reconnecting-websocket";
2022-06-24 13:42:16 +02:00
import {
getUser,
loginRequest,
logoutRequest,
} from "../requests/requests.users.js";
import { notificationService } from "../services/notification.service.js";
2022-06-11 23:39:03 +02:00
import { isBrowser } from "../utils/utils.js";
2022-06-24 13:42:16 +02:00
export const SessionContext = createContext({
isLogin: false,
login: () => {},
logout: () => {},
authData: {},
});
2022-06-11 23:39:03 +02:00
export const useSessionContext = () => {
return useContext(SessionContext);
};
export const SessionProvider = ({ children }) => {
2022-06-24 13:42:16 +02:00
const [authData, setAuthData] = useState();
const [isLogin, setLogin] = useState(
isBrowser && localStorage.getItem("token") !== null
);
useEffect(() => {
setLogin(isBrowser && localStorage.getItem("token") !== null);
}, []);
const router = useRouter();
const login = (token) => {
//data = {username: "", password1: "", password2: ""}
2022-06-11 23:39:03 +02:00
localStorage.clear();
localStorage.setItem("token", token);
2022-06-24 13:42:16 +02:00
setLogin(true);
};
2022-06-11 23:39:03 +02:00
const logout = () => {
2022-06-24 13:42:16 +02:00
if (localStorage.getItem("token") !== null) {
logoutRequest(localStorage.getItem("token"))
.then(() => {
localStorage.setItem("token", null);
if (router.route == "/dashboard") {
router.push("/login");
}
})
.then((res) => {
setAuthData({});
setLogin(false);
notificationService.success(
"Déconnexion",
"Vous n'êtes plus connecté !",
{ keepAfterRouteChange: true }
);
})
.catch((err) => {
notificationService.error(
"Déconnexion",
"Erreur lors de la déconnexion !",
{ keepAfterRouteChange: true }
);
});
}
};
useEffect(() => {
if (localStorage.getItem("token") != null) {
getUser()
.then((res) => {
setAuthData(res);
})
.catch((err) => {
localStorage.clear();
});
} else {
setAuthData({})
2022-06-11 23:39:03 +02:00
}
2022-06-24 13:42:16 +02:00
}, [isBrowser && localStorage.getItem("token")]);
2022-06-11 23:39:03 +02:00
return (
<SessionContext.Provider
value={{
isLogin,
login,
2022-06-24 13:42:16 +02:00
logout,
authData,
2022-06-11 23:39:03 +02:00
}}
>
{children}
</SessionContext.Provider>
);
};