access.ts 1.8 KB

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