2023-03-26 06:53:40 +00:00
|
|
|
import { create } from "zustand";
|
|
|
|
import { persist } from "zustand/middleware";
|
|
|
|
|
|
|
|
export interface AccessControlStore {
|
|
|
|
accessCode: string;
|
2023-03-26 11:58:25 +00:00
|
|
|
token: string;
|
2023-03-26 06:53:40 +00:00
|
|
|
|
2023-04-10 18:54:31 +00:00
|
|
|
needCode: boolean;
|
|
|
|
|
2023-03-26 11:58:25 +00:00
|
|
|
updateToken: (_: string) => void;
|
2023-03-26 06:53:40 +00:00
|
|
|
updateCode: (_: string) => void;
|
|
|
|
enabledAccessControl: () => boolean;
|
2023-04-09 15:51:12 +00:00
|
|
|
isAuthorized: () => boolean;
|
2023-04-10 18:54:31 +00:00
|
|
|
fetch: () => void;
|
2023-03-26 06:53:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export const ACCESS_KEY = "access-control";
|
|
|
|
|
2023-04-10 18:54:31 +00:00
|
|
|
let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
|
|
|
|
|
2023-03-26 06:53:40 +00:00
|
|
|
export const useAccessStore = create<AccessControlStore>()(
|
|
|
|
persist(
|
|
|
|
(set, get) => ({
|
2023-03-26 11:58:25 +00:00
|
|
|
token: "",
|
2023-03-26 06:53:40 +00:00
|
|
|
accessCode: "",
|
2023-04-10 18:54:31 +00:00
|
|
|
needCode: true,
|
2023-03-26 06:53:40 +00:00
|
|
|
enabledAccessControl() {
|
2023-04-10 18:54:31 +00:00
|
|
|
get().fetch();
|
|
|
|
|
|
|
|
return get().needCode;
|
2023-03-26 06:53:40 +00:00
|
|
|
},
|
|
|
|
updateCode(code: string) {
|
|
|
|
set((state) => ({ accessCode: code }));
|
|
|
|
},
|
2023-03-26 11:58:25 +00:00
|
|
|
updateToken(token: string) {
|
|
|
|
set((state) => ({ token }));
|
|
|
|
},
|
2023-04-09 15:51:12 +00:00
|
|
|
isAuthorized() {
|
2023-04-10 02:57:16 +00:00
|
|
|
// has token or has code or disabled access control
|
2023-04-10 17:21:34 +00:00
|
|
|
return (
|
|
|
|
!!get().token || !!get().accessCode || !get().enabledAccessControl()
|
|
|
|
);
|
2023-04-09 15:51:12 +00:00
|
|
|
},
|
2023-04-10 18:54:31 +00:00
|
|
|
fetch() {
|
|
|
|
if (fetchState > 0) return;
|
|
|
|
fetchState = 1;
|
|
|
|
fetch("/api/config", {
|
|
|
|
method: "post",
|
|
|
|
body: null,
|
|
|
|
})
|
|
|
|
.then((res) => res.json())
|
|
|
|
.then((res: DangerConfig) => {
|
|
|
|
console.log("[Config] got config from server", res);
|
|
|
|
set(() => ({ ...res }));
|
|
|
|
})
|
|
|
|
.catch(() => {
|
|
|
|
console.error("[Config] failed to fetch config");
|
|
|
|
})
|
|
|
|
.finally(() => {
|
|
|
|
fetchState = 2;
|
|
|
|
});
|
|
|
|
},
|
2023-03-26 06:53:40 +00:00
|
|
|
}),
|
|
|
|
{
|
|
|
|
name: ACCESS_KEY,
|
|
|
|
version: 1,
|
2023-04-09 15:51:12 +00:00
|
|
|
},
|
|
|
|
),
|
2023-03-26 06:53:40 +00:00
|
|
|
);
|