access.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { REMOTE_API_HOST, StoreKey } from "../constant";
  2. import { getClientConfig } from "../config/client";
  3. import { createPersistStore } from "../utils/store";
  4. import { getAuthKey } from "../client/common/auth";
  5. let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
  6. const DEFAULT_OPENAI_URL =
  7. getClientConfig()?.buildMode === "export" ? REMOTE_API_HOST : "/api/openai/";
  8. console.log("[API] default openai url", DEFAULT_OPENAI_URL);
  9. const DEFAULT_ACCESS_STATE = {
  10. accessCode: "",
  11. needCode: true,
  12. hideUserApiKey: false,
  13. hideBalanceQuery: false,
  14. disableGPT4: false,
  15. };
  16. export const useAccessStore = createPersistStore(
  17. { ...DEFAULT_ACCESS_STATE },
  18. (set, get) => ({
  19. enabledAccessControl() {
  20. this.fetchConfig();
  21. return get().needCode;
  22. },
  23. isAuthorized() {
  24. this.fetchConfig();
  25. // has token or has code or disabled access control
  26. return !!get().accessCode || !this.enabledAccessControl();
  27. },
  28. fetchConfig() {
  29. if (fetchState > 0 || getClientConfig()?.buildMode === "export") return;
  30. fetchState = 1;
  31. fetch("/api/config", {
  32. method: "post",
  33. body: null,
  34. headers: {
  35. Authorization: getAuthKey(),
  36. },
  37. })
  38. .then((res) => res.json())
  39. .then((res: DangerConfig) => {
  40. console.log("[Config] got config from server", res);
  41. set(() => ({ ...res }));
  42. if (res.disableGPT4) {
  43. // disable model
  44. }
  45. })
  46. .catch(() => {
  47. console.error("[Config] failed to fetch config");
  48. })
  49. .finally(() => {
  50. fetchState = 2;
  51. });
  52. },
  53. }),
  54. {
  55. name: StoreKey.Access,
  56. version: 1,
  57. },
  58. );