access.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { DEFAULT_API_HOST, DEFAULT_MODELS, StoreKey } from "../constant";
  2. import { getHeaders } from "../client/api";
  3. import { getClientConfig } from "../config/client";
  4. import { createPersistStore } from "../utils/store";
  5. let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
  6. const DEFAULT_OPENAI_URL =
  7. getClientConfig()?.buildMode === "export" ? DEFAULT_API_HOST : "/api/openai/";
  8. console.log("[API] default openai url", DEFAULT_OPENAI_URL);
  9. const DEFAULT_ACCESS_STATE = {
  10. token: "",
  11. accessCode: "",
  12. needCode: true,
  13. hideUserApiKey: false,
  14. hideBalanceQuery: false,
  15. disableGPT4: false,
  16. openaiUrl: DEFAULT_OPENAI_URL,
  17. };
  18. export const useAccessStore = createPersistStore(
  19. { ...DEFAULT_ACCESS_STATE },
  20. (set, get) => ({
  21. enabledAccessControl() {
  22. this.fetch();
  23. return get().needCode;
  24. },
  25. updateCode(code: string) {
  26. set(() => ({ accessCode: code?.trim() }));
  27. },
  28. updateToken(token: string) {
  29. set(() => ({ token: token?.trim() }));
  30. },
  31. updateOpenAiUrl(url: string) {
  32. set(() => ({ openaiUrl: url?.trim() }));
  33. },
  34. isAuthorized() {
  35. this.fetch();
  36. // has token or has code or disabled access control
  37. return (
  38. !!get().token || !!get().accessCode || !this.enabledAccessControl()
  39. );
  40. },
  41. fetch() {
  42. if (fetchState > 0 || getClientConfig()?.buildMode === "export") return;
  43. fetchState = 1;
  44. fetch("/api/config", {
  45. method: "post",
  46. body: null,
  47. headers: {
  48. ...getHeaders(),
  49. },
  50. })
  51. .then((res) => res.json())
  52. .then((res: DangerConfig) => {
  53. console.log("[Config] got config from server", res);
  54. set(() => ({ ...res }));
  55. if (res.disableGPT4) {
  56. DEFAULT_MODELS.forEach(
  57. (m: any) => (m.available = !m.name.startsWith("gpt-4")),
  58. );
  59. }
  60. })
  61. .catch(() => {
  62. console.error("[Config] failed to fetch config");
  63. })
  64. .finally(() => {
  65. fetchState = 2;
  66. });
  67. },
  68. }),
  69. {
  70. name: StoreKey.Access,
  71. version: 1,
  72. },
  73. );