access.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import {
  2. ApiPath,
  3. DEFAULT_API_HOST,
  4. ServiceProvider,
  5. StoreKey,
  6. } from "../constant";
  7. import { getHeaders } from "../client/api";
  8. import { getClientConfig } from "../config/client";
  9. import { createPersistStore } from "../utils/store";
  10. import { ensure } from "../utils/clone";
  11. import dayjs from "dayjs";
  12. let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
  13. const DEFAULT_OPENAI_URL =
  14. getClientConfig()?.buildMode === "export" ? DEFAULT_API_HOST : ApiPath.OpenAI;
  15. const DEFAULT_ACCESS_STATE = {
  16. accessCode: "",
  17. useCustomConfig: false,
  18. provider: ServiceProvider.Oauth,
  19. // openai
  20. openaiUrl: DEFAULT_OPENAI_URL,
  21. openaiApiKey: "",
  22. // oauth2
  23. accessToken: "",
  24. expiresIn: 0,
  25. tokenType: "bearer",
  26. // azure
  27. azureUrl: "",
  28. azureApiKey: "",
  29. azureApiVersion: "2023-08-01-preview",
  30. // server config
  31. needCode: true,
  32. hideUserApiKey: false,
  33. hideBalanceQuery: false,
  34. disableGPT4: false,
  35. disableFastLink: false,
  36. customModels: "",
  37. };
  38. export const useAccessStore = createPersistStore(
  39. { ...DEFAULT_ACCESS_STATE },
  40. (set, get) => ({
  41. enabledAccessControl() {
  42. this.fetch();
  43. return get().needCode;
  44. },
  45. clearToken() {
  46. set(() => ({
  47. accessToken: "",
  48. expiresIn: 0,
  49. tokenType: "bearer",
  50. }));
  51. },
  52. setAccessToken(token: any) {
  53. set(() => ({ ...token }));
  54. },
  55. hasAccessToken() {
  56. const state = get();
  57. if (state.provider == ServiceProvider.Oauth) {
  58. return !!state.accessToken?.length && dayjs().unix() < state.expiresIn;
  59. }
  60. return false;
  61. },
  62. isValidOpenAI() {
  63. return ensure(get(), ["openaiApiKey"]);
  64. },
  65. isValidAzure() {
  66. return ensure(get(), ["azureUrl", "azureApiKey", "azureApiVersion"]);
  67. },
  68. isAuthorized() {
  69. this.fetch();
  70. // has token or has code or disabled access control
  71. return (
  72. this.isValidOpenAI() ||
  73. this.isValidAzure() ||
  74. !this.enabledAccessControl() ||
  75. (this.enabledAccessControl() && ensure(get(), ["accessCode"]))
  76. );
  77. },
  78. fetch() {
  79. if (fetchState > 0 || getClientConfig()?.buildMode === "export") return;
  80. fetchState = 1;
  81. fetch("/api/config", {
  82. method: "post",
  83. body: null,
  84. headers: {
  85. ...getHeaders(),
  86. },
  87. })
  88. .then((res) => res.json())
  89. .then((res: DangerConfig) => {
  90. console.log("[Config] got config from server", res);
  91. set(() => ({ ...res }));
  92. })
  93. .catch(() => {
  94. console.error("[Config] failed to fetch config");
  95. })
  96. .finally(() => {
  97. fetchState = 2;
  98. });
  99. },
  100. }),
  101. {
  102. name: StoreKey.Access,
  103. version: 2,
  104. migrate(persistedState, version) {
  105. if (version < 2) {
  106. const state = persistedState as {
  107. token: string;
  108. openaiApiKey: string;
  109. azureApiVersion: string;
  110. };
  111. state.openaiApiKey = state.token;
  112. state.azureApiVersion = "2023-08-01-preview";
  113. }
  114. return persistedState as any;
  115. },
  116. },
  117. );