From 5a4fe66e49609a23ac0cc15205d59a5609a33aac Mon Sep 17 00:00:00 2001 From: Mathias Wagner Date: Tue, 27 Dec 2022 15:26:06 +0100 Subject: [PATCH] Created the LoginContext.jsx --- .../common/contexts/Login/LoginContext.jsx | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 admin/src/common/contexts/Login/LoginContext.jsx diff --git a/admin/src/common/contexts/Login/LoginContext.jsx b/admin/src/common/contexts/Login/LoginContext.jsx new file mode 100644 index 0000000..8ab9902 --- /dev/null +++ b/admin/src/common/contexts/Login/LoginContext.jsx @@ -0,0 +1,41 @@ +import React, {createContext, useEffect, useState} from "react"; +import {request} from "@/common/utils/RequestUtil"; +import Login from "@/pages/Login"; + +export const LoginContext = createContext({}); + +export const LoginProvider = (props) => { + + const [token, setToken] = useState(localStorage.getItem("token") || null); + const [renderPage, setRenderPage] = useState(0); + + const checkLogin = () => { + request("/info/status").then(res => { + if (res.status === 401 || res.status === 400) throw 1; + if (!res.ok) throw 2; + }).then(() => setRenderPage(1)).catch((e) => { + if (e === 2) return; + setRenderPage(2); + setToken(null); + }); + } + + const tokenUpdate = () => { + if (token === null) { + localStorage.removeItem("token"); + setRenderPage(2); + return; + } + localStorage.setItem("token", token); + checkLogin(); + } + + useEffect(tokenUpdate, [token]); + + return ( + + {renderPage === 2 && } + {renderPage === 1 && props.children} + + ) +} \ No newline at end of file