ChatGPT-Next-Web/app/store/access.ts

69 lines
1.6 KiB
TypeScript
Raw Normal View History

import { create } from "zustand";
import { persist } from "zustand/middleware";
2023-04-26 18:00:22 +00:00
import { StoreKey } from "../constant";
export interface AccessControlStore {
accessCode: string;
2023-03-26 11:58:25 +00:00
token: string;
2023-04-10 18:54:31 +00:00
needCode: boolean;
2023-03-26 11:58:25 +00:00
updateToken: (_: string) => void;
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-04-10 18:54:31 +00:00
let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
export const useAccessStore = create<AccessControlStore>()(
persist(
(set, get) => ({
2023-03-26 11:58:25 +00:00
token: "",
accessCode: "",
2023-04-10 18:54:31 +00:00
needCode: true,
enabledAccessControl() {
2023-04-10 18:54:31 +00:00
get().fetch();
return get().needCode;
},
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-04-26 18:00:22 +00:00
name: StoreKey.Access,
version: 1,
2023-04-09 15:51:12 +00:00
},
),
);