access.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. disableFastLink: false,
  17. customModels: "",
  18. openaiUrl: DEFAULT_OPENAI_URL,
  19. };
  20. export const useAccessStore = createPersistStore(
  21. { ...DEFAULT_ACCESS_STATE },
  22. (set, get) => ({
  23. enabledAccessControl() {
  24. this.fetch();
  25. return get().needCode;
  26. },
  27. isAuthorized() {
  28. this.fetch();
  29. // has token or has code or disabled access control
  30. return (
  31. !!get().token || !!get().accessCode || !this.enabledAccessControl()
  32. );
  33. },
  34. fetch() {
  35. if (fetchState > 0 || getClientConfig()?.buildMode === "export") return;
  36. fetchState = 1;
  37. fetch("/api/config", {
  38. method: "post",
  39. body: null,
  40. headers: {
  41. ...getHeaders(),
  42. },
  43. })
  44. .then((res) => res.json())
  45. .then((res: DangerConfig) => {
  46. console.log("[Config] got config from server", res);
  47. set(() => ({ ...res }));
  48. })
  49. .catch(() => {
  50. console.error("[Config] failed to fetch config");
  51. })
  52. .finally(() => {
  53. fetchState = 2;
  54. });
  55. },
  56. }),
  57. {
  58. name: StoreKey.Access,
  59. version: 1,
  60. },
  61. );