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

75 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-07-10 15:19:43 +00:00
import { DEFAULT_API_HOST, DEFAULT_MODELS, StoreKey } from "../constant";
import { getHeaders } from "../client/api";
import { getClientConfig } from "../config/client";
import { createPersistStore } from "../utils/store";
2023-04-10 18:54:31 +00:00
let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
const DEFAULT_OPENAI_URL =
getClientConfig()?.buildMode === "export" ? DEFAULT_API_HOST : "/api/openai/";
console.log("[API] default openai url", DEFAULT_OPENAI_URL);
const DEFAULT_ACCESS_STATE = {
token: "",
accessCode: "",
needCode: true,
hideUserApiKey: false,
hideBalanceQuery: false,
disableGPT4: false,
disableFastLink: false,
2023-07-10 15:19:43 +00:00
openaiUrl: DEFAULT_OPENAI_URL,
};
export const useAccessStore = createPersistStore(
{ ...DEFAULT_ACCESS_STATE },
2023-04-10 18:54:31 +00:00
(set, get) => ({
enabledAccessControl() {
this.fetch();
2023-05-05 14:49:41 +00:00
return get().needCode;
},
isAuthorized() {
this.fetch();
// has token or has code or disabled access control
return (
!!get().token || !!get().accessCode || !this.enabledAccessControl()
);
},
fetch() {
if (fetchState > 0 || getClientConfig()?.buildMode === "export") return;
fetchState = 1;
fetch("/api/config", {
method: "post",
body: null,
headers: {
...getHeaders(),
},
})
.then((res) => res.json())
.then((res: DangerConfig) => {
console.log("[Config] got config from server", res);
set(() => ({ ...res }));
if (res.disableGPT4) {
DEFAULT_MODELS.forEach(
(m: any) => (m.available = !m.name.startsWith("gpt-4")),
);
}
})
.catch(() => {
console.error("[Config] failed to fetch config");
})
.finally(() => {
fetchState = 2;
});
2023-04-09 15:51:12 +00:00
},
}),
{
name: StoreKey.Access,
version: 1,
},
);