access.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { REMOTE_API_HOST, DEFAULT_MODELS, StoreKey } from "../constant";
  2. import { getClientConfig } from "../config/client";
  3. import { createPersistStore } from "../utils/store";
  4. import { getAuthHeaders } 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. ...getAuthHeaders(),
  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. DEFAULT_MODELS.forEach(
  44. (m: any) => (m.available = !m.name.startsWith("gpt-4")),
  45. );
  46. }
  47. })
  48. .catch(() => {
  49. console.error("[Config] failed to fetch config");
  50. })
  51. .finally(() => {
  52. fetchState = 2;
  53. });
  54. },
  55. }),
  56. {
  57. name: StoreKey.Access,
  58. version: 1,
  59. },
  60. );