[FEATURE] Integrated Minecluster with Cairo & Established Gitea workflows (#12)

Co-authored-by: Dunemask <dunemask@gmail.com>
Reviewed-on: https://gitea.dunemask.dev/elysium/minecluster/pulls/12
This commit is contained in:
dunemask 2024-02-05 02:13:32 +00:00
parent edbfc2348a
commit 78c5b72482
30 changed files with 391 additions and 53 deletions

40
src/util/auth.js Normal file
View file

@ -0,0 +1,40 @@
import { useState, useContext, useEffect } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import SettingsContext from "@mcl/settings";
const verifyAuth = (authToken) =>
fetch("/api/auth/verify", {
headers: { Authorization: `Bearer ${authToken}` },
})
.then((res) => res.status === 200)
.catch(() => false);
export function useCairoAuth() {
const { state: settings, updateSettings } = useContext(SettingsContext);
const [auth, setAuth] = useState(!!settings.cairoAuth);
const [searchParams] = useSearchParams();
const nav = useNavigate();
useEffect(() => {
const webToken = searchParams.get("cairoAuthToken");
if (!webToken) return;
verifyAuth(webToken).then(setAuth);
updateSettings({ cairoAuth: webToken });
nav("/");
}, [searchParams]);
useEffect(() => {
verifyAuth(settings.cairoAuth).then(setAuth);
nav("/");
}, [settings.cairoAuth]);
return auth;
}
export function getAuthTokenFromStorage() {
return JSON.parse(localStorage.getItem("settings")).cairoAuth;
}
export function cairoAuthHeader() {
return { Authorization: `Bearer ${getAuthTokenFromStorage()}` };
}

View file

@ -1,12 +1,17 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { cairoAuthHeader } from "@mcl/util/auth.js";
const fetchApi = (subPath) => async () =>
fetch(`/api${subPath}`).then((res) => res.json());
fetch(`/api${subPath}`, { headers: cairoAuthHeader() }).then((res) =>
res.json(),
);
const fetchApiCore = async (subPath, json, method = "POST", jsonify = false) =>
fetch(`/api${subPath}`, {
method,
headers: {
"Content-Type": "application/json",
...cairoAuthHeader(),
},
body: JSON.stringify(json),
}).then((res) => (jsonify ? res.json() : res));
@ -16,6 +21,7 @@ const fetchApiPost = (subPath, json) => async () =>
method: "POST",
headers: {
"Content-Type": "application/json",
...cairoAuthHeader(),
},
body: JSON.stringify(json),
}).then((res) => res.json());
@ -117,6 +123,7 @@ const postJsonApi = (subPath, body, invalidate, method = "POST") => {
method,
headers: {
"Content-Type": "application/json",
...cairoAuthHeader(),
},
body: JSON.stringify(body),
});