[FIX] Enable Correct Production Hooks (#13)
Co-authored-by: Dunemask <dunemask@gmail.com> Reviewed-on: https://gitea.dunemask.dev/elysium/minecluster/pulls/13
This commit is contained in:
parent
40b3a42c73
commit
1eaa7ff5a5
1 changed files with 24 additions and 17 deletions
|
@ -1,6 +1,8 @@
|
|||
import { useState, useContext, useEffect } from "react";
|
||||
import { useSearchParams, useNavigate } from "react-router-dom";
|
||||
import SettingsContext from "@mcl/settings";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
|
||||
const tokenStorageName = "cairoAuthToken";
|
||||
const tokenQuery = "cairoAuthToken";
|
||||
|
||||
const verifyAuth = (authToken) =>
|
||||
fetch("/api/auth/verify", {
|
||||
|
@ -10,29 +12,34 @@ const verifyAuth = (authToken) =>
|
|||
.catch(() => false);
|
||||
|
||||
export function useCairoAuth() {
|
||||
const { state: settings, updateSettings } = useContext(SettingsContext);
|
||||
const [auth, setAuth] = useState(!!settings.cairoAuth);
|
||||
const [searchParams] = useSearchParams();
|
||||
const nav = useNavigate();
|
||||
const [authToken, setAuthToken] = useState(
|
||||
localStorage.getItem(tokenStorageName),
|
||||
);
|
||||
const [auth, setAuth] = useState(false);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
const webToken = searchParams.get("cairoAuthToken");
|
||||
if (!authToken) return;
|
||||
verifyAuth(authToken).then((authorized) => {
|
||||
if (!authorized) localStorage.removeItem(tokenStorageName);
|
||||
setAuth(authorized);
|
||||
});
|
||||
}, [authToken]);
|
||||
|
||||
useEffect(() => {
|
||||
const webToken = searchParams.get(tokenQuery);
|
||||
if (!webToken) return;
|
||||
verifyAuth(webToken).then(setAuth);
|
||||
updateSettings({ cairoAuth: webToken });
|
||||
nav("/");
|
||||
localStorage.setItem(tokenStorageName, webToken);
|
||||
searchParams.delete(tokenQuery);
|
||||
setAuthToken(webToken);
|
||||
setSearchParams(searchParams);
|
||||
}, [searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
verifyAuth(settings.cairoAuth).then(setAuth);
|
||||
nav("/");
|
||||
}, [settings.cairoAuth]);
|
||||
|
||||
return auth;
|
||||
}
|
||||
|
||||
export function getAuthTokenFromStorage() {
|
||||
return JSON.parse(localStorage.getItem("settings")).cairoAuth;
|
||||
return localStorage.getItem(tokenStorageName);
|
||||
}
|
||||
|
||||
export function cairoAuthHeader() {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue