NextChat-U/app/store/access.ts

70 lines
1.7 KiB
TypeScript
Raw Normal View History

import { create } from "zustand";
import { persist } from "zustand/middleware";
2023-04-27 03:00:22 +09:00
import { StoreKey } from "../constant";
2023-05-04 00:08:37 +09:00
import { BOT_HELLO } from "./chat";
export interface AccessControlStore {
accessCode: string;
2023-03-26 20:58:25 +09:00
token: string;
2023-04-11 03:54:31 +09:00
needCode: boolean;
2023-03-26 20:58:25 +09:00
updateToken: (_: string) => void;
updateCode: (_: string) => void;
enabledAccessControl: () => boolean;
2023-04-10 00:51:12 +09:00
isAuthorized: () => boolean;
2023-04-11 03:54:31 +09:00
fetch: () => void;
}
2023-04-11 03:54:31 +09:00
let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
export const useAccessStore = create<AccessControlStore>()(
persist(
(set, get) => ({
2023-03-26 20:58:25 +09:00
token: "",
accessCode: "",
2023-04-11 03:54:31 +09:00
needCode: true,
enabledAccessControl() {
2023-04-11 03:54:31 +09:00
get().fetch();
return get().needCode;
},
updateCode(code: string) {
set((state) => ({ accessCode: code }));
},
2023-03-26 20:58:25 +09:00
updateToken(token: string) {
set((state) => ({ token }));
},
2023-04-10 00:51:12 +09:00
isAuthorized() {
2023-04-10 11:57:16 +09:00
// has token or has code or disabled access control
2023-04-11 02:21:34 +09:00
return (
!!get().token || !!get().accessCode || !get().enabledAccessControl()
);
2023-04-10 00:51:12 +09:00
},
2023-04-11 03:54:31 +09: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-04-27 03:00:22 +09:00
name: StoreKey.Access,
version: 1,
2023-04-10 00:51:12 +09:00
},
),
);